简体   繁体   中英

Python list unroll in a recursive function

The following is my python recursive function code:

char_list=[]
def xyz(sample_string):
    global char_list
    if sample_string!="":
        char_list.append(sample_string[0])
        xyz(sample_string[1:])
    # once sample_string == "", the function will start unrolling
    # While unrolling, I wanted to do certain operations on the char_list elements and other operations which includes recursive calls to function xyz()

for eg, if the initial value of sample_string is ABC , What I want is for each iteration char_list will be adding,

iter 1 - char_list = ['A']

iter 2 - char_list = ['A','B']

iter 3 - char_list = ['A','B','C']

Then sample_string will become empty and the function will start unrolling:

Now I want to get the list in each iteration in the following order, ie,

char_list = ['A','B','C']

char_list = ['A','B']

char_list = ['A']

so that I can do my further operations on the list. I can't use return keyword since there are other operations following in the same function including recursive calls to xyz() .

The code I wrote is not serving that purpose. For each unroll , it is returning the full list ( ['A','B','C'] ), not in that decrement fashion. I tried the same with a local list variable, still not working. Any idea on how to do this ?

def xyz(sample_string):
    l = list(sample_string)
    if l :
        for i in reversed(range(1, len(l)+1)):
            print(l[0:i])

change the print to yield , and the function become a generator

what you need is list of number [1,2,3,4....] , than you can use list_[0:i] to get slice of the list_ , once you get the list of number, you can reverse it or do something else. out:

['A', 'B', 'C']
['A', 'B']
['A']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM