【问题标题】:maximum recursion depth error?最大递归深度误差?
【发布时间】:2016-07-28 16:43:32
【问题描述】:

所以我真的很陌生(3 天)而且我在代码学院,我已经为其中一项活动编写了这段代码,但是当我运行它时它显示最大递归深度错误,我正在运行它在代码学院的 python 控制台中,同时在我自己的 ipython 控制台上。页面上的提示没有帮助,有人可以解释如何解决这个问题吗? 谢谢

def hotel_cost(nights):
    return (nights * 140)

def plane_ride_cost(city):
    if plane_ride_cost("Charlotte"):
        return (183)
    if plane_ride_cost("Tampa"):
        return (220)
    if plane_ride_cost("Pittsburgh"):
        return (222)
    if plane_ride_cost("Loas Angeles"):
        return (475)

def rental_car_cost(days):
    cost = days * 40
    if days >= 7:
        cost -= 50
    elif days >= 3:
        cost -= 20
    return cost    

def trip_cost(city, days):
    return hotel_cost(nights) + plane_ride_cost(city) + rental_car_cost(days)

【问题讨论】:

  • edit 我知道拼写错误:')

标签: python-2.7 recursion


【解决方案1】:

也许:

def plane_ride_cost(city):
    if city == "Charlotte":
        return (183)
    if city == "Tampa":
        return (220)
    if city == "Pittsburgh":
        return (222)
    if city == "Los Angeles":
        return (475)

错误是:

plane_ride_cost(city) 在每个递归步骤中调用plane_ride_cost("Charlotte")

不是最好的,而是更好的方法:

def hotel_cost(nights):
    return nights * 140

plane_cost = {
    'Charlotte' : 183,
    'Tampa' : 220,
    'Pittsburgh' : 222,
    'Los Angeles' : 475,
}

def plane_ride_cost(city):
    if city not in plane_cost:
        raise Exception('City "%s" not registered.' % city)
    else:
        return plane_cost[city]

def rental_car_cost(days):
    cost = days * 40
    if days >= 7:
        cost -= 50
    elif days >= 3:
        cost -= 20
    return cost    

def trip_cost(city, days):
    return hotel_cost(nights) + plane_ride_cost(city) + rental_car_cost(days)

【讨论】:

  • 最好使用dict,如果city 不在字典中,请提出Exception
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-10
  • 1970-01-01
  • 1970-01-01
  • 2018-12-03
  • 2015-06-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多