简体   繁体   中英

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:

  • length <= m
  • smallest item in sublist + 2k >= largest item in sublist

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. 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

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.

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}')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM