Hacktoberfest: Update Linked List - print_reverse method (#2792)

* chore: update print_reverse helper method

Use a generator expression instead of slicing
`elements_list` to improve the space and time complexity
of `make_linked_list` to O(1) space and O(n) time
by avoiding the creation a shallow copy of `elements_list`.

* fix: add type checking and argument typing

Add argument typing to all methods in `print_reverse`

Add doctest to helper function `make_linked_list` and
basic edge case tests to `print_reverse`

* test: add `print_reverse` test

Fix doctest syntax and remove edge case tests that are covered
by typed arguments.

Add `print_reverse` test that expects the correct values are printed
out by adding a `test_print_reverse_output` helper function.

* format code

Co-authored-by: shellhub <shellhub.me@gmail.com>
This commit is contained in:
Sherman Hui 2020-10-05 04:08:57 -07:00 committed by GitHub
parent 437c725e64
commit 477b2c24b8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,4 +1,4 @@
# Program to print the elements of a linked list in reverse from typing import List
class Node: class Node:
@ -8,48 +8,63 @@ class Node:
def __repr__(self): def __repr__(self):
"""Returns a visual representation of the node and all its following nodes.""" """Returns a visual representation of the node and all its following nodes."""
string_rep = "" string_rep = []
temp = self temp = self
while temp: while temp:
string_rep += f"<{temp.data}> ---> " string_rep.append(f"{temp.data}")
temp = temp.next temp = temp.next
string_rep += "<END>" return "->".join(string_rep)
return string_rep
def make_linked_list(elements_list): def make_linked_list(elements_list: List):
"""Creates a Linked List from the elements of the given sequence """Creates a Linked List from the elements of the given sequence
(list/tuple) and returns the head of the Linked List.""" (list/tuple) and returns the head of the Linked List.
>>> make_linked_list([])
# if elements_list is empty Traceback (most recent call last):
...
Exception: The Elements List is empty
>>> make_linked_list([7])
7
>>> make_linked_list(['abc'])
abc
>>> make_linked_list([7, 25])
7->25
"""
if not elements_list: if not elements_list:
raise Exception("The Elements List is empty") raise Exception("The Elements List is empty")
# Set first element as Head current = head = Node(elements_list[0])
head = Node(elements_list[0]) for i in range(1, len(elements_list)):
current = head current.next = Node(elements_list[i])
# Loop through elements from position 1
for data in elements_list[1:]:
current.next = Node(data)
current = current.next current = current.next
return head return head
def print_reverse(head_node): def print_reverse(head_node: Node) -> None:
"""Prints the elements of the given Linked List in reverse order""" """Prints the elements of the given Linked List in reverse order
>>> print_reverse([])
# If reached end of the List >>> linked_list = make_linked_list([69, 88, 73])
if head_node is None: >>> print_reverse(linked_list)
return None 73
else: 88
# Recurse 69
"""
if head_node is not None and isinstance(head_node, Node):
print_reverse(head_node.next) print_reverse(head_node.next)
print(head_node.data) print(head_node.data)
list_data = [14, 52, 14, 12, 43] def main():
linked_list = make_linked_list(list_data) from doctest import testmod
testmod()
linked_list = make_linked_list([14, 52, 14, 12, 43])
print("Linked List:") print("Linked List:")
print(linked_list) print(linked_list)
print("Elements in Reverse:") print("Elements in Reverse:")
print_reverse(linked_list) print_reverse(linked_list)
if __name__ == "__main__":
main()