invalid literal with int base 10 for only one input in list, when all others work (postfix)

Viewed 49
expr = '5 3 -'

lyst = ['4', '5 7 +', '7 5 *', '5 3 -', '5 5 /', '8 5 * 3 +', '8 5 3 + *', '8 3 5 * + 7 -', '8 3 + 5 6 - *', '8 3 + 2 7 - *', '8 3 + 2 * 7 -', '8 5 * 3 2 - 7 3 * - +', '8 5 * 3 + 7 - 5 3 * -', '7 9 * 7 + 5 6 * - 3 + 4 -']

def eval_postfix(expr):
    import re
    token_list = re.split("([^0-9])", expr)
    stack = Stack()
    for token in token_list:
        if token == "" or token == " ":
            continue
        if token == "+":
            sum = stack.pop() + stack.pop()
            stack.push(sum)
        elif token == "*":
            product = stack.pop() * stack.pop()
            stack.push(product)
        else:
            stack.push(int(token))
    return stack.pop()
print(eval_postfix(expr))

So i have this list of postfix expressions, and i am trying to evaluate it.

All of the inputs work, except for the '5 3 -' input. It is pulling a invalid literal for int base 10. Now i know this error is usually when something recieves something that is not supposed to be an integer, but this doesn't seeem to be the case.

stack.push(int(token))
ValueError: invalid literal for int() with base 10: '-'

any help or insight would be very helpful.

1 Answers

Converting - to an int will raise an error.

>>> int('-')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '-'

So you can fix your code by handling - as another operator. You are already doing so for + and *, so it is just another condition to check for. Remember that the subtraction operands come off the stack out of order!

expr = '5 3 -'

lyst = ['4', '5 7 +', '7 5 *', '5 3 -', '5 5 /', '8 5 * 3 +', '8 5 3 + *', '8 3 5 * + 7 -', '8 3 + 5 6 - *', '8 3 + 2 7 - *', '8 3 + 2 * 7 -', '8 5 * 3 2 - 7 3 * - +', '8 5 * 3 + 7 - 5 3 * -', '7 9 * 7 + 5 6 * - 3 + 4 -']

def eval_postfix(expr):
    import re
    token_list = re.split("([^0-9])", expr)
    stack = Stack()
    for token in token_list:
        if token == "" or token == " ":
            continue
        if token == "+":
            sum = stack.pop() + stack.pop()
            stack.push(sum)
        elif token == "*":
            product = stack.pop() * stack.pop()
            stack.push(product)
        # extra condition here to handle subtraction
        elif token == "-":
            second_operand = stack.pop()
            difference = stack.pop() - second_operand
            stack.push(difference)
        else:
            print(token)
            stack.push(int(token))
    return stack.pop()
print(eval_postfix(expr))

It still does not not handle /, but this can be solved in the same way as subtraction.

Related