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!

1 Answer 1

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']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.