Skip to content

fix: MultiStack.get_stack bound check was a never-true chained comparison - #274

Open
sulthonzh wants to merge 1 commit into
careercup:masterfrom
sulthonzh:fix/multistack-get-stack-validation
Open

sulthonzh wants to merge 1 commit into
careercup:masterfrom
sulthonzh:fix/multistack-get-stack-validation

Conversation

@sulthonzh

Copy link
Copy Markdown

Bug

MultiStack.get_stack in chapter_08/p06_towers_of_hanoi.py validates stack indices with:

if 0 > stack_num >= self.num_stacks:
    raise IndexError("stack_num invalid")

0 > stack_num >= self.num_stacks is a chained comparison meaning (stack_num < 0) and (stack_num >= self.num_stacks) — logically impossible, so the intended IndexError can never fire. Consequences (both reproduced before the fix):

  • get_stack(-1) silently returns the last stack (Python negative indexing), and push(-1, v) corrupts it — e.g. push(-1, 99) writes 99 to stack 2
  • out-of-range positive indices only fail by accident via the underlying list indexing, not the intended validation

Fix

if not 0 <= stack_num < self.num_stacks:

Also extends the driver self-test to assert that invalid indices (-1, -3, 3, 10) raise IndexError.

Verification (TDD)

  • RED: new assertions fail on current main (AssertionError: get_stack(-1) should raise IndexError)
  • GREEN: with the one-line fix, the self-test passes; the solver still produces the canonical 7-move solution for 3 plates; get_stack(-1) and get_stack(3) now raise IndexError as intended
  • Repo-wide sweep: this is the only instance of the never-true chained-comparison pattern in the codebase

…ison

The guard 'if 0 > stack_num >= self.num_stacks' is logically impossible
(a number cannot be negative and >= num_stacks at the same time), so
get_stack never raised the intended IndexError. Negative stack indices
silently wrapped around (get_stack(-1) returned the last stack;
push(-1, v) corrupted it) and out-of-range positives only failed via
accidental list indexing.

Fix the condition to 'if not 0 <= stack_num < self.num_stacks' and
extend the driver self-test to assert invalid indices raise IndexError.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant