How to get all possible combinations of a list’s elements?
Have a look at itertools.combinations:
itertools.combinations(iterable, r)
Return r length subsequences of elements from
the input iterable.Combinations are emitted in lexicographic sort order. So, if the
input iterable is sorted, the
combination tuples will be produced in
sorted order.
Since 2.6, batteries are included!
How to create all possible combinations of a list which has lists inside of it?
Possible solution is the following:
from itertools import combinations
lst = [['Macau', 'United Kingdom', 'India'], ['United States', 'China'], ['China', 'Australia']]
print([list(combinations(group, 2)) for group in lst])
Returns
[[('Macau', 'United Kingdom'),
('Macau', 'India'),
('United Kingdom', 'India')],
[('United States', 'China')],
[('China', 'Australia')]]
Making all possible combinations of a list
Simply use itertools.combinations
. For example:
import itertools
lst = [1, 2, 3]
combs = []
for i in xrange(1, len(lst)+1):
combs.append(i)
els = [list(x) for x in itertools.combinations(lst, i)]
combs.append(els)
Now combs
holds this value:
[1, [[1], [2], [3]], 2, [[1, 2], [1, 3], [2, 3]], 3, [[1, 2, 3]]]
Yes, it's slightly different from the sample output you provided, but in that output you weren't listing all possible combinations.
I'm listing the size of the combination before the actual list for each size, if what you need is simply the combinations (without the size, as it appears in your sample output) then try these other version of the code:
import itertools
lst = [1, 2, 3]
combs = []
for i in xrange(1, len(lst)+1):
els = [list(x) for x in itertools.combinations(lst, i)]
combs.extend(els)
Now combs
holds this value:
[[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
generating list of every combination without duplicates
There will certainly be more sophisticated/efficient ways of doing this, but here's an approach that works in a reasonable amount of time for your example and should be easy enough to adapt for other cases.
It generates unique teams and unique combinations thereof, as per your specifications.
from itertools import combinations
# this assumes that team_size * team_num == len(players) is a given
team_size = 3
team_num = 4
players = list('ABCDEFGHIJKL')
unique_teams = [set(c) for c in combinations(players, team_size)]
def duplicate_player(combo):
"""Returns True if a player occurs in more than one team"""
return len(set.union(*combo)) < len(players)
result = (combo for combo in combinations(unique_teams, team_num) if not duplicate_player(combo))
result
is a generator that can be iterated or turned into a list with list(result)
. On kaggle.com, it takes a minute or so to generate the whole list of all possible combinations (a total of 15400, in line with the computations by @beaker and @John Coleman in the comments). The teams are tuples of sets that look like this:
[({'A', 'B', 'C'}, {'D', 'E', 'F'}, {'G', 'H', 'I'}, {'J', 'K', 'L'}),
({'A', 'B', 'C'}, {'D', 'E', 'F'}, {'G', 'H', 'J'}, {'I', 'K', 'L'}),
({'A', 'B', 'C'}, {'D', 'E', 'F'}, {'G', 'H', 'K'}, {'I', 'J', 'L'}),
...
]
If you want, you can cast them into strings by calling ''.join()
on each of them.
Getting all possible combination for [1,0] with length 3 [0,0,0] to [1,1,1]
You're looking for a Cartesian product, not a combination or permutation of [0, 1]
. For that, you can use itertools.product
.
from itertools import product
items = [0, 1]
for item in product(items, repeat=3):
print(item)
This produces the output you're looking for (albeit in a slightly different order):
(0, 0, 0)
(0, 0, 1)
(0, 1, 0)
(0, 1, 1)
(1, 0, 0)
(1, 0, 1)
(1, 1, 0)
(1, 1, 1)
How to generate all possible combinations from the letters of strings in a list
I can propose you a trivial algorithm to do the same, it is using recursion:
def associations(entry):
while len(entry) > 2:
to_treat_later = entry.pop()
print(f"We will treat {to_treat_later} later")
entry = associations(entry)
entry.append(to_treat_later)
else:
print(f"we can start with {entry}")
associated_entry = []
for elt_1 in entry[0]:
for elt_2 in entry[1]:
associated_entry.append(f"{elt_1}{elt_2}")
return [associated_entry]
def convert_entry(entry):
converted_entry = []
for elt in entry:
list_elt = []
for letter in elt:
list_elt.append(letter)
converted_entry.append(list_elt)
return converted_entry
the_entry = ["jkl", "ghi", "def", "cfe"]
associations(convert_entry(the_entry))
Related Topics
How to Sort Unicode Strings Alphabetically in Python
Including Non-Python Files with Setup.Py
Read and Write CSV Files Including Unicode with Python 2.7
Basic Http File Downloading and Saving to Disk in Python
Matplotlib: Save Plot to Numpy Array
Calculating Direction of the Player to Shoot Pygame
Loop That Also Accesses Previous and Next Values
How to Pass Arguments in Pytest by Command Line
How to Overload _Init_ Method Based on Argument Type
Python Numpy Valueerror: Operands Could Not Be Broadcast Together with Shapes
How to Add Both File and JSON Body in a Fastapi Post Request
Multiprocessing: Sharing a Large Read-Only Object Between Processes
Convert Pandas Dataframe to Nested JSON
How to Insert a Column at a Specific Column Index in Pandas
Does Python Urllib2 Automatically Uncompress Gzip Data Fetched from Webpage