![]() ![]() 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.This requires that the order of iteration on items is not random (workaround: don't be insane).This requires that you can call len(.) on items (workaround: if items is something like an iterable like a generator, turn it into a list first with items=list(_itemsArg)).For each binary string, you pick all elements corresponding to a "1". Main idea behind this answer: there are 2^N combinations - same as the number of binary strings of length N. Return ( set(compress(items,mask)) for mask in product(*]*len(items)) ) Here's a lazy one-liner, also using itertools: from itertools import compress, product Return om_iterable(combinations(s, r) for r in range(len(s)+1))įor i, combo in enumerate(powerset(stuff), 1): S = list(iterable) # allows duplicate elements from itertools import chain, combinations Regardless, the fact that the iterable is ultimately turned into a list means it will work with generators (unlike several of the other answers). Note: If the, subtly different, goal is to obtain only combinations of unique elements, change the line s = list(iterable) to s = list(set(iterable)) to eliminate any duplicate elements. The function produces all unique combinations of the list elements of every length possible (including those containing zero and all the elements). Since it's probably one of the better if not the best approach to the problem-and given a little encouragement from another commenter, it's shown below. ![]() However, so far no one has posted it as an answer. ![]() In comments under the highly upvoted answer by H, mention is made of the powerset() recipe in the itertools documentation-including one by Dan himself. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |