Last active
October 26, 2022 06:30
-
-
Save ALiwoto/bd92d3cd7297e3cf6af5e9a95782ed4c to your computer and use it in GitHub Desktop.
Combinations of n numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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