简体   繁体   English

列表中总和等于或小于给定数字的元素列表

[英]list of elements from a list that sum is equal or less than to a given number

n = [5, 5, 4, 6] # number of list
X = 8 # user have to pass 2 input has X, Y.
Y = 8
result1 = [5] or [5] or [4] or [6] # if I choose 5. n = [5,4,6]
# total = sum(result1).
# total <= user X.
result2 = [5] or [4] or [6]
# total = sum(result2).
# total <= user Y. 
Ans : 2

n = [6,5,2,1,8] 
X = 17
Y = 5
X = [8, 6, 2, 1] 
Y = [5] 
Ans: 5

n = [6,5,5,4,3] 
X = 8 
Y = 9
X = [5,3] # if I choose 5,3 remaining list of elements will be [6,5,4]
Y = [5,4]
Ans : 4

1.I was unable to find this logic trick. 1.我找不到这个逻辑技巧。 so kindly help me out.所以请帮助我。 2.I tried to solve like Subset Sum. 2.我试着像子集和一样解决。 But still I couldn't figure out logic.但我仍然无法弄清楚逻辑。 Note: using python language.注意:使用python语言。

Unless you are looking for a solution that maximizes the two values, you can get the closest sum for each number (removing the items of the first result from the list before the second search).除非您正在寻找最大化两个值的解决方案,否则您可以获得每个数字的最接近的总和(在第二次搜索之前从列表中删除第一个结果的项目)。

If that is the case, you can approach it recursively by picking each number as the first in the combination and recursing with the remaining numbers to get close to the remaining sum.如果是这种情况,您可以通过选择每个数字作为组合中的第一个数字并使用剩余数字递归以接近剩余总和来递归处理它。

To process Y, you'll need a second function that removes (subtracts) the X result from your list.要处理 Y,您需要第二个函数从列表中删除(减去)X 结果。

def sumless(A,S):
    if not S: return []       # target reached
    closest = []              # track closest combo
    for i,a in enumerate(A):  # try each number as start of combo
        if a>S: continue      # skip nnumbers that are too large
        sl = [a] + sumless(A[i+1:],S-a) # find closest with rest
        if sum(sl)>=sum(closest):  
            closest = sl      # track closest combo
    return closest


def subtract(A,B):
    B = B.copy()
    return [a for a in A if a not in B or B.pop(B.index(a))*0 ]

Output:输出:

n = [5,5,4,6] 
X = 8
Y = 8
Xn = sumless(n,X)
Yn = sumless(subtract(n,Xn),Y)
print("X",Xn) # [6]
print("Y",Yn) # [5]

n = [6,5,2,1,8] 
X = 17
Y = 5
Xn = sumless(n,X)
Yn = sumless(subtract(n,Xn),Y)
print(Xn) # [6,2,1,8]
print(Yn) # [5]

n = [6,5,5,4,3] 
X = 8 
Y = 9
Xn = sumless(n,X)
Yn = sumless(subtract(n,Xn),Y)
print(Xn) # [5,3]
print(Yn) # [5,4]

If you do need to get the largest possible 'closest' sums, you will need to combine all subsets of the two targets and find the best pair of subsets (ie where the total sum is greatest):如果您确实需要获得最大可能的“最接近”总和,则需要组合两个目标的所有子集并找到最佳的一对子集(即总和最大的地方):

def sumGen(A,S):                        # sum set generator
    if not S: return                    # target reached
    for i,a in enumerate(A):            # try each number as start 
        if a>S: continue                # skip if too large
        yield [a]                       # return single value
        for sl in sumGen(A[i+1:],S-a):  # combine rest
            yield [a]+sl                # return longer combos

def twoSums(A,X,Y):
    bestX,bestY,bestSum = [],[],0       # track closest pair of combos
    for Xn in sumGen(A,X):              # subsets <= X
        for Yn in sumGen(subtract(A,Xn),Y): # subsets <= Y (from rest)
            if sum(Xn)+sum(Yn)>bestSum:     # track closest
                bestX,bestY,bestSum = Xn,Yn,sum(Xn)+sum(Yn)
    return bestX,bestY

Output: (same as above given that your examples don't highlight the distinction between a naive search and an optimized one)输出:(与上面相同,因为您的示例没有突出简单搜索和优化搜索之间的区别)

n = [5,5,4,6] 
X = 8
Y = 8
print(*twoSums(n,X,Y)) # [6],[5]


n = [6,5,2,1,8] 
X = 17
Y = 5
print(*twoSums(n,X,Y)) # [6, 2, 1, 8] [5]

n = [6,5,5,4,3] 
X = 8 
Y = 9
print(*twoSums(n,X,Y)) # [5, 3] [5, 4]

This would make a difference though:不过,这会有所作为:

n = [6,5,5,4,3,2] 
X = 9 
Y = 15
Xn = sumless(n,X)
Yn = sumless(subtract(n,Xn),Y)
print(Xn) # [4,3,2] = 9
print(Yn) # [6,5]   = 11
print(*twoSums(n,X,Y)) # [6, 3] [5, 5, 4] = 9, 14

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何打印列表的元素,其总和等于 python 中的给定数字? - how to print elements of a list whose sum is equal to a given number in python? 使用小于或等于给定列表的元素生成列表 - Generate lists with elements less or equal to the given list 从列表中创建子列表,且子列表的总和小于给定的数字 - Making sublists from a list with sum of sublist being less than a given number 从整数列表中,获取最接近并小于给定值的数字 - from list of integers, get number closest to and less than a given value 如果元素总和为给定数字,则追加到列表中 - appending in list if sum of elements makes given number sys.getsizeof(list) 返回小于其元素的总和 - sys.getsizeof(list) returns less than the sum of its elements 从连续元素之间的差异小于特定数字的列表创建嵌套列表 - create a nested list from a list where where the difference between consecutive elements is less than a particular number 总和小于或等于给定数字的二维数组中的最大成本值 - maximum cost value in a 2D array having sum less or equal than a given number 总和小于给定总和的最大子集 - Largest Subset whose sum is less than equal to a given sum 如果另一个列表中元素的差异小于某个值,如何对列表的元素求和 - How to sum the elements of a list if the difference of elements in another list is less than a certain value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM