From 7ac0068aa20e000388cd83ed145222fd724b25c8 Mon Sep 17 00:00:00 2001 From: Cacahuete Date: Mon, 21 Dec 2020 22:48:30 +0100 Subject: [PATCH] tail: added a third, memory efficient, solution. --- tail/tail.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/tail/tail.py b/tail/tail.py index 98696f7..b6cc1bc 100644 --- a/tail/tail.py +++ b/tail/tail.py @@ -1,13 +1,27 @@ 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:]) -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