sbhayana26 sbhayana26 - 2 months ago 9
Python Question

Using the "i-=smallest" statement in the code below, I intend to alter my original array arr, but that isn't happening. What do I do?

Here's the code:

n = int(input())
arr = input().split()
arr = [int(x) for x in arr]
smallest = 1001
while(True):
if smallest==0:
break
arr.sort()
count = 0
smallest = arr[0]
for i in arr:
if i==0:
arr.remove(i)
i-=smallest #This statement.
count+=1
print(count)


For input:
(n=)6 and
(arr=)5 4 4 2 2 8
The output I'm getting is:
6
6
6...
However, according to me, if my logic works (and the aforementioned statement actually edits my original array elements), the output should turn out to be
6
4
2
1
instead.

I might have got whole of the thing wrong. I'm an amateur. Any sort of help is appreciated.

Answer

Let's look at the inside loop

for i in arr:
    if i==0:
        arr.remove(i)
    i-=smallest
    count+=1

It assigns the first value in arr to i. Since no value of the array is zero, it doesn't remove anything from the list.

It then reassigns the value of i by subtracting the smallest value. For the first time through the loop it assigns the value of zero to i. Then it increments count. The list arr is unchanged. The line i=-smallest has no effect since i is reassigned to the next value of the list.

So, with the values 5 4 4 2 8 8 (none of which are zero) that loop is equivalent to

for i in arr:
    count+=1

Which is why it always prints 6. I'm not sure why you think it should print 6 4 2 1. I suspect you think the list is being changed, but that the line if i==0 is always false.

Changing the object being iterated over in a for loop is guaranteed to confuse you. There is almost certainly a better way to achieve what you want. See for example Remove items from a list while iterating in Python

Comments