Grokking Data Structures & Algorithms for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
Steve Ochoa
Python cannot reassign range loop variable values

Steve Ochoa

Oct 27, 2024

In the Python solution, you perform an "i=j" java/c/c++ style reassignment when the success condition is met. However, this does not work in a Python range loop. The loop counter will always be set to the next value in the range sequence at the start of every loop iteration, regardless of any reassignment of the loop counter value within the loop. Granted, your solution still works, but this may be a big "gotcha" during an interview.

Example:

j = 999 for i in range(10): print(f'top={i}') i = j print(f'after={i}')

Will output:

top=0 after=999 top=1 after=999 top=2 after=999 top=3 ...

1

0

Comments
Comments
Steve Ochoa
Steve Ochoaa year ago

Specifically this applies to step 3 of the step-by-step algorithm in the Python implementation:

  • If isEnd is true for the current node:
    • Add (j - i + 1) to matchedLength to account for the length of the matched word.
    • Set i to j to skip over the...
J
james.j.ramsaran a year ago

Great catch. I was observing the behavior of the solution code step-by-step in a debugger and noticed this occurring. It's clearly a bug.

On this page