+ 1
I have a weird problem with Python I don't fully understand.
I was trying to run this code but itBugs out with those numbers. Why? Why Python for ex. won't delete 32 from the list if (32%2 == 0) is True? In this exercise the answer should be 0 because you can't build the biggest rectangle from one number. Here's the code: https://code.sololearn.com/cxUmvYB9EoR3/?ref=app
4 ответов
+ 3
The problem isn't necessarily because of your condition, but rather how you're setting up the loop that goes through the list.
Going through the execution, the first iteration of the for loop gives the variable number the value of the first element within the list numbers. Because 4 % 2 = 0, that element is removed, resulting in all the elements shifting over one space to the left. In the second iteration, number is given the value of the second element within the list, and because 4 had already been removed, the first element had become 34 with the second now being 16. The problem lies in the fact that because you're removing elements while looping through each element, you're skipping over some values which is why you're left with the weird results.
To avoid this, what you could do is instead replace your for loop with a while loop, similar to the following:
x = 0
while x < numbers.length:
# Do some stuff
This lets you reset the loop by just setting the value of x to 0 if the conditional is true
+ 2
You got wrong result because you modified the list while looping through the same list.
I say that you'd only need to change 1 thing.
On line 4, you would need to change:
for number in numbers:
to
for number in numbers.copy():
Then the loop is iterating through a different list, than the one which is being modified.
+ 1
Okay it was easier to just create a new list called numbers2 = [] and append right numbers to it. But thanks to you I understand how to avoid that index paradox.
Fixed:
https://code.sololearn.com/cY2L5Ehiq30Q/?ref=app
If theres something to add please tell me.
+ 1
Wow noice trick SlickBack I did:
numbers2 = [i for i in numbers2 if i % p != 0]
And IT works. Thanks!