python初学者,但已经编程5年了。我想我有很多东西要学,以面向对象的方式做事情,但我知道基本的。我计划编程一个计算器,显示它的工作挑战和知识,我将从中获得。我刚开始,这就是我所拥有的,只是在我看来真的很难看。你会有什么不同的做法呢?在
附言:这只是一个简单的脚本,把问题从括号里拿出来,加起来,展示工作,然后评估整个问题。在
import re
def EvalParenths(problem):
contents = ""
if re.match( "\(", problem):
contents = re.match("(\(.*\))", problem)
parenthsAnswer = contents.group(0)
problem = problem.replace(parenthsAnswer, '')
print " \ \n " + str(eval(parenthsAnswer)) + problem
problem = problem.replace(parenthsAnswer, '')
answer = eval(parenthsAnswer+problem)
print " \ \n " + str(answer)
else:
print "Didn't Find Parenthesis"
def ProblemHasParenths(problem):
return re.match( "\(", problem)
"""""
Example Problem: (12/4)*2
"""""
problem = raw_input()
if ProblemHasParenths:
EvalParenths(problem)
一些问题:
当给定输入
(1+2)/(3+4)
时,它将尝试计算1+2)/(3+4
。在它也没有完全进入嵌套括号,为此,您需要使用递归。在
我认为你应该在“看答案”之前再做一次尝试。在
我可能会替换
与
^{pr2}$在
你不检查内容是否匹配,所以如果你传递给它输入“(1”,当你试图计算时,你会得到一个异常目录.组(0)
不要在一个真正的程序中使用
eval
!在您可以使用pyparsing来创建一个完整的解析器,但我认为这是每个人都应该自己尝试至少一次的事情!在
如果你想做一个简单的计算器,你可以尝试实现Shunting-yard algorithm。在
但如果您想使用regex方法,我还是会做一些不同的事情:
实现你的功能和我的功能不太一样。如你所见,我还添加了很多注释来解释一些东西。在
相关问题 更多 >
编程相关推荐