various fixes

This commit is contained in:
Cameron Neville
2017-09-16 14:15:31 -04:00
parent 6739e940c4
commit b37cf0ea94

View File

@@ -15,6 +15,12 @@ class sortedlist:
def __len__(self):
return len(self.data)
def __repr__(self):
ret = 'sortedlist('
for i in self.data:
ret += str(i) + ', '
return ret[:-2] + ')'
def __str__(self):
return str(self.data)
@@ -23,11 +29,11 @@ class sortedlist:
def __add__(self, operand):
if isinstance(operand, list):
return sortedlist(self.merge(self.data, sorted(operand)), True)
return sortedlist(self.merge(self.data, sorted(operand)), presorted=True)
elif isinstance(operand, sortedlist):
return sortedlist(self.merge(self.data, operand.data), True)
return sortedlist(self.merge(self.data, operand.data), presorted=True)
else:
raise TypeError('can only concatenate list or sortedlist (not "%s") to sortedlist' % type(operand).__name__)
return NotImplemented
#because of sorting, addition is commutative (a + b == b + a)
def __radd__(self, operand):
@@ -35,6 +41,7 @@ class sortedlist:
def __iadd__(self, operand):
self.data = (self + operand).data
return self
#takes two sorted lists (not sortedlists) and returns a sorted combination at O(n)
def merge(self, data1, data2):
@@ -88,28 +95,31 @@ class sortedlist:
else:
return True
#returns an arbitrary index that contains the value at O(log(n))
#returns -1 if the list doesn't contain the value
def index(self, val):
ind = self.indexhelper(self.data, val)
if ind == len(self):
ind = -1
return ind
pass
#at this point I think I'm just bad at defining recursive functions
def indexhelper(self, dat, val):
ind = int(len(dat)/2)
if len(dat) == 0:
return 0
elif dat[ind] == val:
return ind
elif dat[ind] < val:
return ind + 1 + self.indexhelper(dat[ind+1:], val)
#returns an arbitrary index that contains the value, at O(log(n))
def index(self, value):
low = 0
high = len(self)
mid = (low + high) / 2
while self[mid] != value:
if self[mid] > value:
high = mid
else:
return self.indexhelper(dat[:ind], val)
low = mid
mid = (high + low) / 2
if high in (low, low+1):
raise ValueError('sortedlist does not contain entry')
return mid
#TODO: add functionality for single=False
def remove(self, entry, single=True):
#removes a single instance of entry, raises exception if it doesn't exist
def remove(self, entry):
del(self[self.index(entry)])
#removes every instance of entry, doesn't raise an exception if it doesn't exist
#TODO: index once, then search adacent indices
def removeall(self, entry):
while True:
try:
del(self[self.index(entry)])
except ValueError:
break