Python为什么将13/5返回为0?(正在解决逆波兰表达式问题)

huangapple go评论56阅读模式
英文:

Why is python returning 13/5 as 0? (working on reverse polish notation problem)

问题

我在LeetCode上解决这个问题,但它一直在错误地进行除法运算。

s = []

for token in tokens:
    print(s)
    if token.isnumeric():
        s.append(int(token))
    else:
        a = s.pop()
        b = s.pop()
        if token == '+':
            s.append(a + b)
        elif token == '-':
            s.append(a - b)
        elif token == '*':
            s.append(a * b)
        elif token == '/':
            print(int(a / b)) # 这里应该是int(a / b)
            s.append(int(a / b))
return s.pop()

当我打印这个时:

[4]
[4, 13]
[4, 13, 5]
0 <- 这里应该是2
[4, 0]
英文:

I'm working on this problem in leet code and it keeps doing division incorrectly.

    s = []
    
    for token in tokens:
        print(s)
        if token.isnumeric():
            s.append(int(token))
        else:
            a=s.pop()
            b=s.pop()
            if token == &#39;+&#39;:
                s.append(a+b)
            elif token == &#39;-&#39;:
                s.append(a-b)
            elif token == &#39;*&#39;:
                s.append(a*b)
            elif token == &#39;/&#39;:
                print(int(a/b))
                s.append(int(a/b))
    return s.pop()`

when i print this:

    [4]
    [4, 13]
    [4, 13, 5]
    0 &lt;- this should be 2
    [4, 0]

答案1

得分: 5

你在进行反向操作。

[4, 13, 5]
a = s.pop() # a现在是5
[4, 13]
b = s.pop() # b现在是13
[4]
int(a/b) # 5 // 13 = 0

你可能要考虑反转你的弹出操作,或者反转你的除法。

英文:

You are dividing backwards.

[4, 13, 5]
a = s.pop() # a is now 5
[4, 13]
b = s.pop() # b is now 13
[4]
int(a/b) # 5 // 13 = 0

You either want to reverse your pops, or reverse your division.

huangapple
  • 本文由 发表于 2023年2月10日 03:34:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75403589.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定