بتل کد Battle Codeدارد باز می‌شود…

جواب «Spending Chart» چالش 3 از جلسه‌ی 13

سؤال

قدم ۳: نمودار خرج هر دسته. chart = app.bar([], []) به صفحه اضافه شده. آخر show() با یک دیکشنری totals جمع خرج هر دسته را حساب کن (فقط ردیف‌هایی که kind آن‌ها out است؛ دخل در نمودار نمی‌آید) و با chart.update(...) نمودار را تازه کن، به ترتیبی که دسته‌ها اول بار آمده‌اند. مثلاً دخل pocket ۵۰۰۰۰ و خرج‌های snack ۱۲۰۰۰، fun ۸۰۰۰ و snack ۵۰۰۰ ← میله‌های ۱۷۰۰۰ و ۸۰۰۰ با اسم‌های snack و fun.

راهنما

totals = {}، بعد for item in items: و if item["kind"] == "out": ← totals[item["cat"]] = totals.get(item["cat"], 0) + item["amount"]. آخر: chart.update(list(totals.values()), list(totals.keys())).

یک جواب درست

import app

items = []
GOAL = 100000

def add(kind):
    cat = category.value.strip()
    try:
        amount = int(money.value)
    except ValueError:
        app.toast("Type a real amount")
        return
    if amount <= 0:
        app.toast("Type a real amount")
        return
    if cat == "":
        app.toast("Type a category")
        return
    items.append({"kind": kind, "cat": cat, "amount": amount})
    money.value = ""
    show()

def add_income():
    add("in")

def add_spend():
    add("out")

def show():
    lines.clear()
    balance = 0
    for item in items:
        if item["kind"] == "in":
            lines.add(f"+{item['amount']} {item['cat']}")
            balance = balance + item["amount"]
        else:
            lines.add(f"-{item['amount']} {item['cat']}")
            balance = balance - item["amount"]
    balance_text.value = f"Balance: {balance:,} toman"
    if balance >= GOAL:
        goal_text.value = "Goal reached!"
    else:
        goal_text.value = f"Left to goal: {GOAL - balance:,} toman"
    totals = {}
    for item in items:
        if item["kind"] == "out":
            totals[item["cat"]] = totals.get(item["cat"], 0) + item["amount"]
    chart.update(list(totals.values()), list(totals.keys()))

app.title("Pocket Money")
category = app.input("Category")
money = app.number("Amount")
app.button("Income", add_income)
app.button("Spend", add_spend)
balance_text = app.text("Balance: 0 toman")
goal_text = app.text("Left to goal: 100,000 toman")
chart = app.bar([], [])
lines = app.list()
app.run()

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن