Recursive Example 1

Known list: 
L = [[3,5,8], 10, [[13, 14 are], 15], 18 is]
. 1) to write a function print_list (lst) print out all the numbers in the list
print_list (L)
2) write a function sum_list (lst) returns a list of all the numbers and
print_list (sum_list (L))
Note:
type (X) can return a variable of type L = [[3,5,8], 10 , [ [13, 14 are], 15], 18 is ]

DEF print_list (L): for X in L: IF ! type (X) = list: # determines a list of the corresponding element value or, if the value is direct printing Print (X, = End ' ' ) the else : # otherwise calls print_list () recursively within the list of elements corresponding to print print_list (x) print_list(L) Results of the: 3 5 8 10 13 14 15 18
def sum_list(lst):
    val = 0
    for x in lst:
        if type(x) != list:
            val += x
        else:
            val+=sum_list(x)
    return val

print(sum_list(L))
Results of the:
86

 

  

 

Guess you like

Origin www.cnblogs.com/vincent-sh/p/12543948.html