Intermediate
Trim a conversation to a budget
messages is a list of (role, text) pairs, oldest first. Write trim(messages, budget) that returns the newest messages whose words add up to at most budget, in the original order.
Count words with len(text.split()). Always keep the last message, even when it alone is over the budget. Stop at the first older message that does not fit (do not skip it to include an even older one).
What Check tests
- Keeps the newest messages that fit, in order
- Everything is kept when it fits
- The last message is always kept
- It stops at the first message that does not fit
- An empty list gives an empty list
Stuck? One hint at a time
The solution unlocks after your first Check. Try first: that is where the learning happens.
main.py
Sign in to run your code.
Output
Press Run to see what your program prints.