Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Sort Except Zero by frichard44
from collections.abc import Iterable
def except_zero(items: list[int]) -> Iterable[int]:
not_zero = []
zero_idx = []
# First pass, get index of zeros and list of anything else than zero
for i in range(len(items)):
if items[i] == 0:
zero_idx.append(i)
else:
not_zero.append(items[i])
# second pass, prepare result
result = []
not_zero = sorted(not_zero)
for i in range(len(items)):
if i in zero_idx:
result.append(0)
else:
result.append(not_zero.pop(0))
return result
print("Example:")
print(list(except_zero([5, 3, 0, 0, 4, 1, 4, 0, 7])))
# These "asserts" are used for self-checking
assert list(except_zero([5, 3, 0, 0, 4, 1, 4, 0, 7])) == [1, 3, 0, 0, 4, 4, 5, 0, 7]
assert list(except_zero([0, 2, 3, 1, 0, 4, 5])) == [0, 1, 2, 3, 0, 4, 5]
assert list(except_zero([0, 0, 0, 1, 0])) == [0, 0, 0, 1, 0]
assert list(except_zero([4, 5, 3, 1, 1])) == [1, 1, 3, 4, 5]
assert list(except_zero([0, 0])) == [0, 0]
print("The mission is done! Click 'Check Solution' to earn rewards!")
Feb. 13, 2025