如何编写将运算符放在数字之间的函数?

How to write a function that puts operators between numbers?

我怎样才能写一个程序, 收到: 1 2 4 = 7 输出: 1 + 2 + 4 = 7

所以我需要编写一个程序,将运算符放在数字之间以获得正确答案。

好的,这解决了您给定的问题和类似情况。会有很多条件需要检查。这假定必须考虑运算符优先级,但您也可以将它用于简单的 运行 结果(例如在一些 Brilliant 日常问题中)。操作员的选择是快速而肮脏的,可以改进,还需要进行详尽的测试以涵盖更复杂的情况。这只是为了说明一种简单的方法:

from itertools import permutations, combinations_with_replacement

def clclin(coeffl, rslt, copl):
    '''simple forward solve'''
    if len(coeffl)!=len(copl)+1:
        return False
    cv = coeffl[0]
    for icf in range(len(copl)):
        if copl[icf]=='+':
            cv += coeffl[icf+1]
        elif copl[icf]=='-':
            cv -= coeffl[icf+1]
        elif copl[icf]=='*':
            cv *= coeffl[icf+1]
        elif copl[icf]=='/' and coeffl[icf+1]!=0:
            cv /= coeffl[icf+1]
        else:
            return False
    return cv==rslt

def clcop(coeffl, rslt, copl):
    '''consider precedence'''
    if len(coeffl)!=len(copl)+1:
        return False
    cv = [coeffl[0]]
    co = []
    for icf in range(len(copl)):
        if copl[icf]=='*':
            cv[-1] *= coeffl[icf+1]
        elif copl[icf]=='/':
            if coeffl[icf+1]!=0:
                cv[-1] /= coeffl[icf+1]
            else:
                return False
        else:
            cv.append(coeffl[icf+1])
            co.append(copl[icf])
    return clclin(cv, rslt, co)

def solvop(coeffl, rslt, vldop='+-*/'):
    '''try to solve coefficients combined via valid operators for given result'''
    if len(coeffl)==0: # only rudimentary error handling
        return []
    pcopl = []
    for p in combinations_with_replacement(vldop, len(coeffl)-1): # sloppily building all operator lists (can be improved)
        for el in permutations(p, len(coeffl)-1):
            pcopl.append(el)
    for copl in pcopl:
        if clcop(coeffl, rslt, copl): # use clclin for simple linear calculation w/o operator precedence
            return copl
    return []

print(list(solvop([1,2,4], 7)))
print(list(solvop([1,3,4], 7)))
print(list(solvop([1,2,4], 8)))
print(list(solvop([1,2,4], 1/8)))
print(list(solvop([1,2,0], 1/8)))
print(list(solvop([], 1/8)))
print(list(solvop([1,2,3], 7)))
print(list(solvop([1,2,0], 2)))
print(list(solvop([1,2,0,0,0,0], 2)))
print(list(solvop([0,0,0,0,2,0], 2)))
print(list(solvop([0,0,0,0,2,0], 5)))
print(list(solvop([0,0,0,0,-2,-1], 2)))

产生(第一行是你的问题):

['+', '+']
['*', '+']
['*', '*']
['/', '/']
[]
[]
['+', '*']
['*', '+']
['*', '+', '+', '+', '+']
['+', '+', '+', '+', '+']
[]
['+', '+', '+', '+', '*']