我有一个问题,要求我制作一个计算器但其奇怪的计算器用户首先在一行输入算术运算,在第二行输入数字,所以我写这样的代码
input() # here is the number of Arithmetic operation
a=[]
n=raw_input() # here enter the Arithmetical operation
m=map(int, raw_input().split()) #here is the numbers
for x,y in zip(m,n): Here i mix the 2 lists
a.append(x)
a.append(y) # but the 2 Arithmetic operation and the numbers
a.append(m[len(m)-1])
print eval(''.join(map(str, a))) #here to calculate them
输入
6
++*+/+
3 8 9 110 26 38 1
输出
59.58
但我得到1002并且在计算器上,所以我注意到总和是按照这个
(3 + 8)= 11,(11 + 9)= 20,(20 * 110)= 2200,(2200 + 26)= 2226,(38分之2226)= 58.57,(58.5 + 1)= 59.58 我怎么能在python中做到这一点,谢谢你
答案 0 :(得分:1)
没有运算符的优先级我们只是迭代操作数和运算符并执行相应的操作。
s = '++*+/+'
l = [3, 8, 9, 110, 26, 38, 1]
result = l[0]
for i in range(1, len(l)):
# print result,s[i-1],l[i]
if s[i-1]=='-':
result = result - l[i]
elif s[i-1]=='+':
result = result + l[i]
elif s[i-1]=='*':
result = result * l[i]
elif s[i-1]=='/':
result = float(result) / l[i]
print result
输出
59.5789473684
考虑运营商的优先级实际上您有一个infix
表达式。为了计算它,您需要将其转换为postfix
。将其转换为postfix
后,您可以轻松计算结果。有关完整说明,请参阅此link
这是我实施的代码
def hasHigherPrecedence(a, b):
if (a=='*' or a=='/') and (b!='*' and b!='/'):
return True
return False
s = '++*+/+'
l = [3, 8, 9, 110, 26, 38, 1]
## computing postfix from infix
stk = []
postfix = []
for i in range(len(l)):
postfix.append(l[i])
if i < len(s):
if len(stk) == 0 :
stk.append(s[i])
continue
while len(stk):
if hasHigherPrecedence(s[i],stk[-1]):
stk.append(s[i])
break
else:
postfix.append(stk[-1])
stk.pop(-1)
else:
stk.append(s[i])
while len(stk):
postfix.append(stk[-1])
stk.pop(-1)
## evaluate the postfix expression
stk=[]
for x in postfix:
r = None
if x=='+':
r = stk[-2]+stk[-1]
elif x=='*':
r = stk[-2]*stk[-1]
elif x=='/':
r = 1.0*stk[-2]/stk[-1]
elif x=='-':
r = stk[-2]-stk[-1]
else:
stk.append(x) ## x is a operand
if r != None:
stk.pop(-1)
stk.pop(-1)
stk.append(r)
print stk[0]
输出
1002.68421053