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

2024-09-29 01:21:07 发布

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

Tags: 代码inputwith数字popintsplitprint
2条回答

使用递归方法:

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错误(前两行),我不知道这是否是您已经尝试过的。你知道吗

详尽的搜索:

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]

注意:我喜欢上面评论中提到的递归表达式生成器,但我不认为它是直接递归的。你知道吗

相关问题 更多 >