问题
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 possible combinations in the length of n, where every character can be shown more than one time.
It's very mind-blowing for me, all this thinking recursively generally.
For example, for this problem, I think already one and a half hour, not knowing what I'm thinking about. I don't know how to start thinking recursively, what am I starting from?
I have written some nonsense:
def print_sequences(char_list, n):
if len(char_list) == 1:
print(char_list[1])
else:
sub_str = ""
for c in char_list:
print_sequences(list(sub_str + c), n)
Please help me develop some sense of recursion.
回答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:
def print_sequences(char_list, n, _accum):
if len(_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:
def print_sequences(char_list, n, _accum=[]):
if len(_accum) == n:
print(_accum)
else:
for c in char_list:
print_sequences(char_list, n, _accum+[c])
print_sequences([1, 2, 3, 4], 4)
来源:https://stackoverflow.com/questions/53561500/print-n-length-combinations-from-char-list-using-recursion