gpt4 book ai didi

python - 列表中的所有 6 数排列

转载 作者:太空宇宙 更新时间:2023-11-04 10:38:47 25 4
gpt4 key购买 nike

我正在编写一个程序,目标是获取一个数字列表并使用递归函数返回所有六个字母的组合(无需导入函数来帮我完成)。比如说,我的数字是“1 2 3 4 5 6 7 8 9”,输出将是:

1 2 3 4 5 6
1 2 3 4 5 7
1 2 3 4 5 8
1 2 3 4 5 9
1 2 3 4 6 7
1 2 3 4 6 8
1 2 3 4 6 9
1 2 3 4 7 8
... etcetera, all the way down to
4 5 6 7 8 9

我不是在寻找代码,我只是在概念上朝着正确的方向前进。到目前为止,我的尝试都失败了,我已经把自己逼入了一个逻辑陈规。

我在下面包含了我之前使用的代码,但它并不是真正的递归函数,而且似乎只适用于 6-8 位数的值。它非常困惑,我完全可以放弃它:

# Function prints all the possible 6-number combinations for a group of numbers
def lotto(constantnumbers, variablenumbers):
# Base case: No more constant variables, or only 6 numbers to begin with
if len(constantnumbers) == 0 or len(variablenumbers) == 0:
if len(constantnumbers) == 0:
print(" ".join(variablenumbers[1:7]))
else:
print(" ".join(constantnumbers[0:6]))
i = 6 - len(constantnumbers)
outvars = variablenumbers[1:i + 1]
if len(variablenumbers) > len(outvars) + 1:
print(" ".join(constantnumbers + outvars))
for index in range(len(outvars), 0, -1):
outvars[index - 1] = variablenumbers[index + 1]
print(" ".join(constantnumbers + outvars))
else:
i = 6 - len(constantnumbers)
outvars = variablenumbers[1:i + 1]
print(" ".join(constantnumbers + outvars))
if len(variablenumbers) > len(outvars) + 1:
for index in range(len(outvars), 0, -1):
outvars[index - 1] = variablenumbers[index + 1]
print(" ".join(constantnumbers + outvars))
#Reiterates the function until there are no more constant numbers
lotto(constantnumbers[0:-1], constantnumbers[-1:] + variablenumbers)

最佳答案

import itertools

for combo in itertools.combinations(range(1,10), 6):
print(" ".join(str(c) for c in combo))

给出

1 2 3 4 5 6
1 2 3 4 5 7
1 2 3 4 5 8
...
3 4 6 7 8 9
3 5 6 7 8 9
4 5 6 7 8 9

编辑:好的,这是一个递归定义:

def combinations(basis, howmany):
for index in range(0, len(basis) - howmany + 1):
if howmany == 1:
yield [basis[index]]
else:
this, remainder = basis[index], basis[index+1:]
for rest in combinations(remainder, howmany - 1):
yield [this] + rest

编辑2:

基本情况:1 项组合是任何基本项目。

归纳:N 项组合是任何基础项加上来自剩余基础的 (N-1) 项组合。

关于python - 列表中的所有 6 数排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22074912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com