首页 > 解决方案 > 如何压缩多个 for 语句,以便用户可以更改它们的数量

问题描述

我有一个代码,它可以获取每个数字组合(1 到 4),将它们加起来会得到你插入的数字(在这种情况下是 n)......

它基本上以 n 位列出数字 1、2、3 和 4 的每个组合,并添加了 if 语句以排除我在另一个程序中需要的那些。

我现在设置它的方式是将其锁定为 6 位,因为我必须手动更改 for 语句的数量才能更改。我的问题是如何制作它,以便我可以在控制台中输入尽可能多的 for 语句。

这是我的代码:

def num_of_comb(n):
    counter = 0
    for a in range(1, 5):
        if a == n:
            print(str(a))
            counter += 1
        for b in range(1, 5):
            if a+b == n:
                print(str(a) + str(b))
                counter += 1
            for c in range(1, 5):
                if a+b+c == n:
                    print(str(a) + str(b) + str(c))
                    counter += 1
                for d in range(1, 5):
                    if a+b+c+d == n:
                        print(str(a) + str(b) + str(c) + str(d))
                        counter += 1
                    for e in range(1, 5):
                        if a+b+c+d+e == n:
                            print(str(a) + str(b) + str(c) + str(d) + str(e))
                            counter += 1
                        for f in range(1, 5):
                            if a+b+c+d+e+f == n:
                                print(str(a) + str(b) + str(c) + str(d) + str(e) + str(f))
                                counter += 1

    return counter

print(num_of_comb(int(input("Unesi broj: "))))

只有当我输入 6 时,此代码的结果才会正确,因为有 6 个 for 语句。

标签: python

解决方案


我会去itertools.product替换嵌套for循环。

from itertools import product
numberOfLoops = int(input("Number of loops?"))

for t in product(range(1, 5), repeat=numberOfLoops):
    # t is a tuple with all loops variables in it
    if sum(t) == n:
        # do stuff

您可以在此处阅读文档。

请注意,对于您要达到的特定目的,可能还有其他有趣的选项,例如itertools.combinations.


推荐阅读