Print N-length Combinations From Char List Using Recursion
I have to solve this exercise using recursion. Implement a function in Python which recieves as parameters list of characters and an integer n. The function has to print all the p
Solution 1:
You are quite close. Instead of len(char_list) == 1
, you need to check that the length of your accumulated "pool" list is equal to the parameter n
. However, to create a list to accumulate the combinations, create one additional parameter in the signature of the function:
defprint_sequences(char_list, n, _accum):
iflen(_accum) == n:
print(_accum)
else:
for c in char_list:
print_sequences(char_list, n, _accum+[c])
print_sequences([1, 2, 3, 4], 4, [])
Output:
[1, 1, 1, 1]
[1, 1, 1, 2]
[1, 1, 1, 3]
[1, 1, 1, 4]
[1, 1, 2, 1]
[1, 1, 2, 2]
[1, 1, 2, 3]
[1, 1, 2, 4]
[1, 1, 3, 1]
[1, 1, 3, 2]
[1, 1, 3, 3]
[1, 1, 3, 4]
[1, 1, 4, 1]
[1, 1, 4, 2]
[1, 1, 4, 3]
[1, 1, 4, 4]
[1, 2, 1, 1]
....
Edit: implementing _accum
as a default list:
defprint_sequences(char_list, n, _accum=[]):
iflen(_accum) == n:
print(_accum)
else:
for c in char_list:
print_sequences(char_list, n, _accum+[c])
print_sequences([1, 2, 3, 4], 4)
Post a Comment for "Print N-length Combinations From Char List Using Recursion"