简体   繁体   English

从集合中找到等于给定总和的数字组合-Python

[英]Find combination of numbers from set that equal a given sum - Python

Edit: I know this question has been asked a million times, but I can't seem to find anything that works for my specific scenario. 编辑:我知道这个问题被问了一百万遍,但是我似乎找不到适合我的特定情况的任何东西。 For context purposes, I'm running Python 3.6 on a Windows OS. 出于上下文目的,我在Windows操作系统上运行Python 3.6。

I've tried the following code: 我尝试了以下代码:

def subset_sum(numbers, target, partial=[]):
    s = sum(partial)

    # check if the partial sum is equals to target
    if s == target:
        print(f"sum({partial})={target}")
        #print("sum({})={}".format(partial, target))
    if s == target:
        return  # if we reach the number why bother to continue

    for i in range(len(numbers)):
        n = numbers[i]
        #remaining = numbers[:i] + numbers[i+1:]
        remaining = numbers[i+1:]
        subset_sum(remaining, target, partial + [n])

s= [-765143.910000006, -14522903.45, -185360.52, -161161.559999994, -31947.78, 167450, 47715.46, -1725.24, -1532.91, 338381.23, -40962.19, -321.869999999997, -28215.17, -66345.71, 13063.28, -389.37, 6215992.30000001, 2193804.53000001, -458374.52, 106792.609999979, -335194.01, 203687.94, 91147.0500000003, -18.9500000000004, -19.1200000000016, -2.31494823310641]

k= [-2191.62999999806, 5481451.91, -17941.98, 166.719999999996, -2.72848410531878, -3.42659234320308, -13109322.84, -5320290.35000001, -977974.9, 2224562.69999999, 404360.300000002, 579934.88, 1131275.75, 3889264.3, 3364573.99000001, 5225874.59, 2191.62999999806, 176248.27, 19925.25, 2090.84, 11461.32, 3457.83, 4655.76, -17929.46, 449.48, 2187.61, 3084.35, 176274, 48909.78, 55.43]

x= [14795.41, 6497.05, 324.6, 5589.19, 2224.45, 5571.92, 3575.24, 3041.33, 4658.22, 6244.92, 433.59, 2146.55, 1489, 28686.93, 205, 2267.76, 1532.91, -12539.19, 46221.03, 9959.25, 20175.14, 735, 9449, 26880, 426.12, 1355.18, 220.48, 695.88, -389.99, -1.12, -37.56]

v= [-1.96999999999248, 1.58761892521397, -2.1600499167107, -2791.41999999999, 606814.85, -19.1200000000016, -1.49999999999995, -54.3300000000086, 34608.19, -661601.97, 3149949.45, 32247.78, 350.64, 328574.84, 42461.52, 1273, 6635.21, 504, -3100.27, 9868.07, 148179.28, 29205.46, -206.65, -552]

y = [s+k+x+v]

if __name__ == "__main__":
    subset_sum(y, -765143.910000006)

This line 这条线

print(sum(%s)=%s) % (partial, target)

is wrong because you are using patterns of string formatting for things that are not strings. 这是错误的,因为您对非字符串使用了字符串格式化模式。 You probably wanted to do 你可能想做

print("sum(%s)=%s" % (partial, target))

and still this is old syntax, you'd prefer the new syntax 仍然是旧语法,您还是希望使用新语法

print("sum({})={}".format(partial, target))

Concerning SyntaxError: you used formatting in incorrect way. 关于SyntaxError:您使用的格式化方式不正确。 More on that on PyFormat site, just quick solution: PyFormat网站上可以找到更多有关此的快速解决方案:

print("sum(%s) =%s" % (partial, target)) 

Your code doesn't work because 您的代码无效,因为

print(sum(%s)=%s) % (partial, target)

Should be 应该

print "sum(%s)=%s" %(partial, target)

Furthermore you need to indent the line after your main declaration 此外,您需要在主声明后缩进行

if __name__ == "__main__":
subset_sum([3,9,8,4,5,7,10],15)

Should be this 应该是这个

if __name__ == "__main__":
  subset_sum([3,9,8,4,5,7,10],15)

Also your code does not work completely as subset_sum([3,9,8,4,5,7,10,-9],1) does not return a result even though it should return [10,-9]=1. 同样,您的代码也无法完全正常工作,因为subset_sum([3,9,8,4,5,7,10,-9],1)即使应返回[10,-9] = 1也不会返回结果。

Furthermore, to improve on your code I'd recommend using memoization to avoid having to calculate the same subset more than once if you are doing this over large sets of numbers. 此外,为了改进您的代码,我建议使用记忆化,以避免对大量数字进行相同子集计算的情况。

I believe this code works: 我相信这段代码有效:

def subset_sum(numbers, target, partial=[]):
    s = sum(partial)
    if len(numbers) == 0:
        return
    elif s == target:
        print("sum({})={}".format(partial, target))
        return
    else:
        for i in range(len(numbers)):
            n = numbers[i]
            remaining = numbers[:i] + numbers[i+1:]
            subset_sum(remaining, target, partial + [n])

y = [-15, 5, 10, -10, 3, 7, -4, -2]

if __name__ == "__main__":
    subset_sum(y, 6)

It can be extremely slow as the number of possible combinations increases, which you can count mathematically and grows astronomically, so you feel like it is never going to end. 随着可能组合数量的增加,它可能会非常慢,您可以用数学方法进行计数并以天文数字的方式进行增长,因此您感觉它永远不会结束。

NB I don't have Python 3.6 so the formatting will remain old-school here. 注意:我没有Python 3.6,因此这里的格式仍然是老式的。

Edit: Another note is that you should never use equality between floats , like in your termination condition with the new input you propose. 编辑:另一个注意事项是,您永远不要使用浮点数之间的相等性 ,例如在终止条件下使用建议的新输入。 You can have a look at this answer for inspiration for a if isclose(s, target) condition. 您可以查看此答案,以了解if isclose(s, target)条件的灵感。

暂无
暂无

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

相关问题 如何找到它们的总和等于给定数字的数字? - How to find the numbers that their sum equal to a given number? 查找一个数字是否是给定集合中两个或更多个数字的可能总和--python - Find if a number is a possible sum of two or more numbers in a given set - python 在数字组合中求和 - Find the Highest Sum in a Combination of Numbers 给定大量数字,如何找到总和为特定 X 的每个数字组合? - How to find every combination of numbers that sum to a specific X given a large array of numbers? 快速 python 算法,用于从子集总和等于给定比率的数字列表中找到所有可能的分区 - Fast python algorithm to find all possible partitions from a list of numbers that has subset sums equal to given ratios 如何编写 python 代码来计算给定数字的所有组合,这些组合可以求和给定数字? - how to write a python code to calculate all the combination of given numbers that can sum up to a given number? 从两个列表中找到2个数字的最快方法,总和等于x - The fastest way to find 2 numbers from two lists that in sum equal to x 总和等于 0 的一组数字(也是负数)的最大子集 - Largest subset from set of numbers (also negative) having sum equal 0 如何找到给定特定组的组合总和? - How to find a sum of combination given specific group? 查找总和最接近给定数字的所有数字 python - Find all numbers that sum closest to a given number python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM