Skip to content

Instantly share code, notes, and snippets.

@ogallagher
Last active December 31, 2020 06:51
Show Gist options
  • Save ogallagher/19613f7ba37ec3c3be75871c3bef6599 to your computer and use it in GitHub Desktop.
Save ogallagher/19613f7ba37ec3c3be75871c3bef6599 to your computer and use it in GitHub Desktop.
Generate permutations in python
# dependencies
from typing import Union, List, Generator
# permute method
def permute(options:Union[str,List], places:int=None) -> Generator[List,None,None]:
"""Generate all permutations recursively.
Args:
options = list of possible values per place
places = number of places; default=len(options)
Yields:
a permutation, being length places, each element being an element
from options
"""
on:int = len(options)
if places is None:
places = on
elif places > on:
raise Exception('error: can not permute {} over more than {} places'.format(
options,
on
))
for oi in range(on):
# select option for first place
o:Any = options[oi]
if places > 1:
suboptions:List = options[:oi] + options[oi+1:]
if len(suboptions) == 1:
yield [o, suboptions[0]]
else:
# permute latter places recursively
for suffix in permute(suboptions, places-1):
yield [o] + suffix
else:
# no more places to compute
yield [o]
# end for oi in range(on)
# end permute
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment