Python递归深度超限报错原因及修复方案咨询
旅行预算管理Python代码递归超限错误分析与修复
报错原因
你遇到的maximum recursion depth exceeded错误,根源在calculate_total_cost函数,而非你推测的display_budget_summary:
- 函数内部直接调用了自身
calculate_total_cost(hotels, flights),且没有任何终止条件,导致函数无限递归调用,直到触及Python的递归深度上限 - 总费用计算逻辑存在bug:
sum({h_cost, f_cost})使用了集合,集合会自动去重,若酒店总费用和机票总费用相等,会被只统计一次,完全不符合预算统计需求
具体修复方案
- 移除无限递归调用:在
calculate_total_cost中直接返回计算好的总费用,不要调用自身 - 修正总费用计算:将
sum({h_cost, f_cost})改为h_cost + f_cost,直接相加两类费用的总和 - 清理冗余代码:删除函数内无用的
global声明(函数已通过参数接收hotels和flights,无需全局变量),以及add_destination中未使用的cost变量 - 完善函数返回值:让
calculate_total_cost明确返回总费用,确保display_budget_summary能拿到正确结果
修正后的完整代码
cities = ["Boston", "Las Vegas", "Porto Alegre", "Cape Town", "Berlin", "Okinawa", "Sydney"] hotels = [255, 450, 150, 250, 650, 675, 850] flights = [950, 3000, 4500, 2750, 2500, 3500, 10500] def add_destination(city, hotel, flight): global cities, flights, hotels print("""Add your desired destination. Please include your hotel and flight cost, as well as the name of your desired location and hotel.""") new_place_city = input("Please type your new city: ") new_place_hotel = int(input("Please type your new hotel's price per night: ")) new_place_flight = int(input("Please type the cost of your flight:")) cities.append(new_place_city) hotels.append(new_place_hotel) flights.append(new_place_flight) def calculate_total_cost(hotels, flights): f_cost = sum(flights) h_cost = sum(hotels) t_cost = h_cost + f_cost return t_cost def display_budget_summary(cities, hotels, flights): for i in range(len(cities)): print(f"{cities[i]}, ${hotels[i]} ${flights[i]}.") result = calculate_total_cost(hotels, flights) print(f"Your current budget/money spent is ${result}.") while True: print(f"""Currently, the cities you plan to visit during your vacation are {cities}." Please choose an option to make any edits to your vacation.""") print("1. Add a destination") print("2. View budget summary") print("3. Exit program") option = int(input("Please choose an answer: ")) if option == 1: add_destination(cities, hotels, flights) elif option == 2: display_budget_summary(cities, hotels, flights) elif option == 3: break else: print("Please choose a valid option.")
内容的提问来源于stack exchange,提问作者Declan Kennedy
相关产品推荐
相关产品推荐

