Recursive function returns None but prints correct result

寵の児 提交于 2021-01-29 12:30:41

问题


I am working on recursive function that fills a list. I encountered a problem that when I try to return the list itself I recieve None argument. However, if I print the same argument I got the correct list back. Any idea why I see such behavour?

Example:

def Price(tau, price):

price[tau] = (tau**2 - tau) + price[tau+1] - price[tau+2]

if tau == 0:
    return price

else:
    tau = tau - 1
    Price(tau, price)



print(Price(tau = 3,
            price = 6*[0]))

> None

However just prining the price, gives correct result:

def Price(tau, price):

price[tau] = (tau**2 - tau) + price[tau+1] - price[tau+2]

if tau == 0:
    print(price)

else:
    tau = tau - 1
    Price(tau, price)



Price(tau = 3,
      price = 6*[0])

> [-6, 2, 8, 6, 0, 0]

回答1:


Inside your function, you are only returning the result of Price when you go into your if statement. If you hit your else statement, you do indeed go one step deeper into the recursive loop, but you never return that result. Try this instead:

if tau == 0:
    return price

else:
    tau = tau - 1
    return Price(tau, price)

Demo



来源:https://stackoverflow.com/questions/58380558/recursive-function-returns-none-but-prints-correct-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!