Skip to content

Instantly share code, notes, and snippets.

@linj121
Last active December 26, 2024 00:34
Show Gist options
  • Save linj121/f3f27808a0cd57ec9f7a998fd386b4b6 to your computer and use it in GitHub Desktop.
Save linj121/f3f27808a0cd57ec9f7a998fd386b4b6 to your computer and use it in GitHub Desktop.
Generate combinations from a pool of elements
#!/ucrt64/bin/python
from typing import List
from sys import argv
# eg. pool = ['0', '1']
# n = 3
# total count = 2 ** 3 = 8
# 0 0 0
# 0 0 1
# 0 1 0
# 0 1 1
# 1 0 0
# 1 0 1
# 1 1 0
# 1 1 1
pool: List[str] = ['🥵', '🤢', '🥶']
def getCombinations(n: int) -> List[str]:
res: List[str] = []
def dfs(s: str) -> None:
if len(s) == n:
res.append(s)
return
for item in pool:
dfs(s + item)
dfs("")
return res
def getCombinationsIterative(n: int) -> List[str]:
res: List[str] = []
stack: List[str] = [""]
while stack:
s = stack.pop()
if len(s) == n:
res.append(s)
continue
for item in reversed(pool):
stack.append(s + item)
return res
def isInt(s: str) -> bool:
if not s:
return False
try:
int(s)
return True
except ValueError:
return False
if __name__ == "__main__":
if len(argv) != 2 or not isInt(argv[1]):
print("Usage: comb [number]")
exit(1)
n = int(argv[1])
totalCount = len(pool) ** n
result = getCombinationsIterative(n)
for i, s in enumerate(result):
# spaces are added as paddings
print(str(i) + " " * (1 + len(str(totalCount)) - len(str(i))) + s)
print("Generated " + str(totalCount) + " combinations of length " + argv[1])
@linj121
Copy link
Author

linj121 commented Dec 25, 2024

Usage

comb.py [number]

Example

$ ./comb.py 3
0  🥵🥵🥵
1  🥵🥵🤢
2  🥵🥵🥶
3  🥵🤢🥵
4  🥵🤢🤢
5  🥵🤢🥶
6  🥵🥶🥵
7  🥵🥶🤢
8  🥵🥶🥶
9  🤢🥵🥵
10 🤢🥵🤢
11 🤢🥵🥶
12 🤢🤢🥵
13 🤢🤢🤢
14 🤢🤢🥶
15 🤢🥶🥵
16 🤢🥶🤢
17 🤢🥶🥶
18 🥶🥵🥵
19 🥶🥵🤢
20 🥶🥵🥶
21 🥶🤢🥵
22 🥶🤢🤢
23 🥶🤢🥶
24 🥶🥶🥵
25 🥶🥶🤢
26 🥶🥶🥶
Generated 27 combinations of length 3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment