Skip to content

Instantly share code, notes, and snippets.

@evtn
Last active July 3, 2021 13:39
Show Gist options
  • Select an option

  • Save evtn/3f6e1ba8f4572c60e723f93cbe838e63 to your computer and use it in GitHub Desktop.

Select an option

Save evtn/3f6e1ba8f4572c60e723f93cbe838e63 to your computer and use it in GitHub Desktop.
def combinations(letters, length):
current = [0] * length
result = []
while True:
i = len(current) - 1
result.append([letters[x] for x in current])
current[i] += 1
while current[i] == len(letters):
current[i] = 0
i -= 1
current[i] += 1
if i == -1:
break
return result
def combinations_generator(letters, length):
current = [0] * length
while True:
i = len(current) - 1
yield [letters[x] for x in current]
current[i] += 1
while current[i] == len(letters):
current[i] = 0
i -= 1
current[i] += 1
if i == -1:
break
def combinations_recursive(letters, length):
result = []
for letter in letters:
if length > 1:
for combination in combinations_recursive(letters, length - 1):
result.append([letter, *combination])
else:
result.append([letter])
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment