简体   繁体   中英

List append resets list in recursive function

I am running the following code to attempt a simulation of Hanoi recursively but on running the code the list [[1,3]] is returned every time as hlist is reset in the loop. How can I rectify this?

def playHanoi(p1,p2,p3,n):
    hlist=[]
    if n==1:
        hlist.append([p1,p3])
    else:
        playHanoi(p1,p3,p2,n-1)
        hlist.append([p1,p3])
        playHanoi(p2,p1,p3,n-1)
    return(hlist)

using global is one way to do that:

hlist = []

def playHanoi(p1,p2,p3,n):
    global hlist
    if n==1:
        hlist.append([p1,p3])
    else:
        playHanoi(p1,p3,p2,n-1)
        hlist.append([p1,p3])
        playHanoi(p2,p1,p3,n-1)
    return(hlist)

a second (and probably cleaner) way is to use hlist as function argument:

def playHanoi(p1,p2,p3,n, hlist=None):

    if hlist is None:
        hlist = []

    if n==1:
        hlist.append([p1,p3])
    else:
        playHanoi(p1,p3,p2,n-1, hlist)
        hlist.append([p1,p3])
        playHanoi(p2,p1,p3,n-1, hlist)
    return(hlist)

hlist is only defined in the function. If you define hlist=[] first, every use of hlist.append([tobeappended]) is appended to the (global) list.

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