首页 > 解决方案 > 具有优先级的费用跟踪器

问题描述

我需要帮助,我的程序应该询问您的每月预算,您想节省多少钱,然后告诉您可以从需求列表中花多少钱,但它只适用于某些数字,如果我输入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)

标签: python

解决方案


推荐阅读