无法将列表附加到其他lis

2024-04-19 22:11:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个代码,它把一个数字和组的列表,加起来就是21。我的问题是,最终我希望所有的数字都列在一个列表中,但我很难做到这一点。如有任何建议,将不胜感激

def twentyone(seq, groups = []):
goal = 21
s = sum(groups)
final = []
if s == goal:
    final.append(groups)
    print (final)
if s >= goal:
    return

for i in range(len(seq)):
    n = seq[i]       
    remaining = seq[i+1:]
    twentyone(remaining, groups + [n])


#
seq = [1, 5, 6, 7, 10, 2, 11]
(twentyone(seq))

电流输出为:

[[1, 5, 6, 7, 2]]
[[1, 7, 2, 11]]
[[5, 6, 10]]
[[10, 11]]

我希望输出为:

[[1, 5, 6, 7, 2], [1, 7, 2, 11], [5, 6, 10], [10, 11]]

Tags: 代码列表ifdef数字seq建议final
2条回答

每次final列表递归调用自身时,您都在创建新的final列表。您只需将其作为默认参数传递。你知道吗

def twentyone(seq, groups = [], final = []): #default final list
    goal = 21
    s = sum(groups)

    if s == goal:
        final.append(groups)

    if s >= goal:
        return

    for i in range(len(seq)):
        n = seq[i]       
        remaining = seq[i+1:]
        twentyone(remaining, groups + [n])

    return final


seq = [1, 5, 6, 7, 10, 2, 11]
print twentyone(seq)

你知道吗结果:你知道吗

[[1, 5, 6, 7, 2], [1, 7, 2, 11], [5, 6, 10], [10, 11]]

但是上述解决方案将导致每次调用twentyone函数时,最终列表都会增长。因此,我们只能在第一次使用first_call标志调用时创建一个新的final列表,如下所示:

def twentyone(seq, groups = None, final = None, first_call=True): 

    if not groups:
        groups = []

    if first_call:
        final = []

    goal = 21
    s = sum(groups)

    if s == goal:
        final.append(groups)

    if s >= goal:
        return

    for i in range(len(seq)):
        n = seq[i]       
        remaining = seq[i+1:]
        twentyone(remaining, groups + [n], final, False)

    return final


seq = [1, 5, 6, 7, 10, 2, 11]
print twentyone(seq)
print twentyone(seq)

收益率:

[[1, 5, 6, 7, 2], [1, 7, 2, 11], [5, 6, 10], [10, 11]]
[[1, 5, 6, 7, 2], [1, 7, 2, 11], [5, 6, 10], [10, 11]]

扩展Tanveers answer(我认为这是最好的方法),您还可以将最后一个变量移到外部,甚至使用静态变量。代码中的主要问题是在每个递归调用中创建新的final变量。下面的代码修复了这个问题。你知道吗

局部变量法:

final = []

def twentyone(seq, groups = []):
    goal = 21
    s = sum(groups)
    if s == goal:
        final.append(groups)
    if s >= goal:
        return

    for i in range(len(seq)):
        n = seq[i]       
        remaining = seq[i+1:]
        twentyone(remaining, groups + [n])
seq = [1, 5, 6, 7, 10, 2, 11]
twentyone(seq)
print (final)

静态变量法:

class myfinal:
    final=[]
def twentyone(seq, groups = []):
    goal = 21
    s = sum(groups)
    if s == goal:
        myfinal.final.append(groups)
    if s >= goal:
        return

    for i in range(len(seq)):
        n = seq[i]       
        remaining = seq[i+1:]
        twentyone(remaining, groups + [n])


seq = [1, 5, 6, 7, 10, 2, 11]
twentyone(seq)
print (myfinal.final)

相关问题 更多 >