Skip to content

Instantly share code, notes, and snippets.

@temirlanKabylbekov
Created June 10, 2020 12:59
Show Gist options
  • Save temirlanKabylbekov/26fa29b79f1add037ee1c2c18441a212 to your computer and use it in GitHub Desktop.
Save temirlanKabylbekov/26fa29b79f1add037ee1c2c18441a212 to your computer and use it in GitHub Desktop.
Даны два списка, нужно вернуть элементы, которые есть в 1-ом списке, но нет во 2-ом. Оценить эффективность своего решения.
def symmetric_difference(lst1: list, lst2: list) -> list:
"""Возвращает элементы, которые есть в первом списке, но нет в обоих.
Скорость работы и используемая дополнительная память - линейна.
>>> symmetric_difference([], [])
[]
>>> symmetric_difference([], [1, 2])
[]
>>> symmetric_difference([1, 2, 3], [])
[1, 2, 3]
>>> symmetric_difference([4, 1], [1, 2, 3])
[4]
>>> symmetric_difference([1, 2, 3], [2])
[1, 3]
"""
make_counter = lambda lst: {el: True for el in lst}
counter1 = make_counter(lst1)
counter2 = make_counter(lst2)
return [el for el in counter1 if not counter2.get(el)]
if __name__ == "__main__":
import doctest
doctest.testmod()
'''
Trying:
symmetric_difference([], [])
Expecting:
[]
ok
Trying:
symmetric_difference([], [1, 2])
Expecting:
[]
ok
Trying:
symmetric_difference([1, 2, 3], [])
Expecting:
[1, 2, 3]
ok
Trying:
symmetric_difference([4, 1], [1, 2, 3])
Expecting:
[4]
ok
Trying:
symmetric_difference([1, 2, 3], [2])
Expecting:
[1, 3]
ok
Trying:
symmetric_difference([1, 1, 1, 2, 3], [2])
Expecting:
[1, 3]
ok
6 passed and 0 failed.
Test passed.
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment