@@ -47,22 +47,51 @@ def __repr__(self):
47
47
def __getitem__ (self , index ):
48
48
"""
49
49
Indexing Support. Used to get a node at particular position
50
+ >>> linked_list = LinkedList()
51
+ >>> for i in range(0, 10):
52
+ ... linked_list.insert_nth(i, i)
53
+ >>> all(str(linked_list[i]) == str(i) for i in range(0, 10))
54
+ True
55
+ >>> linked_list[-10]
56
+ Traceback (most recent call last):
57
+ ...
58
+ ValueError: list index out of range.
59
+ >>> linked_list[len(linked_list)]
60
+ Traceback (most recent call last):
61
+ ...
62
+ ValueError: list index out of range.
50
63
"""
51
- if index < 0 :
52
- raise ValueError ("Negative indexes are not yet supported " )
64
+ if not 0 <= index < len ( self ) :
65
+ raise ValueError ("list index out of range. " )
53
66
for i , node in enumerate (self ):
54
67
if i == index :
55
- return node . data
68
+ return node
56
69
57
70
# Used to change the data of a particular node
58
71
def __setitem__ (self , index , data ):
72
+ """
73
+ >>> linked_list = LinkedList()
74
+ >>> for i in range(0, 10):
75
+ ... linked_list.insert_nth(i, i)
76
+ >>> linked_list[0] = 666
77
+ >>> linked_list[0]
78
+ 666
79
+ >>> linked_list[5] = -666
80
+ >>> linked_list[5]
81
+ -666
82
+ >>> linked_list[-10] = 666
83
+ Traceback (most recent call last):
84
+ ...
85
+ ValueError: list index out of range.
86
+ >>> linked_list[len(linked_list)] = 666
87
+ Traceback (most recent call last):
88
+ ...
89
+ ValueError: list index out of range.
90
+ """
91
+ if not 0 <= index < len (self ):
92
+ raise ValueError ("list index out of range." )
59
93
current = self .head
60
- # If list is empty
61
- if current is None :
62
- raise IndexError ("The Linked List is empty" )
63
94
for i in range (index ):
64
- if current .next is None :
65
- raise IndexError ("list index out of range" )
66
95
current = current .next
67
96
current .data = data
68
97
@@ -163,8 +192,15 @@ def test_singly_linked_list() -> None:
163
192
assert linked_list .delete_head () == 0
164
193
assert linked_list .delete_nth (9 ) == 10
165
194
assert linked_list .delete_tail () == 11
195
+ assert len (linked_list ) == 9
166
196
assert str (linked_list ) == "->" .join (str (i ) for i in range (1 , 10 ))
167
197
198
+ assert all (linked_list [i ] == i + 1 for i in range (0 , 9 )) is True
199
+
200
+ for i in range (0 , 9 ):
201
+ linked_list [i ] = - i
202
+ assert all (linked_list [i ] == - i for i in range (0 , 9 )) is True
203
+
168
204
169
205
def main ():
170
206
from doctest import testmod
0 commit comments