Advertisement
Carcigenicate

Custom List

May 29th, 2014
290
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.82 KB | None | 0 0
  1. from random import randint
  2. from time import time
  3.  
  4. class Slot:
  5.     def __init__ (self, data = None):
  6.         self.data = data
  7.         self.nslot = None #"Next slot". Links to the next slot
  8.  
  9. class cList:
  10.     def __init__ (self):
  11.         #Where iteration starts
  12.         self.root = Slot()
  13.  
  14.         #The start is also the end of the container when it's empty
  15.         self.tail = self.root
  16.  
  17.         self.csize = 0
  18.  
  19.     def get_slot (self, index):
  20.         #Finds and returns the index'th slot
  21.         if self.root is None: raise KeyError("List is empty")
  22.         cslot = self.root #Current slot for iteration
  23.         for n in range(index + 1):
  24.             cslot = cslot.nslot #Advance cslot to its next linked slot
  25.         if cslot is None: raise KeyError #Reached the end of the container
  26.         return cslot
  27.  
  28.     def __getitem__ (self, key):
  29.         return self.get_slot(key).data
  30.  
  31.     def __setitem__ (self, key, value):
  32.         self.get_slot(key).data = value
  33.  
  34.     def add (self, data):
  35.         #Mimics List's append()
  36.         #Add a new slot linked to the container's tail
  37.         self.tail.nslot = Slot(data)
  38.  
  39.         #Reassign the new tail of the container
  40.         self.tail = self.tail.nslot
  41.  
  42.         #Increase the size counter by 1
  43.         self.csize += 1
  44.  
  45.     def __iter__ (self):
  46.         index = 0
  47.         while True:
  48.             try:
  49.                 yield self.__getitem__(index)
  50.                 index += 1
  51.             except KeyError:
  52.                 raise StopIteration
  53.    
  54.     def __len__ (self):
  55.         return self.csize
  56.  
  57. cl = cList()
  58.  
  59. cstime = time()
  60. for n in range(1000000):
  61.     cl.add(n)
  62. cetime = time() - cstime
  63. print("Custom list time:", cetime)
  64. del cl
  65.  
  66. l = []
  67.  
  68. lstime = time()
  69. for n in range(1000000):
  70.     l.append(n)
  71. etime = time() - lstime
  72. print("List time:", etime)
  73. del l
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement