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

جواب «A Budget of Letters» چالش 5 از جلسه‌ی 39

سؤال

پنجره‌ی زمینه را با تعداد حرف اندازه بگیر. total_chars(history) جمع طول content همه‌ی پیام‌ها را برگرداند. fit_budget(history, budget) یک کپی از لیست بسازد (list(history)) و تا وقتی جمع حرف‌ها بیشتر از budget است و لیست خالی نیست، قدیمی‌ترین پیام را بردارد (pop(0)). خروجی test:
200 5 118
70 3 59
20 1 17
5 0 0
5

راهنما

while total_chars(kept) > budget and len(kept) > 0: و داخلش kept.pop(0).

یک جواب درست

def total_chars(history):
    total = 0
    for m in history:
        total += len(m["content"])
    return total

def fit_budget(history, budget):
    kept = list(history)
    while total_chars(kept) > budget and len(kept) > 0:
        kept.pop(0)
    return kept


# ---- test (do not change) ----
msgs = [
    {"role": "user", "content": "I have a pet turtle called Sheldon."},
    {"role": "assistant", "content": "Sheldon is a great name!"},
    {"role": "user", "content": "He likes lettuce."},
    {"role": "assistant", "content": "Yum, turtles love greens."},
    {"role": "user", "content": "What is his name?"},
]
for budget in [200, 70, 20, 5]:
    kept = fit_budget(msgs, budget)
    print(budget, len(kept), total_chars(kept))
print(len(msgs))

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