python - 具有优先级的费用跟踪器
问题描述
我需要帮助,我的程序应该询问您的每月预算,您想节省多少钱,然后告诉您可以从需求列表中花多少钱,但它只适用于某些数字,如果我输入100 它工作正常,但如果我把 200 它给了我这个错误:
Traceback (most recent call last):
File "<string>", line 52, in <module>
File "<string>", line 41, in get_expenses
IndexError: index out of range
>
关于如何解决这个问题的任何想法?
from heapq import heappush, heappop
bud = int(input("What is your monthly budget?"))
sav = int(input("Hom much money do you want to save?"))
#sets dictionary with name and price of needs
need = {"Food": 10, "Rent": 40, "School": 20, "Extras": 10}
#Set the wants (Priority, name, price)
wants = [(2, "Party", 5), (1, "Clothes", 5), (3, "Trip", 10)]
heap = []
affordables = []
#in this list we will store the wants we can afford
def need_spent():
n = 0
for value in need.values():
n = n + value
return n
#this function gives a total of how much you spend on needs (with no priorities because they are all needed)
x = need_spent()
def money(budget,savings,needs):
for_needs = budget - savings
#gives us the amount of money available to spend
spare = for_needs - x
return spare
#the amount of money left for wants
remaining_budget = money(bud,sav,x)
for i in wants:
heappush(heap, i)
def get_expenses(remaining_budget, heap, affordables):
have_budget = 1
while have_budget:
item = heappop(heap)
# Check if this item causes us to exceed the budget
if remaining_budget - item[2] < 0:
# If it does, put it back in the heap
heappush(heap, item)
have_budget = 0
else:
remaining_budget -= item[2]
affordables.append(item)
return remaining_budget, affordables
remaining_budget, affordables = get_expenses(remaining_budget, heap, affordables)
print("Items you can buy: ", [i[1] for i in affordables])
print("Remaining Budget: ", remaining_budget)
解决方案
推荐阅读
- firebase - Flutter 中的 FirebaseVisionImage 是什么?
- vue.js - 为什么我的对象和数组道具在子组件中变成了字符串?
- sql-server - 带条件插入的存储过程
- django - Django如何过滤嵌套关系
- java - 变量绑定到对象而没有自定义构造函数?
- python - 为什么第二个示例无法正常工作
- reactjs - 为什么 "axios.post("/api/payment_intents", 方法不能定位我的付款意图?
- function - 使用 fortran 内在函数时具有额外灵活性的原因
- json - 如何在没有完整路径的情况下向 JSON 数组添加值?
- python - 如何在Windows中获取所有者的用户ID?