问题
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