蟒蛇。如何计算嵌套for循环中的除数的数量?

时间:2020-04-20 06:16:33

标签: python python-3.x for-loop

我有一个生成三角数的代码,计算每个三角数的除数,并打印出3列,其中第一列是输入数,第二列是三角数,第三列是每个三角形的除数数。如何计算每个三角数的除数(计算第三列中的数字)?

for num in range(10):
    triangle_number = num*(num+1)//2
    print(num, end = '   ')
    print(triangle_number, end = '     ')
    for divisor in range(1, triangle_number+1):
        if triangle_number%divisor == 0:
            print(divisor,  end = ',')
    print()

输出看起来像这样:

0   0     
1   1     1,
2   3     1,3,
3   6     1,2,3,6,
4   10     1,2,5,10,
5   15     1,3,5,15,
6   21     1,3,7,21,
7   28     1,2,4,7,14,28,
8   36     1,2,3,4,6,9,12,18,36,
9   45     1,3,5,9,15,45,

2 个答案:

答案 0 :(得分:0)

您可以在for循环中添加一个变量,并在获得除数并打印结尾时对其进行递增。

for num in range(10):
    count = 0
    triangle_number = num*(num+1)//2
    print(num, end = '\t')
    print(triangle_number, end = '\t')
    for divisor in range(1, triangle_number+1):
        if triangle_number%divisor == 0:
            print(divisor,  end = ',')
            count += 1

    print("\t", count)
##Output:
##0   0          0
##1   1     1,   1
##2   3     1,3,     2
##3   6     1,2,3,6,     4
##4   10     1,2,5,10,   4
##5   15     1,3,5,15,   4
##6   21     1,3,7,21,   4
##7   28     1,2,4,7,14,28,  6
##8   36     1,2,3,4,6,9,12,18,36,   9
##9   45     1,3,5,9,15,45,  6
##Output order : input number, count of divisors divisors, triangular number

或者您可以在打印前创建除数列表并测量长度。

for num in range(10):
    divisors = []
    triangle_number = num*(num+1)//2
    print(num, end = '\t')
    print(triangle_number, end = '\t')
    for divisor in range(1, triangle_number+1):
        if triangle_number%divisor == 0:
            divisors.append(divisor)

    print(len(divisors), "\t", ",".join(str(div )for div in divisors))
##Output:
##0 0   0    
##1 1   1    1
##2 3   2    1,3
##3 6   4    1,2,3,6
##4 10  4    1,2,5,10
##5 15  4    1,3,5,15
##6 21  4    1,3,7,21
##7 28  6    1,2,4,7,14,28
##8 36  9    1,2,3,4,6,9,12,18,36
##9 45  6    1,3,5,9,15,45
##Output order : input number, triangular number, count of divisors divisors

答案 1 :(得分:0)

您可以使用列表理解替换您的内部for循环,然后使用CoroutineScope函数获取该列表的长度,即替换:

len

具有:

for divisor in range(1, triangle_number+1):
    if triangle_number%divisor == 0:
        print(divisor,  end = ',')

列表理解是创建列表的一种简洁方法,可以通过在divisors = [divisor for divisor in range(1, triangle_number+1) if triangle_number%divisor == 0] print(*divisors, sep=',', end=' ') print(len(divisors), end='') append进行创建,如果您拥有列表{{1},for loop(星号运算符)会解压缩},那么*等同于x = [1, 2, 3],依此类推。