Skip to content

Instantly share code, notes, and snippets.

@ALiwoto
Last active October 26, 2022 06:30
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 ALiwoto/bd92d3cd7297e3cf6af5e9a95782ed4c to your computer and use it in GitHub Desktop.
Save ALiwoto/bd92d3cd7297e3cf6af5e9a95782ed4c to your computer and use it in GitHub Desktop.
Combinations of n numbers
res = []
n = 3
def solve(size, ans):
global res, n
if size == 1 :
for i in range(1, n + 1):
res.append(ans + str(i))
else:
for i in range(1, n + 1) :
solve(size - 1, ans + str(i) + ' ')
solve(n, "")
for i in res:
print(i)
def _increment(elements, n):
element_off = n - 1
while True:
if elements[element_off] == n:
elements[element_off] = 1
if element_off == 0:
return False
element_off -= 1
else:
elements[element_off] += 1
return True
def combos(n):
assert n >= 1 and n <= 9
elements = [1 for _ in range(n)]
escape = False
while not escape:
yield ' '.join(str(i) for i in elements)
escape = not _increment(elements, n)
for i in combos(4):
yield i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment