[英]smallest number of sublists with maximum length m and tolerance k
我需要創建一個程序,它接受一個排序的整數列表 x,並輸出具有以下屬性的最小數字子列表:
重要的是要注意我實際上並不需要自己找到子列表,只需要找到其中的數量
我試過寫這個 function 但它創建的數字太高了。 我知道這與我拆分列表的方式有關,但我想不出更好的方法。
x是排序列表,k是公差,m是最大子列表長度,n是x的長度,時間是子列表的數量
def split(x,k,m,n):
time = 0
if n<=m:
try:
if x[-1]<=x[0]+2*k:
time +=1
else:
time += split(x[0:n-1],k,m,n-1)
time += split(x[n-1:n],k,m,1)
except:
pass
else:
time += split(x[0:n-m],k,m,n-m)
time += split(x[n-m:n],k,m,m)
return time
使用combinations
來查找列表的有序組合。
from itertools import combinations
def split(lst, t, m):
n = len(lst)
counter = 0
for i in range(1, m+1):
for c in combinations(x, r=i):
if min(c) + t >= max(c):
counter += 1
return counter
x = [1, 2, 5, 9]
t, m = 1, 3
c = split(x, t, m)
print(f'{c}-sublists of at most length {m} with tolerance {t}')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.