简体   繁体   English

具有最大长度 m 和公差 k 的子列表的最小数量

[英]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,并输出具有以下属性的最小数字子列表:

  • length <= m长度 <= 米
  • smallest item in sublist + 2k >= largest item in sublist子列表中的最小项 + 2k >= 子列表中的最大项

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.

相关问题 根据最小子列表的长度对子列表进行下采样 - Downsample sublists based on length of smallest sublist 写一个 function,给定自然数 n,m,确定最小的自然数 k 使得 n^k >= m,时间为 O(log k) - Write a function that, given natural numbers n, m, determines the smallest natural number k such that n^k >= m, in time O(log k) 如何获取字典中的第一个K最小数字 - how to get first K smallest number in a dictionary Python算法在未排序的数组中找到k个最小数字的索引? - Python algorithm to find the indexes of the k smallest number in an unsorted array? 两个排序数组并找到第 k 个最小的数字 - two sorted array and find k'th smallest number 算法(Python):找到大于k的最小数 - Algorithm (Python): find the smallest number greater than k 使用递归进行 K 次交换后的最大数量 - Maximum number after K swaps using recursion 给定Python中的列表列表,返回最大长度的唯一值子列表 - Given a list of lists in Python, return the maximum length uniquely-valued sublists 将子列表截断到最小长度 - Truncate sublists to the lowest length python scipy eigs:无论收敛容差如何,在最大迭代次数后返回特征向量 - python scipy eigs : return eigenvector after maximum number of iterations whatever the convergence tolerance
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM