![]() Result += binations(nums, i)Īpproach 1: Straightforward recursion def subsets(nums): Other possible approaches Approach 0: Using combinations import itertools Return _iterable(combinations(s, r) for r in range(len(s)+1)) Probably this is the best way to go: import itertools The intertools' documentation has a self-contained example, why not use it in your code? Some people suggested using more_itertools.powerset, but it has exactly the same implementation! If I were you I wouldn't install the whole package for one tiny thing. I decided to create a reference answer for the future. I like this problem because there are so many ways to implement it. > list(sorted( combs(range(5)), key=len)) It visits every element in turn, and either takes it or leaves it (we can directly see the 2^N cardinality from this algorithm). (We don't realistically have to worry about running out of stack space since there's no way we could process all N! permutations.) This requires that the items are unique, or else ]īelow is a "standard recursive answer", similar to the other similar answer. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |