![](/img/trans.png)
[英]Efficient way to add iterables in this simple Gpa calculator. Also 2 variables in 1 input?
[英]RPN (Postfix) Calculator. Not Accepting Input The Way I Want
我,我已经写了一个RPN计算器,但它不是按照我的方式打印或接受输入。
目前,它需要输入并打印如下:
5 5 +
10
我想在哪里这样输入
5
5
+
=
10
到目前为止,这是我的代码:
def op_pow(stack):
b = stack.pop(); a = stack.pop()
stack.append(a ** B)/>/>
def op_mul(stack):
b = stack.pop(); a = stack.pop()
stack.append(a * B)/>/>
def op_div(stack):
b = stack.pop(); a = stack.pop()
stack.append(a / B)/>/>
def op_add(stack):
b = stack.pop(); a = stack.pop()
stack.append(a + B)/>/>
def op_sub(stack):
b = stack.pop(); a = stack.pop()
stack.append(a - B)/>/>
def op_num(stack, num):
stack.append(num)
ops = {
'^': op_pow,
'*': op_mul,
'/': op_div,
'+': op_add,
'-': op_sub,
}
def get_input(inp):
tokens = inp.strip().split()
return tokens
def rpn_calc(tokens):
stack = []
table = []
for token in tokens:
if token in ops:
ops[token](stack)
table.append( (token, ' '.join(str(s) for s in stack)) )
else:
op_num(stack, eval(token))
table.append( (token, ' '.join(str(s) for s in stack)) )
return stack[-1]
while True:
rp = rpn_calc(get_input((raw_input())))
print rp
我试图通过更改来修复它:
rp = rpn_calc(get_input((raw_input())))
print rp
至:
rp = [get_input(raw_input())]
但这不起作用,因为我还没有通过rpn_calc函数传递它,所以它不加总,因为当我这样做时,我得到了错误:
Traceback (most recent call last):
File "C:\Users\James\Desktop\rpn.py", line 58, in <module>
help = rpn_calc[get_input(raw_input())]
TypeError: 'function' object has no attribute '__getitem__'
您正在使用rpn_calc()
函数,就像使用方括号索引到序列一样:
rpn_calc[get_input(raw_input())]
进行适当的函数调用:
rpn_calc(get_input(raw_input()))
但是,您将不得不重新设计程序,以将tokens
上的循环替换为无限循环,在每次循环迭代时要求输入,并将该输入视为令牌:
while True:
token = raw_input()
您可能想要寻找exit
或end
令牌以脱离循环和程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.