Skip to content

Instantly share code, notes, and snippets.

@cleoold
Created May 12, 2019 15:51
Show Gist options
  • Save cleoold/be7feb5209a169dd2a1d1a0f6d0f4d2d to your computer and use it in GitHub Desktop.
Save cleoold/be7feb5209a169dd2a1d1a0f6d0f4d2d to your computer and use it in GitHub Desktop.
getting all permutations in python with eval
# getting all permutations of N items in lst in python with eval
# iterable Int -> [(...) (...) ...]
def permute(lst, N):
if N == 0 or N > len(lst):
return []
elif N < 0:
raise ValueError('Second argument must be non-negative.')
item = tuple(('i' + str(d) for d in range(N))) # tuple
itemStr = '(' + ','.join(item) + ')' # str
forSentence = ' '.join(' for ' + i + ' in _lst ' for i in item).replace('_lst', str(list(lst))) # str
a = '[' + itemStr + forSentence + 'if len(set(' + itemStr + ')) == ' + str(N) + ']'
return eval(a)
# eg: len(permute('1234', 3)) -> 24
# getting all permutations in lst
def permuteself(nums):
if len(nums) == 0:
return []
from functools import reduce
return [tuple(i) for i in reduce(lambda x, y: [str(a) + str(b) for a in x for b in y if str(b) not in str(a)], [nums] * len(nums))]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment