简体   繁体   中英

What is the difference between these two python methods?

I am a python newbie.

I have one python method which returns the list recursively (previous is the dictionary of string and s is just a string that is included in the previous dictionary)

def path(previous, s):
    "Return a list of states that lead to state s, according to the previous dict."
     return [] if (s is None) else path(previous, previous[s]) + [s]

and this one which I believe should return the same result

def path(previous, s):
    "Return a list of states that lead to state s, according to the previous dict."
    if s is None:
        return []
    else:
        path(previous, previous[s]) + [s]

I was expecting that functionality wise those two methods are exactly identical, it's just that the first one is more consice. However, when I run the second methods,

I am receiving following error:

"TypeError: unsupported operand type(s) for +: 'NoneType' and 'list'"

What am I doing wrong here?

You're missing a return statement in the else branch of the second method:

def path(previous, s):
    "Return a list of states that lead to state s, according to the previous dict."
    if s is None:
        return []
    else:
        return path(previous, previous[s]) + [s]

The first approach uses a ternary operator whose returned value (one of two) is returned by the return statement, therefore, the second needs a return statement in both branches.

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