I'm trying to create an algorithm that will return all the possible combinations from a list of elements (fruits in this example). The challenge is that the elements can be grouped in different sizes and the number of elements on the result list must be equal to n, where n is the list size. In short, all the elements must be on the final list.
Here is an example:
fruits = ['Apple', 'Orange', 'Banana', 'Watermelon']
We can quickly find all the combinations without repetition from size 0 to n as follows:
from itertools import combinations
fruits = ['Apple', 'Orange', 'Banana', 'Watermelon']
for L in range(0, len(fruits) + 1):
for subset in combinations(fruits, L):
print(subset)
The result:
()
('Apple',)
('Orange',)
('Banana',)
('Watermelon',)
('Apple', 'Orange')
('Apple', 'Banana')
('Apple', 'Watermelon')
('Orange', 'Banana')
('Orange', 'Watermelon')
('Banana', 'Watermelon')
('Apple', 'Orange', 'Banana')
('Apple', 'Orange', 'Watermelon')
('Apple', 'Banana', 'Watermelon')
('Orange', 'Banana', 'Watermelon')
('Apple', 'Orange', 'Banana', 'Watermelon')
However, what I'm looking for is different because all the elements must be present. Examples:
('Apple',) ('Orange',) ('Banana',) ('Watermelon',) is valid (1),(1),(1),(1)
('Apple',) ('Orange',) ('Banana', 'Watermelon') is valid (1),(1),(2)
('Apple',) ('Banana',) ('Orange', 'Watermelon') is valid (1),(1),(2)
('Apple',) ('Watermelon',) ('Orange', 'Banana') is valid (1),(1),(2)
('Apple',) ('Orange', 'Banana', 'Watermelon') is valid (1),(3)
...
('Apple', 'Orange') ('Banana', 'Watermelon') is valid (2),(2)
('Apple', 'Orange', 'Banana', 'Watermelon') is valid (4)
Is there an easy way to generate this in Python?