为什么我无法在 while 循环内更改索引?

发布于 2025-01-11 22:55:02 字数 1575 浏览 0 评论 0原文

我想在Python中实现只包含数字、“+”和“-”的基本计算器。但我发现我无法在 while 循环内更改索引 i 。

def basicCalculator(expression):
    res = 0
    sign = 1
    i = 0
    while i < len(expression): # using while loop here
        if expression[i] == '+':
            sign = 1
        elif expression[i] == '-':
            sign = -1
        elif '0' <= expression[i] <= '9':
            temp = int(expression[i])
            while i + 1 < len(expression) and '0' <= expression[i + 1] <= '9':
                i += 1             # want to increase i, but failed
                temp = temp * 10 + int(expression[i])
            res += sign * temp
    return res

s = "2+3-999"
print(basicCalculator(s))    # ouput should be -994, but infinite

然后我尝试了另一种方法:使用for循环而不是while循环,得到错误的答案。

def basicCalculator(expression):
    res = 0
    sign = 1
    for i in range(len(expression)):  # using for loop
        if expression[i] == '+':
            sign = 1
        elif expression[i] == '-':
            sign = -1
        elif '0' <= expression[i] <= '9':
            temp = int(expression[i])
            while i + 1 < len(expression) and '0' <= expression[i + 1] <= '9':
                i += 1                    # increase i
                temp = temp * 10 + int(expression[i])
            res += sign * temp
    return res

s = "2+3-999"
print(basicCalculator(s))    # ouput should be -994, but got -1102

我不知道为什么我无法更改 while 循环或 for 循环内的索引。在 for 循环中改变 i 不是一个好主意。修复该错误的最佳方法是什么? (我使用方法 2 在 Java 中编写了相同的代码,一切都很好,有什么区别吗?)

I want to implement basic calculator only includes numbers, '+' and '-' in Python. But I found that I cannot change index i inside the while loop.

def basicCalculator(expression):
    res = 0
    sign = 1
    i = 0
    while i < len(expression): # using while loop here
        if expression[i] == '+':
            sign = 1
        elif expression[i] == '-':
            sign = -1
        elif '0' <= expression[i] <= '9':
            temp = int(expression[i])
            while i + 1 < len(expression) and '0' <= expression[i + 1] <= '9':
                i += 1             # want to increase i, but failed
                temp = temp * 10 + int(expression[i])
            res += sign * temp
    return res

s = "2+3-999"
print(basicCalculator(s))    # ouput should be -994, but infinite

Then I tried another way: using for loop instead of while loop, get incorrect answer.

def basicCalculator(expression):
    res = 0
    sign = 1
    for i in range(len(expression)):  # using for loop
        if expression[i] == '+':
            sign = 1
        elif expression[i] == '-':
            sign = -1
        elif '0' <= expression[i] <= '9':
            temp = int(expression[i])
            while i + 1 < len(expression) and '0' <= expression[i + 1] <= '9':
                i += 1                    # increase i
                temp = temp * 10 + int(expression[i])
            res += sign * temp
    return res

s = "2+3-999"
print(basicCalculator(s))    # ouput should be -994, but got -1102

I don't know why I cannot change the index inside the while loop or for loop. It is not a good idea to change i in for loop. What is the best way to fix the bug?
(I wrote the same code in Java using approach 2, everything is good, any difference?)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

遗心遗梦遗幸福 2025-01-18 22:55:02

我建议不要在循环内的循环中递增索引,而是在主循环中累加当前数字,这样您就无需跟踪:

def basicCalculator(expression):
    res = 0
    sign = 1
    num = ""
    for c in expression:
        if c.isdecimal():
            num += c
            continue
        res += int(num) * sign
        num = ""
        if c == "+":
            sign = 1
        elif c == "-":
            sign = -1
        else:
            raise ValueError(f"Invalid operator {c}")
    return res + int(num) * sign

print(basicCalculator("2+3-999"))  # -994

Rather than incrementing the index in a loop within the loop, I suggest just accumulating the current number in the main loop so you have less to keep track of:

def basicCalculator(expression):
    res = 0
    sign = 1
    num = ""
    for c in expression:
        if c.isdecimal():
            num += c
            continue
        res += int(num) * sign
        num = ""
        if c == "+":
            sign = 1
        elif c == "-":
            sign = -1
        else:
            raise ValueError(f"Invalid operator {c}")
    return res + int(num) * sign

print(basicCalculator("2+3-999"))  # -994
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文