计算结果数

haw*_*183 0 python list count

我有一个家庭作业,在这里我必须打印没有连续数字的结果数(range(1,36),7)。我已经为此编写了python脚本,但是不知道如何计算结果行数,这是什么样的:

(1、2、5、6、8、16、34)

(1、2、5、6、8、16、35)

(1、2、5、6、8、17、18)

...

我期望的结果是:6711905

这是我的小脚本:

from itertools import combinations

def count_consecutive(l): 
    counts = [1]
    counts_index = 0
    for i in range(1, len(l)):
        if l[i] == l[i-1] + 1:
            counts[counts_index] = counts[counts_index] + 1
        else:
            counts.append(1)
            counts_index += 1
    return max(counts)     

for comb in combinations(range(1,36), 7):
    if count_consecutive(comb) not in [5, 6, 7]:
        #print (comb)
Run Code Online (Sandbox Code Playgroud)

GLH*_*LHF 5

counting=0
for comb in combinations(range(1,36), 7):
    if count_consecutive(comb) not in [5, 6, 7]:
        print (comb)
        counting+=1
print (counting)
Run Code Online (Sandbox Code Playgroud)

每次打印后,这将为您提供所需的编号,将计数变量加1 。当for循环结束时,将打印计数变量的最后一个值。

例:

counting=0
for comb in combinations(range(1,10),3):
    print (comb)
    counting+=1
print ("The number of counts is:",counting)
Run Code Online (Sandbox Code Playgroud)

输出:

(1, 2, 3)
(1, 2, 4)
(1, 2, 5)
(1, 2, 6)
(1, 2, 7)
(1, 2, 8)
(1, 2, 9)
(1, 3, 4)
(1, 3, 5)
(1, 3, 6)
....
....
....
(6, 8, 9)
(7, 8, 9)
The number of counts is: 84
Run Code Online (Sandbox Code Playgroud)

编辑:这是更多的pythonic:

list1=[comb for comb in combinations(range(1,10),3)]
print (len(list1))
Run Code Online (Sandbox Code Playgroud)

输出:

>>> 
84
>>> 
Run Code Online (Sandbox Code Playgroud)