Monday, November 13, 2017

Permutations

Permutations

Permutations with Recursion

In [1]:
def permutation(s):
    if len(s) == 1:
        return [s]

    permu_list = []
    for a in s:
        remaining_elements = s[:]
        remaining_elements.remove(a)
        b = permutation(remaining_elements) 

        for t in b:
            permu_list.append([a] + t)

    return permu_list
In [2]:
n = 1234
s = list(str(1234))
print(s,"\n")
['1', '2', '3', '4'] 

In [3]:
L = permutation(s)
for t in L:
    print(t)
['1', '2', '3', '4']
['1', '2', '4', '3']
['1', '3', '2', '4']
['1', '3', '4', '2']
['1', '4', '2', '3']
['1', '4', '3', '2']
['2', '1', '3', '4']
['2', '1', '4', '3']
['2', '3', '1', '4']
['2', '3', '4', '1']
['2', '4', '1', '3']
['2', '4', '3', '1']
['3', '1', '2', '4']
['3', '1', '4', '2']
['3', '2', '1', '4']
['3', '2', '4', '1']
['3', '4', '1', '2']
['3', '4', '2', '1']
['4', '1', '2', '3']
['4', '1', '3', '2']
['4', '2', '1', '3']
['4', '2', '3', '1']
['4', '3', '1', '2']
['4', '3', '2', '1']