BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Debug and fix7 of 16 in topic

862. Fix the agent memory shared between conversations

EasyDebug and fix

Why it matters Shared mutable defaults leak one user's messages into another user's agent context. It is a real production bug and a classic Python interview question.

The starter code below runs, but it has a realistic bug. Read the spec, find the bug and fix it. Keep the function name and signature.

add_turn(role, text, history=None) should append {"role": role, "content": text} to the given history list and return that list. When history is not given, it must start a new empty list for that call only, so separate conversations never share messages.

Inputs: role and text are strings. history is a list of message dicts or None.

Return the list of message dicts.

Functiondef add_turn(role, text, history=[])

Example 1

Input: add_turn('user', 'hi')

Output: [{'role': 'user', 'content': 'hi'}]

Constraints

  • Python 3 standard library. Code runs in your browser.
  • Your code must pass all 5 tests to be accepted.
Hint 1

Call the function twice with no history. What does the second call return?

Hint 2

Default values are created once.

Hint 3

Use None as the default and build a new list inside.

Common mistakes
  • Copying the default list but still mutating it.
  • Returning a new list when history is given, so the caller's list is not updated.
  • Using a module-level global history.
Understand the idea

Python evaluates default arguments once, when the function is defined. history=[] creates one list that every call without history appends to. The fix is to default to None and create the list inside the function. The second test only passes when each call starts fresh.

Shapes and data flow
Lists of dicts.
Topics
Debug and fix
Similar questions
  • Fix the softmax that returns nanEasy
  • Fix the LayerNorm that normalises the wrong axisEasy
  • Fix the cross-entropy that returns infEasy
  • Fix the F1 score that crashes on empty predictionsEasy
All Debug and fix problems
Report
862 / 903
Python 3solution.pyPython idle
1
2
3
4
def add_turn(role, text, history=[]):
history.append({"role": role, "content": text})
return history
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 5 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS