[英]Solve basic mathematical operations in python 3
我正在尝试开发一种简单的python方法,该方法将允许我计算基本的数学运算。 这里的要点是我不能使用eval(),exec()或任何其他评估python statemets的函数,因此我必须手动执行。 到目前为止,我遇到了这段代码:
solutionlist = list(basicoperationslist)
for i in range(0, len(solutionlist)):
if '+' in solutionlist[i]:
y = solutionlist[i].split('+')
solutionlist[i] = str(int(y[0]) + int(y[1]))
elif '*' in solutionlist[i]:
y = solutionlist[i].split('*')
solutionlist[i] = str(int(y[0]) * int(y[1]))
elif '/' in solutionlist[i]:
y = solutionlist[i].split('/')
solutionlist[i] = str(int(y[0]) // int(y[1]))
elif '-' in solutionlist[i]:
y = solutionlist[i].split('-')
solutionlist[i] = str(int(y[0]) - int(y[1]))
print("The solutions are: " + ', '.join(solutionlist))
因此,我们有两个字符串列表,basicoperationlist具有以下格式的操作:2940-81、101-16、46 / 3、10 * 9、145 / 24,-34-40。 它们将始终有两个数字,中间是一个操作数。 我的解决方案的问题在于,当我进行类似上一个操作时,.split()方法将我的列表分为一个空列表和一个包含完整操作的列表。 总而言之,当我们将负数与减号运算混合时,此解决方案将无法很好地工作。 我不知道它是否在任何其他情况下都会失败,因为我只能设法注意到我先前描述的错误。 想法是,在方法的最后,我将solutionlist作为字符串的列表,这些字符串将作为基本数学运算的有序答案。 每当我的代码遇到类似上一个操作时,就会提示该错误: ValueError:int()以10为底的无效文字:''
基本操作列表在此处定义:
basicoperationslist = re.findall('[-]*\d+[+/*-]+\d+', step2processedoperation)
如您所见,我使用正则表达式从较大的操作中提取基本操作。 step2processedoperation是服务器发送到我的计算机的字符串。 但例如,它可能包含:
((87/(64*(98-94)))+((3-(97-27))-(89/69)))
它包含完整且平衡的数学运算。
也许有人可以帮助我解决此问题,或者我应该完全更改此方法。
先感谢您。
我会放弃整个拆分方法,因为它太复杂了,在某些情况下可能会失败,正如您所注意到的那样。
相反,我将使用正则表达式和operator
模块来简化操作。
import re
import operator
operators = {'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv}
regex = re.compile(r'(-?\d+)' # 1 or more digits with an optional leading '-'
r'(\+|-|\*|/)' # one of +, - , *, /
r'(\d+)', # 1 or more digits
re.VERBOSE)
exprssions = ['2940-81', '101-16', '46/3', '10*9', '145/24', '-34-40']
for expr in exprssions:
a, op, b = regex.search(expr).groups()
print(operators[op](int(a), int(b)))
# 2859
# 85
# 15.333333333333334
# 90
# 6.041666666666667
# -74
这种方法更容易适应新情况(例如新操作员)
您可以轻松地使用operator
和dict
来存储操作,而不是一长串的if-else
该解决方案还可以通过递归来计算更复杂的表达式。
from operator import add, sub, mul, floordiv, truediv
from functools import reduce
OPERATIONS = {
'+': add,
'-': sub,
'*': mul,
'/': floordiv, # or '/': truediv,
'//': floordiv,
}
OPERATION_ORDER = (('+', '-'), ('//', '/', '*'))
def calculate(expression):
# expression = expression.strip()
try:
return int(expression)
except ValueError:
pass
for operations in OPERATION_ORDER:
for operation in operations:
if operation not in expression:
continue
parts = expression.split(operation)
parts = map(calculate, parts) # recursion
value = reduce(OPERATIONS[operation], parts)
# print(expression, value)
return value
计算之前:
negative = False
if expression[0] == '-':
negative = True
expression = expression[1:]
在计算中,在拆分字符串之后:
if negative:
parts[0] = '-' + parts[0]
因此,总的来说:
def calculate(expression):
try:
return int(expression)
except ValueError:
pass
negative = False
if expression[0] == '-':
negative = True
expression = expression[1:]
for operations in OPERATION_ORDER:
for operation in operations:
if operation not in expression:
continue
parts = expression.split(operation)
if negative:
parts[0] = '-' + parts[0]
parts = map(calculate, parts) # recursion
return reduce(OPERATIONS[operation], parts)
使用re
可以很容易地检查是否有括号。 首先,我们需要确保它不能识别“简单的”带括号的中间结果(例如(-1)
)
PATTERN_PAREN_SIMPLE= re.compile('\((-?\d+)\)')
PAREN_OPEN = '|'
PAREN_CLOSE = '#'
def _encode(expression):
return PATTERN_PAREN_SIMPLE.sub(rf'{PAREN_OPEN}\1{PAREN_CLOSE}', expression)
def _decode(expression):
return expression.replace(PAREN_OPEN, '(').replace(PAREN_CLOSE, ')')
def contains_parens(expression):
return '(' in _encode(expression)
然后,要计算最左边的最括号,可以使用此函数
def _extract_parens(expression, func=calculate):
# print('paren: ', expression)
expression = _encode(expression)
begin, expression = expression.split('(', 1)
characters = iter(expression)
middle = _search_closing_paren(characters)
middle = _decode(''.join(middle))
middle = func(middle)
end = ''.join(characters)
result = f'{begin}({middle}){end}' if( begin or end) else str(middle)
return _decode(result)
def _search_closing_paren(characters, close_char=')', open_char='('):
count = 1
for char in characters:
if char == open_char:
count += 1
if char == close_char:
count -= 1
if not count:
return
else:
yield char
在calculate(middle)
()
周围calculate(middle)
的原因是,中间结果可能为负,如果以后在此处省略括号,可能会造成问题。
然后,算法的开始更改为:
def calculate(expression):
expression = expression.replace(' ', '')
while contains_parens(expression):
expression = _extract_parens(expression)
if PATTERN_PAREN_SIMPLE.fullmatch(expression):
expression = expression[1:-1]
try:
return int(expression)
except ValueError:
pass
由于中间结果可能为负,因此我们需要使用正则表达式在-
进行拆分,以防止5 * (-1)
在-
处进行拆分
因此,我对可能的操作进行了重新排序,如下所示:
OPERATIONS = (
(re.compile('\+'), add),
(re.compile('(?<=[\d\)])-'), sub), # not match the - in `(-1)`
(re.compile('\*'), mul),
(re.compile('//'), floordiv),
(re.compile('/'), floordiv), # or '/': truediv,
)
为图案-
只有当它是前面有一个匹配)
或数字。 这样我们就可以删除negative
标志并进行处理
其余算法将更改为:
operation, parts = split_expression(expression)
parts = map(calculate, parts) # recursion
return reduce(operation, parts)
def split_expression(expression):
for pattern, operation in OPERATIONS:
parts = pattern.split(expression)
if len(parts) > 1:
return operation, parts
完整的代码可以在这里找到
def test_expression(expression):
return calculate(expression) == eval(expression.replace('/','//')) # the replace to get floor division
def test_calculate():
assert test_expression('1')
assert test_expression(' 1 ')
assert test_expression('(1)')
assert test_expression('(-1)')
assert test_expression('(-1) - (-1)')
assert test_expression('((-1) - (-1))')
assert test_expression('4 * 3 - 4 * 4')
assert test_expression('4 * 3 - 4 / 4')
assert test_expression('((87/(64*(98-94)))+((3-(97-27))-(89/69)))')
test_calculate()
加电变得像加电一样简单
(re.compile('\*\*'), pow),
(re.compile('\^'), pow),
OPERATIONS
calculate('2 + 4 * 10^5')
400002
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.