tail: added a third, memory efficient, solution.
This commit is contained in:
parent
addba9ca0a
commit
7ac0068aa2
16
tail/tail.py
16
tail/tail.py
|
|
@ -1,13 +1,27 @@
|
||||||
def tail_v1(sequence, count):
|
def tail_v1(sequence, count):
|
||||||
|
"""My first take at this exercise."""
|
||||||
if count <= 0:
|
if count <= 0:
|
||||||
return list()
|
return list()
|
||||||
return list(sequence[-count:])
|
return list(sequence[-count:])
|
||||||
|
|
||||||
|
|
||||||
def tail_v2(sequence, count):
|
def tail_v2(sequence, count):
|
||||||
|
"""This solution can handle any iterator."""
|
||||||
if count <= 0:
|
if count <= 0:
|
||||||
return []
|
return []
|
||||||
return list(list(sequence)[-count:])
|
return list(list(sequence)[-count:])
|
||||||
|
|
||||||
|
|
||||||
tail = tail_v2
|
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
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue