开发者

Tail recursive function fails to return a value (Python 3)

I've created a tail recursive function to solve an optimization problem:

def optimize(current_price = 0.1, last_profit = 0.0):
    current_profit = profit(current_price)
    if (last_profit > current_profit) and (current_profit > 0.0):
        return {'best_price': current_price - 0.1, 'best_profit': last_profit}
        # print({'best_price': current_price - 0.1, 'best_profit': last_profit})
    else:
        optimize(current_price + 0.1, current_profit)

def best_price():
    optimized = optimize() # optimize() should return a dict, 
                           # allowing optimized['best_price'] 
                           # and optimized['best_profit'] to be called
    pr开发者_开发百科int("Pricing the tickets at ${0} will produce the greatest profit, ${1}.".format(optimized['best_price'], optimized['best_profit']))

The function operates correctly with the exception that it fails to return anything. I do not mean to say that the first if statement is never called (in fact, when I uncomment the print line, it will print the correct result), but that the return statement fails to return a dictionary.

This results in a TypeError when I attempt to call optimized['best_price'], as 'NoneType' object is not subscriptable.

I've been working on this error for a while now, and can't seem to either make it work myself or find anything regarding it online. At this point, it's just a matter of me wanting to know the solution. Any ideas? Thanks!


Even a tail-recursive function needs a return in Python:

def optimize(current_price = 0.1, last_profit = 0.0):
    current_profit = profit(current_price)
    if (last_profit > current_profit) and (current_profit > 0.0):
        return {'best_price': current_price - 0.1, 'best_profit': last_profit}
    else: # Add return below here
        return optimize(current_price + 0.1, current_profit)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜