Python Stack Question!

Asked 1 years ago, Updated 1 years ago, 111 views

Hello. I'm implementing a calculator using a stack.

If you enter only integers now, the problem is saved to the list as a string. ex) 1+2/3 [1,+,2,/,3]
But I'm asking you a question because I'm trying to save the mistake.
ex)1.2+3/4 The value I want [1.2,+,3,/,4]
It doesn't come out well even if I google it. I'd appreciate your help.
The part that I'm coding right now is elif token in '.':.
I tried to add the front and the back based on the string when the string . came in. But I don't think that's right, so I'm asking.

class Stack:
    def __init__(self):
        self.items = []

    def push(self, val):
        self.items.append(val)

    def pop(self):
        try:
            return self.items.pop()
        except IndexError:
            print("Stack is empty")
    def top(self):
        try:
            return self.items[-1]
        except IndexError:
            print("Stack is empty")

    def __len__(self):
        return len(self.items)

    def isEmpty(self):
        return self.__len__() == 0  

def get_token_list(expr):
    opstack = Stack()
    outstack = []
    token_list = expr

    for token in token_list:
        print(token)
        if token == '(':
            opstack.push(token)
        elif token == ')':
            opstack.push(token)
        eliftoken in '+-/*^': pop an operator higher than oneself in #opstack
            #while (not opstack.isEmpty()) and \
            #(prec[opstack.top()] >= prec[token]):
            #outstack.append(opstack.pop())
                #print(outstack)
                # # print(opstack)
            opstack.push(token)
        elif token in '.':
            outstack.append(opstack.top()+token)
            opstack.push(token)
        if opstack.pop() == '.': #
            outstack.append(opstack.pop()+opstack.top()+token)
        opstack.push(token)

        #outstack.append(opstack.top())
        #if outstack in '.':
        #    #    outstack.append(str(opstack.pop()+'.'+opstack.pop()))
    outstack.append(opstack.pop())
    return print(outstack)

expr = input()
value = get_token_list(expr)
#value = compute_postfix(infix_to_postfix(get_token_list(expr)))
#print(value)

python stack

2022-09-21 11:18

1 Answers

Can I know how you solved it? I'd like to see some coding ㅠ<


2022-09-21 11:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.