I'm taking this Python course online and am trying to figure out why this loop is infinite when the x value is 3
def mystery(x):
a = [0, 4, 0, 3, 2]
while x > 0:
x = a[x]
return "Done"
mystery(3) runs infinitely.
Is it because it keeps trying to set x to 3 when the list value is already 3?
Remember array indices start from 0, so if
a = [0, 4, 0, 3, 2]
then a[3] == 3
so this line
x = a[x]
never sets x
to anything other than 3!
"Is it because it keeps trying to set x to 3 when the list value is already 3?"
Yes. a[3]
points to 3
in that list. So x
is just being assigned to 3
repeatedly.
是的,x始终为3。最初x是3,索引3是list的值,即a [x]也是3.因此无限循环。
Remember that list indices start at zero, so a[3]=3. Then, try unrolling the loop manually:
x = 3
is x=3 > 0, YES
x = a[x] = a[3] = 3
is x=3 > 0, YES
x = a[x] = a[3] = 3
is x=3 > 0, YES
and so on.
def mystery(x): # Here x = 3
a = [0, 4, 0, 3, 2]
while x > 0: # Since x = 3 the program enters the loop
x = a[x] # a[3] = 3 and hence x is assigned 3. Again x = 3 and therefore
# the program will get into an infinite loop in the while
# statement.
return "Done"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.