Skip to content

Commit

Permalink
#1 removes if to use more polymorphism
Browse files Browse the repository at this point in the history
  • Loading branch information
taciogt committed Sep 13, 2020
1 parent 58ae125 commit 817a68a
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 13 deletions.
29 changes: 19 additions & 10 deletions src/sequences/linked_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,14 @@ def __iter__(self):
return _NodeIterator(current_node=self)

@property
def content(self):
raise AttributeError
@abstractmethod
def content(self) -> T:
...

@property
def next(self):
raise AttributeError
@abstractmethod
def next(self) -> _AbstractNode:
...


class _EmptyNode(_AbstractNode):
Expand All @@ -70,6 +72,14 @@ def __eq__(self, other):
def __getitem__(self, _):
raise IndexError

@property
def content(self):
raise AttributeError

@property
def next(self):
raise AttributeError


class _Node(_AbstractNode):
def __init__(self, content: T, *next_nodes: Sequence[T]):
Expand Down Expand Up @@ -125,13 +135,11 @@ def __len__(self):
length += 1
return length

def __str__(self):
if self.head is not _EmptyNode:
return f'{self.__class__.__name__}[{self.head}]'
else:
return f'{self.__class__.__name__}[]'
def __str__(self) -> str:
list_contents = ', '.join(map(str, self.head))
return f'{self.__class__.__name__}[{list_contents}]'

def __repr__(self):
def __repr__(self) -> str:
return self.__str__()

def __getitem__(self, item) -> Union[T, LinkedList]:
Expand All @@ -140,6 +148,7 @@ def include_index(index):
match_step = item.step is None or index % item.step == 0
should_stop = item.stop is not None and index >= item.stop
return item.start <= index and match_step and not should_stop

if self.head is not None:
return LinkedList(*[node for index, node in enumerate(self.head)
if include_index(index)])
Expand Down
6 changes: 3 additions & 3 deletions src/sequences/test_linked_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,16 @@
class TestLinkedListBasicMethods(TestCase):
def test_str(self):
linked_list = LinkedList(1, 2, 3)
self.assertEqual(str(linked_list), 'LinkedList[Node(1)->Node(2)->Node(3)]')
self.assertEqual(str(linked_list), 'LinkedList[1, 2, 3]')

linked_list = LinkedList(1)
self.assertEqual(str(linked_list), 'LinkedList[Node(1)]')
self.assertEqual(str(linked_list), 'LinkedList[1]')

linked_list = LinkedList()
self.assertEqual(str(linked_list), 'LinkedList[]')

linked_list = LinkedList(None)
self.assertEqual(str(linked_list), 'LinkedList[Node(None)]')
self.assertEqual(str(linked_list), 'LinkedList[None]')

def test_equality_with_same_type(self):
self.assertEqual(LinkedList(), LinkedList())
Expand Down

0 comments on commit 817a68a

Please sign in to comment.