Python Forum
a solution to the Subset Sum Problem
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
a solution to the Subset Sum Problem
#5
For me, this is an overuse of generator expressions. When they are not needed, it is better (and it may actually be faster) to write ordinary syntax like so
from itertools import combinations

def solve(items):
    for length in range(1, len(items)):
        for subset in combinations(items, length):
            if sum(subset) == 0:
                print('A solution for set {} is {}'.format(items, subset))
                return
    print('There is no solution for set {}'.format(items))

if __name__ == '__main__':
    solve({-3, -10, 2, 5, 7, 13})
Generator expressions are most useful when you want to create and manipulate 'sequences' of things.
Reply


Messages In This Thread
a solution to the Subset Sum Problem - by league55 - Jan-15-2018, 02:56 AM
RE: a solution to the Subset Sum Problem - by Gribouillis - Jan-16-2018, 07:30 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020