Skip to content

Instantly share code, notes, and snippets.

@temirlanKabylbekov
Created June 10, 2020 13:36
Show Gist options
  • Save temirlanKabylbekov/caea67e7cf82c8164236cbe5caf30896 to your computer and use it in GitHub Desktop.
Save temirlanKabylbekov/caea67e7cf82c8164236cbe5caf30896 to your computer and use it in GitHub Desktop.
Дан массив целых чисел. Нужно удалить из него нули. Можно использовать только О(1) дополнительной памяти
def remove_zeroes(lst: list) -> list:
"""Удаление нулей из списка с сохранением относительного порядка элементов.
Скорость работы - линейна.
Дополнительная память не используется.
>>> remove_zeroes([])
[]
>>> remove_zeroes([0])
[]
>>> remove_zeroes([0, 0])
[]
>>> remove_zeroes([0, 1])
[1]
>>> remove_zeroes([0, 1, 0])
[1]
>>> remove_zeroes([1])
[1]
>>> remove_zeroes([1, 0])
[1]
>>> remove_zeroes([1, 0, 0, 0, 2])
[1, 2]
>>> remove_zeroes([1, 0, 0, 2, 0, 0, 3])
[1, 2, 3]
"""
last_non_zero_idx: int = 0
for idx in range(len(lst)):
if lst[idx] != 0:
lst[last_non_zero_idx] = lst[idx]
last_non_zero_idx += 1
return lst[:last_non_zero_idx]
if __name__ == "__main__":
import doctest
doctest.testmod()
'''
Trying:
remove_zeroes([])
Expecting:
[]
ok
Trying:
remove_zeroes([0])
Expecting:
[]
ok
Trying:
remove_zeroes([0, 0])
Expecting:
[]
ok
Trying:
remove_zeroes([0, 1])
Expecting:
[1]
ok
Trying:
remove_zeroes([0, 1, 0])
Expecting:
[1]
ok
Trying:
remove_zeroes([1])
Expecting:
[1]
ok
Trying:
remove_zeroes([1, 0])
Expecting:
[1]
ok
Trying:
remove_zeroes([1, 0, 0, 0, 2])
Expecting:
[1, 2]
ok
Trying:
remove_zeroes([1, 0, 0, 2, 0, 0, 3, 0])
Expecting:
[1, 2, 3]
ok
9 tests in 2 items.
9 passed and 0 failed.
Test passed.
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment