[英]Missing Operators Calculator In Python
我正在嘗試編寫一個程序來查找數學表達式的所有結果和 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
預期的 output 到 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
function 沒有返回任何東西,結果你最后在循環中打印。
此解析器僅適用於 <5 值,因為有一段笨拙的代碼 - 在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
內置 function 縮短很多代碼。 您將在下面找到一個帶有 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.