Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Just for demo. DON'T DO THIS IN PRODUCTION CODE
- import sys
- class List(object):
- class Node(object):
- def __init__(self, data):
- self.data = data
- self.next = None
- def __init__(self):
- self.head = None
- self.current = None
- def __iter__(self):
- while self.current is not None:
- yield self.current.data
- self.current = self.current.next
- self.current = self.head # reset self.current for later use
- def __len__(self):
- count = 0
- while self.current is not None:
- count += 1
- self.current = self.current.next
- self.current = self.head # reset self.current for later use
- return count
- def __getitem__(self, key):
- if not isinstance(key, int):
- raise TypeError
- value = None
- if key >= 0:
- count = 0
- while self.current is not None:
- if count == key:
- value = self.current.data
- break
- count += 1
- self.current = self.current.next
- self.current = self.head
- if key > count:
- raise IndexError
- else:
- count = -len(self)
- if key < count:
- raise IndexError
- while self.current is not None:
- if count == key:
- value = self.current.data
- break
- count += 1
- self.current = self.current.next
- self.current = self.head
- return value
- def __setitem__(self, key, value):
- if not isinstance(key, int):
- raise TypeError
- if key >= 0:
- count = 0
- while self.current is not None:
- if key == count:
- self.current.data = value
- break
- count += 1
- self.current = self.current.next
- self.current = self.head
- if key > count:
- raise IndexError
- else:
- count = -len(self)
- if key < count:
- raise IndexError
- while self.current is not None:
- if key == count:
- self.current.data = value
- break
- count += 1
- self.current = self.current.next
- self.current = self.head
- def append(self, data):
- klass = globals()[self.__class__.__name__]
- node = klass.Node(data)
- if self.head is None:
- self.head = node
- self.current = self.head
- else:
- current = self.head
- while current.next is not None:
- current = current.next
- current.next = node
- if __name__ == '__main__':
- _list = List()
- _list.append(33)
- _list.append(55)
- _list.append(88)
- _list.append(77)
- print 'length:', len(_list)
- print '3rd item:', _list[2]
- print 'last item:', _list[-1]
- try:
- print _list[99]
- except IndexError:
- sys.stderr.write("Out of range\n")
- for e in _list:
- print e
- print 'Change _list item'
- _list[0] = 100
- for e in _list:
- print e
- try:
- _list[99] = 66
- except IndexError:
- sys.stderr.write("Out of range\n")
- for e in _list:
- print e
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement