所有+ - / x组合4个数字

时间:2017-07-25 01:19:38

标签: python

4个一位数字,并尝试获得所有可能的组合 4511 像4 + 5 + 1 x 1 获得第一,第二和第四数字的代码

numbers = input("Input 4 numbers separated with , : ")
numlist = numbers.split(",")
print (numlist)
No1 = int(numlist.pop(0))
No2 = int(numlist[0])
No3 = int(numlist[1])
No4 = int(numlist[2])

2 个答案:

答案 0 :(得分:2)

详尽的搜索:

from random import randrange
from itertools import permutations

def solve(digits):
    for xs in permutations(digits):
        for ops in permutations('+-*/', 3):
            equation = reduce(lambda r, (x, op): '{0} {1} {2}'.format(r, op, float(x)), zip(xs[1:], ops), xs[0])
            try:
                if eval(equation) == 10:
                    yield equation.replace('.0','')
            except ZeroDivisionError:
                pass

digits = [randrange(0,10,1) for x in range(4)]
solutions = list(solve(digits))
if solutions:
    print '\n'.join(solutions)
else:
    print 'No solution for {0}'.format(digits)

示例输出:

2 * 5 / 1 + 0
2 * 5 / 1 - 0
2 * 5 + 0 / 1
2 * 5 - 0 / 1
2 / 1 * 5 + 0
2 / 1 * 5 - 0
5 * 2 / 1 + 0
5 * 2 / 1 - 0
5 * 2 + 0 / 1
5 * 2 - 0 / 1
5 / 1 * 2 + 0
5 / 1 * 2 - 0
0 + 2 * 5 / 1
0 + 2 / 1 * 5
0 + 5 * 2 / 1
0 + 5 / 1 * 2
0 / 1 + 2 * 5
0 / 1 + 5 * 2

No solution for [7, 1, 0, 2]

注意:我喜欢上面评论中提到的递归表达式生成器,但我不会直接以递归的方式思考。

答案 1 :(得分:0)

使用递归方法:

numbers = input("Input 4 numbers separated with , : ")
numlist = list(numbers)

def f(lst,carry,result):
    x = lst.pop(0)
    if lst == []:
        return carry+x == result or \
               carry-x == result or \
               carry*x == result or \
               carry/x == result
    elif carry==None:
        carry = x
        return f(lst,carry,result)
    else:
        return f(lst,carry+x,result) or\
               f(lst,carry-x,result) or\
               f(lst,carry*x,result) or\
               f(lst,carry/x,result)

print(f(numlist, None, 10))

您的I / O错误(前两行),我不知道这是否是您已经尝试过的。