Implement the __getitem__ method to work with positive and negative indices. For example: > W = L1(Node(10, Node(20, Node(30)))) > print W [ 10, 20, 30 ] > print W[0], W[1], W[2] > print W[-1], W[-2], W[-3] 10 20 30 30 20 10 Be aware of cases where the index exceeds the size of the list, either positive or negative. In these cases you have to generate an assertion error. In the above example, W[3] and W[-4] should raise an AssertionError Complete the Code: class L(object): def __init__ (self, first_node=None): assert first_node is None or isinstance(first_node,Node), "first must be Node, not %s"%(type(first_node)) self.first_node = first_node def __len__(self): k = self.first_node if k is None: return 0 i=1 while k.next is not None: i+=1 k = k.next return i def __repr__ (self): if self.first_node is None: return "[]" s = "[ %s"%self.first_node k=self.first_node while (k.next is not None): s += ", %s"%k.next k = k.next return s+" ]" def L1(*args,**kwargs): class L1_class(L): def __getitem__(self, idx): return <... Your Code Here ...> return L1_class(*args,**kwargs)
Implement the __getitem__ method to work with positive and negative indices. For example:
> W = L1(Node(10, Node(20, Node(30))))
> print W
[ 10, 20, 30 ]
> print W[0], W[1], W[2]
> print W[-1], W[-2], W[-3]
10 20 30
30 20 10
Be aware of cases where the index exceeds the size of the list, either positive or negative. In these cases you have to generate an assertion error.
In the above example, W[3] and W[-4] should raise an AssertionError
Complete the Code:
class L(object):
def __init__ (self, first_node=None):
assert first_node is None or isinstance(first_node,Node), "first must be Node, not %s"%(type(first_node))
self.first_node = first_node
def __len__(self):
k = self.first_node
if k is None:
return 0
i=1
while k.next is not None:
i+=1
k = k.next
return i
def __repr__ (self):
if self.first_node is None:
return "[]"
s = "[ %s"%self.first_node
k=self.first_node
while (k.next is not None):
s += ", %s"%k.next
k = k.next
return s+" ]"
def L1(*args,**kwargs):
class L1_class(L):
def __getitem__(self, idx):
return <... Your Code Here ...>
return L1_class(*args,**kwargs)
Trending now
This is a popular solution!
Step by step
Solved in 4 steps with 3 images