Issue
My calculation takes forever when the duration is supposed to be short (0.2 second). when I interrupt the cell, it allows to finish the process at 100%.
Context :
I want to verify that a value is in a dictionary, for that I iterate on the dictionary :
i = 0
j = 0
while i < 9 :
try :
if dictionary[i] == "my_value" :
j = i
break
except :
i +=1
Where j
is here to store the location of the key in the dictionary.
What happens is that it should take 0.2 seconds to process. However, it runs infinitely. If I interrupt the cell, two scenarios happen :
- The interruption goes as expected
- The interruption actually completes the operation and displays the result
Example : I print i
at each step and I get :
Running forever, frozen on a random number
>>>0
>>>1
>>>2
>>>3
>>>4
>>>5
>>>6
>>>7
Then, when I interrupt the cell, I get :
>>>0
>>>1
>>>2
>>>3
>>>4
>>>5
>>>6
>>>7
>>>8
>>>9
>>>j = 2
aka the run of the cell is successful, I get the output that I expected. In conclusion, interrupting the cell allows the operation to be successful.
I do not understand what happens exactly, maybe the interruption exists a try()
that was stuck.
The problem is that it is obviously not consistent at all to manually interrupt the cells (sometimes it really interrupts the cell without finishing the computation).
What causes the infinite run? How to fix the code? Thank you in advance.
Solution
The while
loop is always checking the if
condition, but because i=0
is not going to change, the condition is always false and you are stuck in the loop forever
Try to add i += 1
in the try
block so that it will not stuck at i=0
, like this:
dictionary = {1:'', 2:'', 3:'', 4:'', 99:'', 6:'my_value', 7:'', 8:'', 9:'', }
i = 0
j = 0
while i < 9 :
try :
if dictionary[i] == "my_value" :
print(i, dictionary[i])
break
else:
print(i)
i +=1
except :
print('exception at', i)
i +=1
Output
exception at 0
1
2
3
4
exception at 5
6 my_value
Answered By - perpetualstudent
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.