Reputation: 27
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:
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!
Upvotes: 2
Views: 227
Reputation: 16747
Corrected code:
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