具有优先级的费用跟踪器 python

Expense tracker with priorities python

帮助,我刚开始编程,但我的一部分代码卡住了。我需要创建一个程序来跟踪你的开支,所以你输入你的预算,你想存多少钱,然后你想把它花在什么地方。所以首先我需要想出一种方法来在这些需求中创建一个优先级,然后开始将它减去剩余的金额但是当你没有足够的钱买某样东西时它必须停止并警告你你不能花钱在那上面。有什么建议吗?

这是我的想法,但它是错误的,因为它只检查字典中的第一个值而跳过其余的值。求助!!

def gexpenses(spared,wants):
y = 0
while (y <= spared):
    for value in wants.values():
        y = spared - value
        return y
want = {"Party": 10, "Trip": 10, "Clothes":10}
spare = 25
print(expenses(25,want))

您可以考虑在 Python 中使用优先级队列(查找 heapq 库)。优先级队列基本上是一种数据结构,它将始终生成具有最小(或最大)优先级的项目。

您必须为每个需求分配一个优先级编号以及相关费用。然后您可以从优先队列中删除该项目并扣除与该项目相关的成本。如果包括该项目的成本超出了您的预算,请将该项目重新添加到优先队列中。优先队列会自动将该项目洗回“队列”的顶部。

编辑 1:根据评论添加示例代码

编辑 2:在 while 循环中添加了 and heap 以检查堆为空但仍有剩余预算的情况

# Import Priority Queue library
from heapq import heappush, heappop

# Initialise remaining budget, wants, priority queue (heap)
# For the list of wants, initialise with (priority, item, cost)
# Initialise a list of affordables, assuming you'll want to see what you can afford
remaining_budget = 20
wants = [(2, "Party", 10), (1, "Clothes", 10), (3, "Trip", 10)]
heap = []
affordables = []

# The priority queue implemented in Python is a minimum heap,
# meaning that the smallest number will be "pushed" out of the priority queue first
for i in wants:
    heappush(heap, i)

def get_expenses(remaining_budget, heap, affordables):
    have_budget = 1
    
    while have_budget and heap:
        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)

基于以上,示例输出如下:

Items you can buy:  ['Clothes', 'Party']
Remaining Budget:  0

由于衣服和派对的优先级(优先级值较低)比旅行“高”,所以首先购买衣服和派对。

示例代码可能不是 streamlined/optimized,但您可以阅读更多有关如何实现优先级队列的信息,并根据程序的要求调整代码。