def move_zeros(array):
for element in array:
if element == 0 and type(element) is not bool:
array.append(array.pop(array.index(element)))
return array
print(move_zeros([False,1,0,1,2,0,1,3,"a"]))
My result is [1, 1, 2, 1, 3, 'a', False, 0, 0]
I don't want False to move, my program sees False as 0.
This is coming about because you're operating on the list while looping over it, as well as the issue that you've correctly identified, that False == 0 and 0 == 0 both are True in Python. One way to deal with this is the following, using is instead of == to check equality to 0:
def move_zeros(a):
return [x for x in a if x is not 0] + [x for x in a if x is 0]
print(move_zeros([False,1,0,1,2,0,1,3,"a"]))
Output:
[False, 1, 1, 2, 1, 3, 'a', 0, 0]
Note that the use of is to compare integers is not safe in general because integers outside of the range (-5, 256) have different ids from each other (see this question). In our case however, we are just using 0, so the solution above is safe.
Simple solution and showing that your check is actually ok:
>>> sorted(array, key=lambda x: x == 0 and type(x) is not bool)
[False, 1, 1, 2, 1, 3, 'a', 0, 0]
Or compare with the False singleton:
>>> sorted(array, key=lambda x: x == 0 and x is not False)
[False, 1, 1, 2, 1, 3, 'a', 0, 0]
Or if you're feeling playful, chained comparisons:
>>> sorted(array, key=lambda x: 0 == x is not False)
[False, 1, 1, 2, 1, 3, 'a', 0, 0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With