Back to course home
0% completed
Vote For New Content
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 Ochoaa year ago
Specifically this applies to step 3 of the step-by-step algorithm in the Python implementation:
- If
isEndistruefor the current node:- Add
(j - i + 1)tomatchedLengthto account for the length of the matched word. - Set
itojto skip over the...
- Add
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