计算器减法导致无限循环

2024-09-25 12:38:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个计算器,它可以接受用户的输入。 它必须解决以下表达式:

1+38*(!2)-5%37

我一直在做加法和减法,但遇到了一个问题。在

我有一个寻找“+”或“-”符号的循环。 对于“+”它有效,但是对于“-”来说,每当我解一个像

1-38

它让我进入一个无限循环,因为这个表达式的结果是

-37

循环继续将“-”符号识别为减法,但将其识别为负37。在

我如何解决这个问题?在

def symbols_exist(exp, symbols_list):
    """ Gets an expression string and a symbols list and returns true if any symbol
        exists in the expression, else returns false. """
    for s in symbols_list:
        if s in exp:
            return True
    return False

def BinaryOperation(exp, idx):
    """ Gets an expression and an index of an operator and returns a tuple with (first_value, operator, second_value). """
    first_value = 0
    second_value = 0

    #Get first value
    idx2 = idx -1
    while (idx2 > 0) and (exp[idx2] in string.digits):
        idx2 -=1

    first_value = exp[idx2:idx]

    #Get second value
    idx2 = idx +1
    while (idx2 < len(exp)) and (exp[idx2] in string.digits):
        idx2 += 1

    second_value = exp[idx+1:idx2]

    return (first_value, exp[idx], second_value)

def solve(exp):
    if not symbols_exist(exp, all_symbols):
        return exp

    idx = 0

    while idx < len(exp):
        if exp[idx] in string.digits:
            #Digit
            idx +=1
        elif exp[idx] in ("+", "-"):
            #Addition and Subtraction
            sub_exp = BinaryOperation(exp, idx)
            if sub_exp[1] == "+":
                value = int(sub_exp[0]) + int(sub_exp[2])
            else:
                value = int(sub_exp[0]) - int(sub_exp[2])

            value = str(value)

            exp = exp.replace(''.join(sub_exp), value)
            print exp

        return solve(exp)

Tags: andinanstringreturnifvaluedef
1条回答
网友
1楼 · 发布于 2024-09-25 12:38:02

将原始示例中的三个函数结合起来的一种可能的解决方案。(编辑:刚意识到我发布的原始答案可以简化不少)

all_symbols = '+-'
def solve(expres):
    lhs, symbol, rhs = expres[0], None, ''
    for ch in expres[1:]:
        if symbol:
            rhs += ch
        elif ch in all_symbols:
            symbol = ch
        else:
            lhs += ch
    if symbol is '+':
        return int(lhs) + solve(rhs)
    if symbol is '-':
        return int(lhs) - solve(rhs)
    return int(expres)

print solve('1+5')

以及另一种可能有用的解决方案

^{pr2}$

相关问题 更多 >