Python递归生成7个数字的唯一组合,6位数

-4 投票
2 回答
698 浏览
提问于 2025-04-17 20:24

我正在尝试让这个程序正常工作,当输入正好是7个数字时,它可以正常运行,但一旦我增加到8个或更多,它就出问题了。我不太确定自己哪里做错了。这个程序的设计是接收7个以上的数字,然后用递归的方法输出所有可能的6位数字组合。

例如,输入:1 2 3 4 5 6 7

输出:

1 2 3 4 5 6
1 2 3 4 5 7
1 2 3 4 6 7
1 2 3 5 6 7
1 2 4 5 6 7
1 3 4 5 6 7
2 3 4 5 6 7

这是我目前的代码。

def main():
    numbers = '1 2 3 5 8 13 21 34'
    numbers = numbers.split(' ')
    for i in range(len(lotto(numbers))):
        print(lotto(numbers)[i])

def lotto(numbers):
    if len(numbers) < 7:
        return numbers
    else:
        output = list()
        for i in range(len(numbers)):
            rem = lotto(numbers[i+1:])
            output.append(numbers[:i]+rem)
    return output

当我输入1 2 3 5 8 13 21 34时,如上所示,

['1', '3', '5', '8', '13', '21', '34']
['1', '2', '5', '8', '13', '21', '34']
['1', '2', '3', '8', '13', '21', '34']
['1', '2', '3', '5', '13', '21', '34']
['1', '2', '3', '5', '8', '21', '34']
['1', '2', '3', '5', '8', '13', '34']
['1', '2', '3', '5', '8', '13', '21']

输出是这样的,而不是

1 2 3 5 8 13
1 2 3 5 8 21
1 2 3 5 8 34
1 2 3 5 13 21
1 2 3 5 13 34
1 2 3 5 21 34
1 2 3 8 13 21
1 2 3 8 13 34
1 2 3 8 21 34
1 2 3 13 21 34
1 2 5 8 13 21
1 2 5 8 13 34
1 2 5 8 21 34
1 2 5 13 21 34
1 2 8 13 21 34
1 3 5 8 13 21
1 3 5 8 13 34
1 3 5 8 21 34
1 3 5 13 21 34
1 3 8 13 21 34
1 5 8 13 21 34
2 3 5 8 13 21
2 3 5 8 13 34
2 3 5 8 21 34
2 3 5 13 21 34
2 3 8 13 21 34
2 5 8 13 21 34
3 5 8 13 21 34

问题不在于输出是列表还是非列表,而在于输出的数量和大小。

2 个回答

0

使用 ''.join(list) 这个方法。

>>> x = 'hello world'
>>> x = list(x)
>>> x
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>> ''.join(x)
'hello world'
>>> 
1

Python已经内置了这个功能,你可以直接使用。具体可以查看这个链接:http://docs.python.org/2/library/itertools.html#itertools.permutations

g = permutations('1 2 3 5 8 13 21 34'.split())
for v in g:
    print " ".join(v)

下面是一个示例输出:

34 21 13 8 2 1 3 5
34 21 13 8 2 1 5 3
34 21 13 8 2 3 1 5
34 21 13 8 2 3 5 1
34 21 13 8 2 5 1 3
34 21 13 8 2 5 3 1

撰写回答