python_morsels/tail/tail.py

28 lines
643 B
Python

def tail_v1(sequence, count):
"""My first take at this exercise."""
if count <= 0:
return list()
return list(sequence[-count:])
def tail_v2(sequence, count):
"""This solution can handle any iterator."""
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