Subset sum Problem

后端 未结 6 1139
Happy的楠姐
Happy的楠姐 2020-12-01 13:32

recently I became interested in the subset-sum problem which is finding a zero-sum subset in a superset. I found some solutions on SO, in addition, I came across a particula

6条回答
  •  情书的邮戳
    2020-12-01 13:58

    The following code works for Python 3.3+ , I have used the itertools module in Python that has some great methods to use.

    from itertools import chain, combinations
    def powerset(iterable):
        s = list(iterable)
        return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

    nums = input("Enter the Elements").strip().split() inputSum = int(input("Enter the Sum You want"))

    for i, combo in enumerate(powerset(nums), 1): sum = 0 for num in combo: sum += int(num) if sum == inputSum: print(combo)

    The Input Output is as Follows:

    Enter the Elements 1 2 3 4
    Enter the Sum You want 5
    ('1', '4')
    ('2', '3')

提交回复
热议问题