(范围(1,36),7)和+条件下的所有组合

2024-10-04 17:19:59 发布

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

我有一个小python脚本,它将返回范围(1,36)的所有7个组合,并将其写入txt文件。在

from itertools import combinations

f = open('combinations.txt', 'w')
for comb in combinations(range(1,36), 7):
    f.write(str(comb))
    f.write('\n')
f.close()

但因为这会是一个非常大的文件,我不想写那些7,6,5连续数字。在

例如:

  • 7个连续号码:1 2 3 4 5 6 7和2 3 4 5 6 7 8和。。29 30 31 32 33 34 35
  • 6个连续数字:1 2 3 4 5 6+(一个或更多)和。。29 30 31 32 33 34+(一个或多个)
  • 5。。在

你知道我怎么做吗?我的txt有多大?在


Tags: 文件infromimporttxt脚本forrange
3条回答

这会让你上路:

from itertools import combinations

def foo(a):
    if len(a) == 2:
        return a[1] - a[0] == 1
    return a[1] - a[0] == 1 and foo(a[1:])
##print foo('1234567')
##print foo('1234678')

# all combinations of 35 things taken 7 at a time
z = [comb for comb in combinations(range(1,36), 7)]
print len(z)
# remove combinations with consecutive numbers
z = [s for s in z if not foo(s)]
print len(z)
# make it into a string
z = '\n'.join(''.join(map(str,thing)) for thing in z)
print len(z)

如果我没搞错,你可以这样做:

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)

f = open('C:/combinations.txt', 'w')
for comb in combinations(range(1,36), 7):
    if count_consecutive(comb) not in [5, 6, 7]:
        f.write(str(comb))
        f.write('\n')
f.close()

它节省了6724520中的12615,相当于0.18%,结果是180.5 MB的文件。在

我有点小问题。txt文件太小,无法存储这样的数据,所以我决定使用数据库。但是在我的新代码之后,我收到了一条错误消息:

File "C:\Users\zolka\workspace\LottoAllCombination\LottoCombinations.py", line 34, in <module>
    c.execute("INSERT INTO test (word) VALUES (?)", (i,))
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type. 




from itertools import combinations, groupby
from operator import itemgetter
import sqlite3

data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]

def find_consecutive(lst, min_string=5):
    for k, g in groupby(enumerate(lst), lambda (i,x):i-x):
        num_string = map(itemgetter(1), g)
        if len(num_string) >= 5:
            yield num_string

con = sqlite3.connect("dictionary.sqlite")
c = con.cursor()
c.execute("CREATE TABLE test (word char(14))")
for i in combinations(data, 7):
    if not any(find_consecutive(i, min_string=5)):
        c.execute("INSERT INTO test (word) VALUES (?)", (i,))
con.commit()

相关问题 更多 >

    热门问题