python_morsels/tail/tail.py

28 lines
643 B
Python
Raw Permalink Normal View History

2020-12-19 23:04:37 +01:00
def tail_v1(sequence, count):
"""My first take at this exercise."""
2020-12-19 23:04:37 +01:00
if count <= 0:
return list()
return list(sequence[-count:])
def tail_v2(sequence, count):
"""This solution can handle any iterator."""
2020-12-19 23:04:37 +01:00
if count <= 0:
return []
return list(list(sequence)[-count:])
def tail_v3(iterable, n):
"""Based on Trey's explanations, this solution is more memory efficient."""
result = []
if n > 0:
for element in iterable:
if n == 1:
result = [element]
else:
result = [*result[-n + 1 :], element]
return result
tail = tail_v3