Santiago Pérez
Santiago Pérez

Reputation: 27

RECURSION in PYTHON to make all possible PERMUTATIONS without repeat

I have written a code using recursion, which follows the following rules:

RULES 2 inputs:

With these two inputs, the program must do the following:

CODE My code is as follows and it fails to give the length of the output:

def stringPermutations(string, prefix, permutation_list):
    if len(string) == 0:
        permutation_list.append(prefix)
    else:
        for i in range(len(string)):
            rem = string[0:i] + string[i + 1:]
            stringPermutations(rem, prefix + string[i], permutation_list)
    return sorted(list(dict.fromkeys(permutation_list)))
def main():
    n = int(input("write size: "))
    b = str(input("Write String: "))
    permutation_list = [] * n
    print(stringPermutations(b, " ", permutation_list))

if __name__ == '__main__':
    main()

EXAMPLE OF HOW SHOULD WORK:

Input:

2
+x#

Output:

+x
+#
x+
x#
#+
#x

Could someone tell me why it doesn't work?

Thank you very much for the help!

Upvotes: 2

Views: 227

Answers (1)

Arty
Arty

Reputation: 16747

Corrected code:

Try it online!

def stringPermutations(n, string, prefix, permutation_list):
    if n == 0:
        permutation_list.append(prefix)
    else:
        for i in range(len(string)):
            rem = string[0:i] + string[i + 1:]
            stringPermutations(n - 1, rem, prefix + string[i], permutation_list)
    return permutation_list

def main():
    n = int(input("write size: "))
    b = str(input("Write String: "))
    permutation_list = [] * n
    print(stringPermutations(n, b, "", permutation_list))

if __name__ == '__main__':
    main()

Input:

2
+x#

Output:

['+x', '+#', 'x+', 'x#', '#+', '#x']

Upvotes: 3

Related Questions