Skip to content

Instantly share code, notes, and snippets.

@drmingle
Last active May 4, 2018 13:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drmingle/14834161590de6c7715c85e85b5c39d7 to your computer and use it in GitHub Desktop.
Save drmingle/14834161590de6c7715c85e85b5c39d7 to your computer and use it in GitHub Desktop.
title author date
Create All Combinations of a List
Damian Mingle
05/04/2018

Preliminary

from itertools import combinations_with_replacement

Create a list of objects

# Create a list of math objects to combine
list_of_math_objects = ['calculus', 'geometry', 'logic']

Find all combinations (with replacement) for the list

# Create an object that is an empty list so it can hold our results
combinations = []

# Create a loop for every item in the length of list_of_math_objects
for i in list(range(len(list_of_math_objects))):
    # Finds every combination (with replacement) for each object in the list
    combinations.append(list(combinations_with_replacement(list_of_math_objects, i+1)))
    
# View the output
combinations
[[('calculus',), ('geometry',), ('logic',)],
 [('calculus', 'calculus'),
  ('calculus', 'geometry'),
  ('calculus', 'logic'),
  ('geometry', 'geometry'),
  ('geometry', 'logic'),
  ('logic', 'logic')],
 [('calculus', 'calculus', 'calculus'),
  ('calculus', 'calculus', 'geometry'),
  ('calculus', 'calculus', 'logic'),
  ('calculus', 'geometry', 'geometry'),
  ('calculus', 'geometry', 'logic'),
  ('calculus', 'logic', 'logic'),
  ('geometry', 'geometry', 'geometry'),
  ('geometry', 'geometry', 'logic'),
  ('geometry', 'logic', 'logic'),
  ('logic', 'logic', 'logic')]]
# Generae a flattent list of lists
combinations = [i for row in combinations for i in row]

# View the results
combinations
[('calculus',),
 ('geometry',),
 ('logic',),
 ('calculus', 'calculus'),
 ('calculus', 'geometry'),
 ('calculus', 'logic'),
 ('geometry', 'geometry'),
 ('geometry', 'logic'),
 ('logic', 'logic'),
 ('calculus', 'calculus', 'calculus'),
 ('calculus', 'calculus', 'geometry'),
 ('calculus', 'calculus', 'logic'),
 ('calculus', 'geometry', 'geometry'),
 ('calculus', 'geometry', 'logic'),
 ('calculus', 'logic', 'logic'),
 ('geometry', 'geometry', 'geometry'),
 ('geometry', 'geometry', 'logic'),
 ('geometry', 'logic', 'logic'),
 ('logic', 'logic', 'logic')]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment