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

جواب «Step 3: Tick, Clear, Count» چالش 3 از جلسه‌ی 9

سؤال

قدم ۳ از ۴: toggle(i) تیک کار شماره‌ی i را برعکس کند. clear_done() کارهای تیک‌دار را از داده پاک کند. متن count (زیر لیست) همیشه مثل 1 of 2 done بگوید چند کار انجام شده. ضربه و دکمه‌ی Clear done از قبل وصل شده‌اند.

راهنما

کدهای جلسه‌ی ۷: not در toggle، global todos و لیست left در clear_done، و شمردن در show_list. بعد از هر تغییر show_list().

یک جواب درست

import app

todos = [
    {"text": "Brush my teeth", "done": True},
    {"text": "Pack my school bag", "done": False},
]

def show_list():
    items.clear()
    done = 0
    for t in todos:
        items.add(t["text"], done=t["done"])
        if t["done"]:
            done = done + 1
    count.value = f"{done} of {len(todos)} done"

def add():
    text = box.value.strip()
    if text == "":
        app.toast("Write a task first")
        return
    for t in todos:
        if t["text"] == text:
            app.toast("Already in the list")
            return
    todos.append({"text": text, "done": False})
    box.value = ""
    show_list()

def toggle(i):
    todos[i]["done"] = not todos[i]["done"]
    show_list()

def clear_done():
    global todos
    left = []
    for t in todos:
        if not t["done"]:
            left.append(t)
    todos = left
    show_list()

app.title("My Day")
box = app.input("New task")
app.button("Add", add)
items = app.list()
items.on_tap(toggle)
count = app.text("")
app.button("Clear done", clear_done)
show_list()
app.run()

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