[英]Avoid chained numbers when printing lists
我創建的代碼從組合中生成了一個包含15個數字的列表,因此對它進行排序后,可能會看到一些序列附帶了許多數字鏈,例如:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 16, 20]
我正在嘗試一種方法來控制它,並僅打印最多具有4個鏈接數字的列表:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 16, 20]
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) >>>> 11 Chained numbers: 1 to 11.
So it won't be stored in file.txt.
[1, 2, 3, 6, 7, 8, 9, 11, 12, 16, 17, 18, 19, 22, 23]
(1, 2, 3) >>>> 3 chained, OK
(6, 7, 8, 9) >>>> 4 chained, OK
(11, 12) >>>> 2 chained, OK
(16, 17, 18, 19) >>>> 4 chained, OK
(22,23) 2 chained, OK.
So this list will be stored in the file
你們能給我個主意嗎? 燈嗎
我創建的代碼會生成一個文件,其中包含25個列表中15個數字的所有可能組合:
import itertools
my_file = open('file.txt', 'w')
ALL_25 = [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]
for subset in itertools.combinations(ALL_25, 15):
sort_subsets = sorted(subset)
my_file.write("{0}\n".format(sort_subsets))
print(sort_subsets)
my_file.close()
如果您可以將鏈轉換為其連續元素之間的差異,則更容易識別增量序列,即[1,2,3,4,7,8]
被轉換為[1,1,1,3,1]
。 另外,通過將其轉換為字符串,更容易搜索圖案111
。
import numpy as np
import re
def validate(seq):
stl = "".join(np.diff(seq).astype(str))
for x in re.findall("[1]+",stl):
if len(x)>3:
return False
return True
print validate([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 16, 20])
print validate([1, 2, 3, 6, 7, 8, 9, 11, 12, 16, 17, 18, 19, 22, 23])
產量
False
True
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.