Last active
December 26, 2024 00:34
-
-
Save linj121/f3f27808a0cd57ec9f7a998fd386b4b6 to your computer and use it in GitHub Desktop.
Generate combinations from a pool of elements
This file contains hidden or 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
#!/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]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
comb.py [number]
Example