[英]smallest number of sublists with maximum length m and tolerance k
I need to create a program that takes a sorted list of integers, x, and outputs the smallest number sublists with the following properties:我需要创建一个程序,它接受一个排序的整数列表 x,并输出具有以下属性的最小数字子列表:
it is important to note I don't actually need to find the sublists themselves just the how many of them重要的是要注意我实际上并不需要自己找到子列表,只需要找到其中的数量
I've tried writing this function but the number it creates is too high.我试过写这个 function 但它创建的数字太高了。 I know it has to do with the way i'm spliting the list but I can't figure out a better way to do it.
我知道这与我拆分列表的方式有关,但我想不出更好的方法。
x is the sorted list, k is the tolerance, m is the max sublist length, n is the length of x, time is the number of sublists 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
Use combinations
to find the ordered combinations of a list.使用
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.