Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
find non-zero-index then sort solution in Clear category for Sort Except Zero by hbczmxy
"""
Sort Except Zero (Simple)
Sort the numbers in an array. But the position of zeros should not be changed.
Input: A List.
Output: An Iterable (tuple, list, iterator ...).
"""
from typing import Iterable
def except_zero(items: list) -> Iterable:
# your code here
non_zero_index = [index for index, num in enumerate(items) if num != 0]
non_zero_num = [num for num in items if num != 0]
for index, num in zip(non_zero_index, sorted(non_zero_num)):
items[index] = num
return items
if __name__ == '__main__':
print("Example:")
print(list(except_zero([5, 3, 0, 0, 4, 1, 4, 0, 7])))
# These "asserts" are used for self-checking and not for an auto-testing
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("Coding complete? Click 'Check' to earn cool rewards!")
Sept. 15, 2021