Skip to content

Instantly share code, notes, and snippets.

@wafflecomposite
Created February 28, 2020 14:09
Show Gist options
  • Save wafflecomposite/570ad71d2a1a9a6b7a743b0e7aa520ac to your computer and use it in GitHub Desktop.
Save wafflecomposite/570ad71d2a1a9a6b7a743b0e7aa520ac to your computer and use it in GitHub Desktop.
Python unique combinations generator
#!/usr/bin/env python
# coding=utf-8
def __ten_to_listed_convert(options, list_length, n):
if n == 0:
return [options[0]]* list_length
nums = []
while n:
n, r = divmod(n, len(options))
nums.append(options[r])
while len(nums) < list_length:
nums.append(options[0])
return [l for l in reversed(nums)]
def generate_combinations(options_list, list_length):
variants = []
for i in range(len(options_list) ** list_length):
variants.append(__ten_to_listed_convert(options_list, list_length, i))
return variants
# >>> generate_combinations([0,1],3)
# [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]
# >>> generate_combinations(["r","g","b"],2)
# [['r', 'r'], ['r', 'g'], ['r', 'b'], ['g', 'r'], ['g', 'g'], ['g', 'b'], ['b', 'r'], ['b', 'g'], ['b', 'b']]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment