我需要从给定的字符串中评估表达式,例如“(19 +((91 -96)-13))”但我必须自己制作te算法,我不能使用eval()或其他东西类似。
我已经尝试了很多这个代码,但它给了我带负数的问题:
while counter < 1:
chunks = []
counter2 = 1
for character in operation:
if character.isdigit():
if chunks[-1].isdigit(): # If the last chunk is already a number
chunks[-1] += character # Add onto that number
else:
chunks.append(character) # Start a new number chunk
elif character in '+-/*()':
chunks.append(character) # This doesn't account for `1 ++ 2`.
for e in reversed(chunks):
if e == '(':
counter2 = len(chunks) - counter2
break
else:
counter2 = counter2 + 1
if chunks[counter2+2] == '+':
result2 = int (chunks[counter2+1]) + int (chunks[counter2+3])
elif chunks[counter2+2] == '-':
result2 = int (chunks[counter2+1]) - int (chunks[counter2+3])
elif chunks[counter2+2] == '*':
result2 = int (chunks[counter2+1]) * int (chunks[counter2+3])
elif chunks[counter2+2] == '/':
result2 = int (chunks[counter2+1]) / int (chunks[counter2+3])
chunks[counter2] = ''
chunks[counter2 + 1] = ''
chunks[counter2 + 2] = str (result2)
chunks[counter2 + 3] = ''
chunks[counter2 + 4] = ''
operation = ''.join(chunks)
不要注意while条件,我正在更新它,因为我需要检查
答案 0 :(得分:0)
您应该尝试更多地自行调试代码。你遇到的问题是int转换正在&#34; - &#34;而不是&#34; -5&#34;。你需要结合&#34; - &#34;和序列中的next整数并将其转换为int并使用。 temp = str(chunk [counter2 + 3])+ str(chunk [counter2 + 4])