Python 中的前缀表示法与中缀表示法
我正在编写一个小型计算器(带有前缀表示法),我很好奇如何将前缀表示法转换为中缀表示法。我目前有一个功能,但它很奇怪,我不知道如何修复它。奇怪的是,如果给定 ['+', x, y]
它将返回 (() + x + () + y)
这让我感到困惑。这是代码。
def pre_in(read):
#print read
tempOp = read[0]
body = read[1:]
expr = []
for i in range(len(body)-1):
if not isinstance(body[i], list) and body[i] != " ":
expr.append(str(body[i]))
expr.append(tempOp)
else:
expr.append(str(pre_in(body[i])))
expr.append(tempOp)
try:
if not isinstance(body[-1], list):
expr.append(str(body[-1]))
else:
expr.append(str(pre_in(body[-1])))
except:
pass
if expr != None: return "("+' '.join(expr)+")"
我做错了什么?
I am writing a small calculator (with prefix notation) and I'm curious how I'd convert prefix notation to infix notation. I currently have a function, but it's being weird, and I'm not sure how to fix it. By being weird, I mean that if given ['+', x, y]
it will return (() + x + () + y)
which is confusing me. Here's the code.
def pre_in(read):
#print read
tempOp = read[0]
body = read[1:]
expr = []
for i in range(len(body)-1):
if not isinstance(body[i], list) and body[i] != " ":
expr.append(str(body[i]))
expr.append(tempOp)
else:
expr.append(str(pre_in(body[i])))
expr.append(tempOp)
try:
if not isinstance(body[-1], list):
expr.append(str(body[-1]))
else:
expr.append(str(pre_in(body[-1])))
except:
pass
if expr != None: return "("+' '.join(expr)+")"
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
实际上你的代码工作得很好。
产量
编辑:
正如其他人所说,也许您想使用堆栈。这是一个带有一些示例的简单沙箱实现(它会产生许多括号,但这些不会造成伤害):
Actually your code works fine.
yields
EDIT:
As the others have stated, maybe you want to use a stack. Here a simple sandbox implementation with some examples (it produces many parenthesis but those don't hurt):
如果您的目标不是自己开发算法,请转到此页面。有两个页面的链接解释了 infix->postfix 和 postfix->infix 算法。 (另外,如果你想知道这些算法是如何用 javascript 实现的,你可以查看该页面的源代码。)
If your aim is not to develop the algorithm on your own, go to this page. There are links to two pages which explain the infix->postfix and postfix->infix algorithm. (And also, if you want to know how the algorithms are implemented in javascript, you can take a look at the source code of the page.)
这是一个相当简单的递归解决方案。
Here's a fairly simple recursive solution.
对于这种简单的解析/转换作业,您可能需要查看 pyparsing。
At the risk of being a bit overkill for this kind of simple parsing/conversion jobs, you may want to look at pyparsing.