Python如何实现随机组合结果元组重复数量不能超过某个值?
请各位高手指点思路,能附代码万分感谢!
1、现有Excel若干行(很多),每行都有不连续的整数组成(数量不定);
2、现需要在1-45中随机选取5个不重复的数,按从小到大排列;
3、要求:随机组合的结果中的元素与Excel每行元素重复数量不能超过4个(重复3个、2个、1个、0个)
4、输出所有符合要求的结果
回答
如果随机生成一个
from random import randint, sampleimport pandas as pd
excel = pd.read_excel(r"d:\test.xlsx")
rows=excel.values #[]
# for i in range(20):
# rows.append([randint(1,50) for _ in range(randint(10,30))])
data = range(1,46)
sampleCount=5
def getSample(data):
return sorted(sample(data, sampleCount))
sp = getSample(data)
while True:
count=0
for row in rows:
same = list(set(sp).intersection(set(row))) #交集
if len(same)>=4:
sp = getSample(data)
break
else:
count = count + 1
if count == len(rows):
break
print(sp)
所有可能
from random import randint, sample
import pandas as pd
import itertools
excel = pd.read_excel(r"d:\test.xlsx")
rows=excel.values #[]
# for i in range(20):
# rows.append([randint(1,50) for _ in range(randint(10,30))])
data = range(1,11) #使用45求组合时很慢,这里用10个
sampleCount=5
pers = list(itertools.combinations(data, sampleCount)) #组合
for per in pers:
count=0
for row in rows:
same = list(set(per).intersection(set(row))) # 交集
if len(same) >= 4:
break
else:
count = count + 1
if count== len(rows):
print(sorted(per))
以上是 Python如何实现随机组合结果元组重复数量不能超过某个值? 的全部内容, 来源链接: utcz.com/a/41487.html