我正在尝试编写一个程序来查找数学表达式的所有结果以及 4 个缺失的运算符,即
+,*,-
和 /
。例如 2?3
的所有结果将是这样的:
(2+3) = 5
(2-3) = -1
(2*3) = 6
(2/3) = 0.6666666666666666
这些是我的代码
import itertools
expression='1?2?3'
def operation_counter(expression):
count = 0
for i in expression:
if (i == '?'):
count += 1
else:
pass
return count
def parenthesize(expression):
operators = ['?']
depth = len([s for s in expression if s in operators])
if depth == 0:
return [expression]
if depth== 1:
return ['('+ expression + ')']
answer = []
for index, symbol in enumerate(expression):
if symbol in operators:
left = expression[:index]
right = expression[(index+1):]
expressions = ['(' + lt + ')' + symbol +'(' + rt + ')'
for lt in parenthesize(left)
for rt in parenthesize(right) ]
answer.extend(expressions)
return answer
def operation_replacer(expression):
spare = expression
opr = ['+', '-', '*', '/']
operation_numbers = operation_counter(expression)
products = list(itertools.product(opr, repeat=operation_numbers))
for i in products:
pair_of_operators = str(i)
length = len(pair_of_operators)
z = []
for i in range(0,length):
s = pair_of_operators.find("'",i,length)
e = pair_of_operators.find("'",s+1,length)
x = pair_of_operators[s+1:e]
if (x != ""):
pair_of_operators = pair_of_operators[e:length]
z.append(x)
for i in z:
expression = expression.replace('?',i,1)
try:
evaluation = str(eval(expression))
except ZeroDivisionError:
evaluation = 'Division By Zero!'
print(expression + ' = ' + evaluation)
expression = spare
for i in parenthesize(expression):
result = operation_replacer(i)
print(result)
问题是该程序对于五个数字可以正常工作,而不是像:
1?2?3?4?5
,但是当我将其应用于超过五个数字的更复杂表达式时,我收到错误,例如:3?6?1?5?12?6
。我尝试了很多,但从未找到解决这个问题的方法
这是完整的回溯消息:
Traceback (most recent call last):
File "C:\Users\Muhammad\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\IPython\core\interactiveshell.py", line 3417, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-14-790301a5c9b0>", line 64, in <module>
result = operation_replacer(i)
File "<ipython-input-14-790301a5c9b0>", line 55, in operation_replacer
evaluation = str(eval(expression))
File "<string>", line 1
(1)+((2)+((3)+((4)+((5?6)))))
^
SyntaxError: invalid syntax
预计输出 6 个及更多数字太长,我无法写出所有可能性,因为它超出了这个问题允许的最大字符数
另外,我在结果中得到一个
None
值,但我不知道它来自哪里,例如,查看 1?2?3
的结果
(1)+((2+3)) = 6
(1)+((2-3)) = 0
(1)+((2*3)) = 7
(1)+((2/3)) = 1.6666666666666665
(1)-((2+3)) = -4
(1)-((2-3)) = 2
(1)-((2*3)) = -5
(1)-((2/3)) = 0.33333333333333337
(1)*((2+3)) = 5
(1)*((2-3)) = -1
(1)*((2*3)) = 6
(1)*((2/3)) = 0.6666666666666666
(1)/((2+3)) = 0.2
(1)/((2-3)) = -1.0
(1)/((2*3)) = 0.16666666666666666
(1)/((2/3)) = 1.5
None
((1+2))+(3) = 6
((1+2))-(3) = 0
((1+2))*(3) = 9
((1+2))/(3) = 1.0
((1-2))+(3) = 2
((1-2))-(3) = -4
((1-2))*(3) = -3
((1-2))/(3) = -0.3333333333333333
((1*2))+(3) = 5
((1*2))-(3) = -1
((1*2))*(3) = 6
((1*2))/(3) = 0.6666666666666666
((1/2))+(3) = 3.5
((1/2))-(3) = -2.5
((1/2))*(3) = 1.5
((1/2))/(3) = 0.16666666666666666
None
首先是简单的 -
None
问题。您会得到 None
,因为 operation_replacer
函数不会返回任何内容,并且您在最后的循环中打印该结果。
此解析器仅适用于 <5 values because there is a bit clumsy piece of code - preparing operation in the
pair_operators
循环。我真的不明白 - 从你得到的元组(运算符的产品)中,你将它字符串化,然后解析它只是为了获取列表......你可以使用元组而不需要整个解析的东西。
没有解析的示例
def operation_replacer(expression):
spare = expression
ops = ['+', '-', '*', '/']
ops_count = len([ch in ch in experssion if ch == '?'])
products = list(itertools.product(ops, repeat=ops_count))
for op_set in products:
for op in op_set:
expression = expression.replace('?', op, 1)
try:
evaluation = str(eval(expression))
except ZeroDivisionError:
evaluation = 'Division By Zero!'
print(expression + ' = ' + evaluation)
expression = spare
不是真正的答案,但代码太大,无法作为评论发布。您可以使用
split
内置函数来缩短代码。您将在下面找到一个包含 6 个数字(不带括号)的工作示例。我想下面的代码可以通过使用 itertools
: 进一步优化
import itertools
expression='1?2?3?4?5?6'
opr = ['+', '-', '*', '/']
sp = expression.split('?')
products = list(itertools.product(opr, repeat=len(sp)-1))
for product in products:
expression = [ sp[i]+product[i] for i in range(0,len(product))]
expression.append(sp[len(sp)-1])
expression = ''.join(expression)
print(expression)
我重写了代码并更改了很多东西,代码可能并不完美,但它可以完成工作
import itertools
string='1?2?3'
def operation_counter(string):
count = 0
for i in string:
if (i == '?'):
count += 1
else:
pass
return count
def q_positions(string):
positions = []
for i in range(len(string)):
if (string[i] == '?'):
positions.append(i)
return positions
def string_char_replacer(string,newstring,index):
string = string[:index] + newstring + string[index + 1:]
return string
def parenthesize(string):
operators = ['?']
depth = len([s for s in string if s in operators])
if depth == 0:
return [string]
if depth== 1:
return ['('+ string + ')']
answer = []
for index, symbol in enumerate(string):
if symbol in operators:
left = string[:index]
right = string[(index+1):]
strings = ['(' + lt + ')' + symbol +'(' + rt + ')'
for lt in parenthesize(left)
for rt in parenthesize(right) ]
answer.extend(strings)
return answer
def operation_replacer(string):
opr = ['+', '-', '*', '/']
operation_numbers = operation_counter(string)
products = list(itertools.product(opr, repeat=operation_numbers))
#print(products)
return products
def single_operation_list(string):
single_operators = []
for i in range(len(string)):
char = string[i]
if (char == "'" and string[i+1] != "," and string[i+1] != ")"):
single_operator = string[i+1:i+2]
single_operators.append(single_operator)
return single_operators
exp= parenthesize(string)
opr_tuple = operation_replacer(string)
opr = []
for i in opr_tuple:
tuple = str(i).replace(' ', '')
opr.append(tuple)
for i in exp:
for j in opr:
h = single_operation_list(j)
spare = i
for l in h:
i = i.replace('?',l,1)
find_q = i.find('?')
if (find_q == -1):
try:
evaluation = str(eval(i))
except ZeroDivisionError:
evaluation = 'Division By Zero!'
print(i + ' = ' + evaluation)
else:
pass
i = spare