Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from random import randint
- from time import time
- class Slot:
- def __init__ (self, data = None):
- self.data = data
- self.nslot = None #"Next slot". Links to the next slot
- class cList:
- def __init__ (self):
- #Where iteration starts
- self.root = Slot()
- #The start is also the end of the container when it's empty
- self.tail = self.root
- self.csize = 0
- def get_slot (self, index):
- #Finds and returns the index'th slot
- if self.root is None: raise KeyError("List is empty")
- cslot = self.root #Current slot for iteration
- for n in range(index + 1):
- cslot = cslot.nslot #Advance cslot to its next linked slot
- if cslot is None: raise KeyError #Reached the end of the container
- return cslot
- def __getitem__ (self, key):
- return self.get_slot(key).data
- def __setitem__ (self, key, value):
- self.get_slot(key).data = value
- def add (self, data):
- #Mimics List's append()
- #Add a new slot linked to the container's tail
- self.tail.nslot = Slot(data)
- #Reassign the new tail of the container
- self.tail = self.tail.nslot
- #Increase the size counter by 1
- self.csize += 1
- def __iter__ (self):
- index = 0
- while True:
- try:
- yield self.__getitem__(index)
- index += 1
- except KeyError:
- raise StopIteration
- def __len__ (self):
- return self.csize
- cl = cList()
- cstime = time()
- for n in range(1000000):
- cl.add(n)
- cetime = time() - cstime
- print("Custom list time:", cetime)
- del cl
- l = []
- lstime = time()
- for n in range(1000000):
- l.append(n)
- etime = time() - lstime
- print("List time:", etime)
- del l
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement