2

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

RULES 2 inputs:

  • 1st input: define the length of the output, as an integer.
  • 2nd input: write all elements that user want, as a string, that will be part of the output.

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

  • 1st. Find all possible substrings of the length entered in the input, [] * 1st input.

  • 2nd. Form all the possible combinations with the elements entered in the 2nd input.

  • 3rd. Print all possible combinations of length [] * 1st input, with the elements of the 2nd input, without repeating.

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!

Arty
  • 14,883
  • 6
  • 36
  • 69

1 Answers1

3

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']
Arty
  • 14,883
  • 6
  • 36
  • 69