Bird
Raised Fist0

Identify the bug in this code snippet for initializing a variable-sized board and multiple players:

medium📝 Analysis Q14 of Q15
LLD - Design — Tic-Tac-Toe Game
Identify the bug in this code snippet for initializing a variable-sized board and multiple players:
def setup_game(n, players):
    board = [[None]*n]*n
    for p in players:
        print(f"Player: {p}")
    return board

setup_game(3, ['A', 'B'])
AThe board rows are references to the same list, causing shared updates.
BThe players list is not printed correctly.
CThe function does not return anything.
DThe board size is fixed to 3 regardless of input.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze board initialization

    Using [[None]*n]*n creates rows that reference the same list object.
  2. Step 2: Understand impact of shared references

    Changing one cell affects all rows because they share the same inner list.
  3. Final Answer:

    The board rows are references to the same list, causing shared updates. -> Option A
  4. Quick Check:

    Shared inner lists cause bugs = The board rows are references to the same list, causing shared updates. [OK]
Quick Trick: Avoid list multiplication for nested lists [OK]
Common Mistakes:
MISTAKES
  • Ignoring shared reference problem
  • Thinking players print is incorrect
  • Assuming function returns nothing

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes