Please give me an answer regarding the method of calculating the median potential

Asked 2 years ago, Updated 2 years ago, 18 views

class Node:
    def __init__(self,item,link):
        self.item=item
        self.next=link

def push(item):
        global top
        global size
        top = Node(item, top)
        size += 1

def peek():
        if size != 0:
            return top.item

def pop():
        global top
        global size
        if size != 0:
            top_item = top.item
            top = top.next
            size -= 1
            return top_item

def print_stack():
        print('top -> \t',end='')
        p = top
        while p:
            if p.next != None:
                print(p.item,end='')
                print(" ")
            else:
                print(p.item,end='')
                print(" ")
            p = p.next
        print()
top = None
size = 0

So that's the code I've shown you, and the goal is to use that code to calculate the potential, the median, and the posterior using the stack

temp1=0
temp2=0
postfix='4 4 3 * / 2 + 3 -'
for i in postfix:
    if i == '1':
        push(1)
    elif i == '2':
        push(2)
    elif i == '3':
        push(3)
    elif i == '4':
        push(4)
    elif i == '5':
        push(5)
    elif i == '6':
        push(6)
    elif i == '7':
        push(7)
    elif i == '8':
        push(8)
    elif i == '9':
        push(9)
    elif i == ' ':
        continue
    elif i == '+':
        temp2=pop()
        temp1=pop()
        push(temp1+temp2)
    elif i == '-':
        temp2=pop()
        temp1=pop()
        push(temp1-temp2)
    elif i == '*':
        temp2=pop()
        temp1=pop()
        push(temp1*temp2)
    elif i == '/':
        temp2=pop()
        temp1=pop()
        push(int(temp1/temp2))

    print_stack()
print("result = " + str(pop()))

This is a posteriori calculation that I made, and how do I do the translocation and the median calculation in this way?;

python

2022-09-22 19:22

1 Answers

Isn't it okay to change the order of pop/push for the lieutenant?

    elif i == '+':
        temp2=pop()
        push(temp1+temp2)
        temp1=pop()
    elif i == '-':
        temp2=pop()
        push(temp1-temp2)
        temp1=pop()
    elif i == '*':
        temp1=pop()
        push(temp1*temp2)
        temp2=pop()
    elif i == '/':
        temp1=pop()
        push(int(temp1/temp2))
        temp2=pop()

Have you done it like this?


2022-09-22 19:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.