Just a quick help please | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Just a quick help please

I found this code in the challenge and the output has to be 18. Can anybody help me figure it out, how the output is 18 ? https://code.sololearn.com/c1P3nkO9D7wE/?ref=app

30th Sep 2021, 1:05 PM
Sacar
Sacar - avatar
7 Answers
+ 4
If you add these lines inside the loop, you will get a better idea what's happening. print(arr) print(n) So then you can see that it adds 3 again and again. Because you changed the array while you goes through them. Arr: 0, 1, 2, 10, 10... 3, 4, 5 The pointer goes from left to right through the array but you insirt everytime 10 so it reached again again 3. I hope it was understandable.
30th Sep 2021, 1:25 PM
Stefanoo
Stefanoo - avatar
+ 2
So the index of 3 is incremented by 1 after each Iteration, therefore returning the same value for n i.e 3 ? Output = 0+1+2+3+3+3+3+3 = 18 Thank you, everyone !
30th Sep 2021, 3:11 PM
Sacar
Sacar - avatar
+ 2
Ipang Do you really think same would happen if we remove a member ? sum = 0 arr = [0,1,2,3,4,5] for n in arr: sum += n if n == 3: del arr[n] if sum > 15: break print(sum) This code gives output : 0+1+2+3+5
30th Sep 2021, 3:40 PM
Sacar
Sacar - avatar
+ 2
Sacar, Not with the exact same scenario, but in summary, modification to an iterable during iteration through it, brings funny unexpected result.
30th Sep 2021, 3:43 PM
Ipang
+ 1
Add this line as the first line inside the for...in loop to better understand what's going on before the check of <sum> > 15 print( f'n = ({n}) sum = ({sum}) arr ={arr}' )
30th Sep 2021, 1:32 PM
Ipang
+ 1
As Stefanno has already mentioned, what happens is, when loop reaches n==3 it gets stuck on that element until it is bigger than 15 You cold see for yourself what exactly happens if you run that code: https://code.sololearn.com/c2os8forQF8g/?ref=app
30th Sep 2021, 1:36 PM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
+ 1
It happened because the iterable size changes during the for...in loop due to call for insert() method. It's kinda odd but quite the same funny symptom also happens when a member is removed from the iterable during iteration :D
30th Sep 2021, 3:16 PM
Ipang