Python中缺少运算符计算器

2024-09-28 03:24:57 发布

您现在位置: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

预期输出为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

Tags: ofinforreturnif数字operationlength
3条回答

我已经重写了代码并改变了很多东西,代码可能并不完美,但它确实起到了作用

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
  1. 首先是一个简单的问题。之所以得到None,是因为operation_replacer函数不返回任何内容,并且在最后的循环中打印该结果

  2. 此解析器仅适用于<;5个值,因为在pair_operators循环中有一段代码准备操作有点笨拙。我真的不明白-从一个元组你得到(操作符产品),你把它字符串化,然后解析它只得到列表。。。您可以使用tuple而不需要整个解析过程

不加修饰的例子

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)

相关问题 更多 >

    热门问题