Skip to content

Instantly share code, notes, and snippets.

@npodonnell
Last active July 19, 2024 00:16
Show Gist options
  • Save npodonnell/5d8c93cff1b9d771b3f5b48309d20ef4 to your computer and use it in GitHub Desktop.
Save npodonnell/5d8c93cff1b9d771b3f5b48309d20ef4 to your computer and use it in GitHub Desktop.
# N. P. O'Donnell, 2024
from typing import Iterator
def generate_combinations(elements: list[any], count: int) -> Iterator[list[int]]:
"""
Non-recursive generation of combinations.
:param elements: Elements from which to make combinations.
:param count: Size of each combination.
:return: Each combination.
"""
indexes = [i for i in range(count)]
while indexes and indexes[-1] != len(elements):
a = [elements[i] for i in indexes]
ei = -1
while indexes[0] != len(elements) - count + 1:
indexes[ei] += 1
for fi in range(ei + 1, 0):
indexes[fi] = indexes[fi - 1] + 1
if indexes[ei] > len(elements) + ei:
ei -= 1
else:
break
yield a
def main():
for c in generate_combinations(['a', 'b', 'c', 'd', 'e', 'f'], 4):
print(c)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment