Print n-length combinations from char list using recursion

折月煮酒 提交于 2019-12-24 00:49:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!