-1

trying to make a function permutations(s) that takes a set of elemnts and returns a collection of all its permutations, where the permutations are of type tuple. Here is my code:

def permutations(s):
str1 = list(s)
if len(str1) <= 1:
    print(s)
else:
    for i in range(0, len(s)):
        str1[0], str1[i] = str1[i], str1[0]
        permutations(str1[1:])
        str1[0], str1[i] = str1[i], str1[0]

given this input

print(sorted(permutations({1,2,3})))

it should return

[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

but after alot of headache i can only seem to get

[3][2][3][1][1][2]
Martin Lopez
  • 103
  • 1
  • 16
  • Your if statement checks that the length of s is 1, then prints it. why do you expect it to have 3 elements? – MFisherKDX Mar 14 '19 at 23:06

2 Answers2

1

You can use permutations from itertools in the standard library to compute all permutations

from itertools import permutations
out = list(permutations({1,2,3}))
print(out)
#Output
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
amanb
  • 5,276
  • 3
  • 19
  • 38
0

You are probably looking for an algorithm, e.g. recursive algorithm. Some times ago I wrote it (as exercise):

def get_permutations(array):
    result = list()

    def permute(x, index, acc=[0] * len(array)):
        if index == len(array):
            result.append(acc[:])
            acc = list()
            return None
        for j in range(len(x)):
            acc[index] = x[j]
            _x = x[:]
            _x.pop(j)
            permute(_x, index + 1, acc)

    permute(array, 0)
    return result
bubble
  • 1,634
  • 12
  • 17