计算结果数量

时间:2014-12-27 10:52:12

标签: python list count

我有一个家庭作业,我必须打印结果的数量(范围(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)

1 个答案:

答案 0 :(得分:4)

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)

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

  

示例:

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

输出:

(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
  

编辑:这里有更多pythonic:

list1=[comb for comb in combinations(range(1,10),3)]
print (len(list1))

输出:

>>> 
84
>>>