Python recursive function example question.

Asked 2 years ago, Updated 2 years ago, 76 views

building = ["Gyeongbokgung", 1395, ["Sungnyemun", 1396, ["Changdeokgung", 1405]] This building string is

 Gyeongbokgung Palace
 1395
    Sungnyemun
    1396
        Changdeokgung Palace
        1405

I'm going to put it this way. By default, the given function is

def printItems(aList):
    for item in aList:
        if isinstance(item, list):
            printItems(item)
        else:
            print(item)

And if you add a factor tab that deals with '\t' to call the recursive function, you want to print it out with a space once and then make it as empty as the tab.

python recursion tab

2022-09-21 10:53

1 Answers

building ="Gyeongbokgung", 1395, ["Sungnyemun", 1396, ["Changdeokgung", 1405]

def printItems(lst, tabs=''):
    for item in lst:
        if isinstance(item, list):
            printItems(item, tabs+'\t')
        else:
            print('%s%s'%(tabs, item))


printItems(building)
 Gyeongbokgung Palace
1395
    Sungnyemun
    1396
        Changdeokgung Palace
        1405


2022-09-21 10:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.