我有一个小的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的数字。
例如:
知道我该怎么办?我的txt有多大?
答案 0 :(得分:1)
如果我没弄错的话,你可以这样做:
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()
它节省了12,715的6,724,520,这相当于0.18%,导致180.5 MB的文件。
答案 1 :(得分:0)
我有点问题。 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()
答案 2 :(得分:0)
这应该可以帮助你:
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)