Why Am I Getting An Infinite For Loop?
For this python problem I am taking in one argument an int, this is the max length of a list I am going to be appending to. Starting with an int value of 1, I want to iterate throu
Solution 1:
You are adding to the list as you loop over it. A list iterator simply increments a position counter and returns the value at that index until the index doesn't exist. It doesn't keep track of the length of the list up-front. In your case, by adding more elements to the end, the iterator never reaches an index that doesn't exist.
You have several options:
Create a copy of the list first to iterate over; that copy won't grow:
defdbl_linear(n): lst_u = [1] whilelen(lst_u)<=n: for i in lst_u[:]: # [:] returns a shallow copy lst_u.append(2*i+1) lst_u.append(3*i+1) returnsorted(lst_u)
Append to a separate, new list and extend the original after the loop:
defdbl_linear(n): lst_u = [1] whilelen(lst_u)<=n: new_values = [] for i in lst_u: new_values.append(2*i+1) new_values.append(3*i+1) lst_u.extend(new_values) returnsorted(lst_u)
Use a
range()
to produce indices; this is based on taking the length once:defdbl_linear(n): lst_u = [1] whilelen(lst_u)<=n: for idx inrange(len(lst_u)): i = lst_u[idx] lst_u.append(2*i+1) lst_u.append(3*i+1) returnsorted(lst_u)
Post a Comment for "Why Am I Getting An Infinite For Loop?"