def meetPools(start, goal, upperBound, sparse=False, log=False): startPool = [SortedList([]), SortedList([start])] goalPool = [SortedList([]), SortedList([goal])] if sparse: startPool = SparseList(startPool, length=8) goalPool = SparseList(goalPool, length=8) overlapByStart = [] overlapByGoal = [] overlapCenter = [] startFull = False goalFull = False while True: if log: print("s", end="") startFull = expandSegmentedPool(start, startPool, upperBound, log=log) if log: print("i", end="") overlapByStart = intersect(startPool[-1], goalPool[-1]) if len(overlapByStart) > 0: break if log: print("g", end="") goalFull = expandSegmentedPool(goal, goalPool, upperBound, log=log) if log: print("i", end="") overlapByGoal = intersect(startPool[-2], goalPool[-1]) if len(overlapByGoal) > 0: break if log: print("i", end="") overlapCenter = intersect(startPool[-1], goalPool[-1]) if len(overlapCenter) > 0: break if goalFull or startFull: break return (startPool, goalPool, [ item for test in [overlapByStart, overlapByGoal, overlapCenter] for item in test ])
def __init__(self, inputList, lag=16): self.lag = lag self.base = SortedList(inputList) #self.base = SortedList.__init__(inputList) # if self.lag > 8: # self.hat = SortedStack([],lag=self.lag//2) # else: self.hat = []
def transpose(self): T = Matrix() for i in range(len(self)): L = SortedList() for j in range(len(self)): if i in self[j]: L.add(j) T.insert_col(L) return T
def test_sub(self): s = SortedList([1, 4, 5]) o = SortedList([9, 8, 7]) s - o self.assertEqual(s, [1, 4, 5, 7, 8, 9]) self.assertEqual(o, [7, 8, 9]) p = SortedList([1, 2, 4, 5]) s - p self.assertEqual(s, [2, 7, 8, 9]) self.assertEqual(p, [1, 2, 4, 5])
def __init__(self, dictionary=None, key=None, **kwargs): """Initializes with a shallow copy of the given dictionary and/or with keyword key=value pairs and preserving order using the key function. All keys must be unique. key is a key function which defaults to the identity function if it is not specified >>> d = SortedDict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> list(d.items()) [('a', 2), ('i', 4), ('n', 3), ('s', 1), ('t', 5), ('y', 6)] >>> dict(SortedDict()) {} >>> e = SortedDict(d) >>> list(e.items()) [('a', 2), ('i', 4), ('n', 3), ('s', 1), ('t', 5), ('y', 6)] >>> dict(e) {'a': 2, 'i': 4, 's': 1, 't': 5, 'y': 6, 'n': 3} >>> f = SortedDict(key=str.lower, S=1, a=2, n=3, I=4, T=5, y=6) >>> dict(f) {'a': 2, 'I': 4, 'S': 1, 'T': 5, 'y': 6, 'n': 3} """ dictionary = dictionary or {} # this copy initialize the dict type super().__init__(dictionary) # using dict type's __init__ to initialize the dictionary , # even there is None, we still initialize {} if kwargs: super().update(kwargs) # adding the kwargs into dictionary self.__keys = SortedList.SortedList(super().keys(), key)
def __init__(self, dictionary=None, key=None, **kwargs): """Inicializuje se mělkou kopií zadaného slovníku a nebo dvojicemi klíč=hodnota, jejichž pořadí zůstane zachováno klíč je klíčová funkce, která je ve výchozím stavu zastoupena funkcí představující identitu >>> d = SortedDict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> list(d.items()) [('a', 2), ('i', 4), ('n', 3), ('s', 1), ('t', 5), ('y', 6)] >>> dict(SortedDict()) {} >>> e = SortedDict(d) >>> list(e.items()) [('a', 2), ('i', 4), ('n', 3), ('s', 1), ('t', 5), ('y', 6)] >>> dict(e) {'a': 2, 'i': 4, 's': 1, 't': 5, 'y': 6, 'n': 3} >>> f = SortedDict(key=str.lower, S=1, a=2, n=3, I=4, T=5, y=6) >>> dict(f) {'a': 2, 'I': 4, 'S': 1, 'T': 5, 'y': 6, 'n': 3} """ dictionary = dictionary or {} super().__init__(dictionary) if kwargs: super().update(kwargs) self.__keys = SortedList.SortedList(super().keys(), key)
def test_add(self): s = SortedList() for i in range(10): s.add(i + (-1)**i) self.assertEqual(s, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) s = SortedList() self.assertFalse(s) for i in {2, 5, 8, 0, 1, 3}: s.add(i) self.assertEqual(s, [0, 1, 2, 3, 5, 8])
def generatePoolEdgewise(around, numItems, upperBound, numIters=-1, sparse=False, log=True): startTime = time.clock() pool = [SortedList([]), SortedList([around])] if sparse: pool = SparseList(pool) poolSize = lambda: sum(len(generation) for generation in pool) while (poolSize() < numItems) if numIters < 0 else ( (pool.totalLength() if sparse else len(pool)) - 2 < numIters): shouldStop = expandSegmentedPool(around, pool, upperBound, log=log) if shouldStop: break if log: print("generatePoolEdgewise took " + str(time.clock() - startTime) + " seconds") return pool
def reduce(self): # doesn't use union-find av = {} # annotation vectors avT = {} # transpose of annotation vectors for i in range(len(self)): temp = SortedList() # so that I can use ^ for j in self.R[i]: if j in av: temp ^= av[j] if not temp: av[i] = SortedList([i]) avT[i] = [i] else: low = temp.pop() av[i] = temp for j in temp: avT[j].append(i) for k in avT.pop(low): av[k].remove(low) av[k] = av[k] ^ temp self.dgm[low] = i
def update(self, dictionary=None, **kwargs): if dictionary is None: pass elif isinstance(dictionary, dict): super().update(dictionary) else: for key, value in dictionary.items(): super().__setitem__(key, value) if kwargs: super().update(kwargs) self._keys = SortedList.SortedList(super().keys(), self._keys.key)
def test_max(self): s = SortedList() for i in {3, 4, 2, 6, 8}: s.add(i) self.assertEqual(max(s), 8) s.add(100) self.assertEqual(max(s), 100)
def test_min(self): s = SortedList() for i in {1, 3, 4, 7, 2, 4, 8}: s.add(i) self.assertEqual(min(s), 1) s.add(0) self.assertEqual(min(s), 0)
def test_len(self): s = SortedList() for i in range(20): s.add(i) self.assertEqual(len(s), 20) s.remove(4) self.assertEqual(len(s), 19)
def test_remove(self): s = SortedList() for i in range(10): s.add(i + (-1)**i) for i in range(10): s.remove(i) self.assertFalse(s)
class Day: def __init__(self): self.day_interval = SortedList() def insert_interval(self, start, end, name): self.day_interval.insert(start, end, name) def is_overlap(self, start, end): return self.day_interval.is_overlap(start, end) #iterate through every class in a day def __iter__(self): for i in self.day_interval: yield i def __str__(self): return str(self.day_interval) def copy(self): day = Day() for start, end, name in self.day_interval: day.insert_interval(start, end, name) return day
def poolExpansion(startBatch, goal, exclusions, upperBound): stopAt = len(startBatch) result = SortedList([]) i = 0 while i < stopAt: result.extend(optionsFrom(startBatch[i], goal, exclusions, upperBound)) i += 1 result.sort() dedupe(result) return result
def __init__(self, dictionary=None, key=None, **kwargs): """ Initializatizes with a shallow copy of the given dictionary and/or with keyword key=value pairs and preserving order using this key is a key function which defaults to the identity function if it is not specified >>> d = SortedDict(dict(s=1, a=2, n=3, i=4,, t=5, y=6)) >>> list(d.items()) [('a', 2), ('i', 4), ('n', 3), ('s', 1), ('t', 5), ('y', 6)] >>> dict(e) {'a': 2, 'i': 4, 's': 1, 't': 5, 'y': 6, 'n': 3} >>> d = SortedDict(key=str.lower, S=1, a=2, n=3, I=4, T=5, y=6) >>> dict(f) {'a': 2, 'I': 4, 'S': 1, 'T': 5, 'y': 6, 'n': 3} """ dictionary = dictionary or {} super().__init__(dictionary) if kwargs: super().update(kwargs) self.__keys = SortedList.SortedList(super().keys(), key)
def update(self, dictionary=None, **kwargs): """Updates this dictionary with another dictionary and/or with keyword key=value pairs and preserving order using this dictionary's key function >>> d = SortedDict(dict(s=1, a=2, n=3, i=4, t=5)) >>> d.update(dict(a=4, z=-4)) >>> list(d.items()) [('a', 4), ('i', 4), ('n', 3), ('s', 1), ('t', 5), ('z', -4)] >>> del d["a"] >>> del d["i"] >>> d.update({'g': 9}, a=1, z=3) >>> list(d.items()) [('a', 1), ('g', 9), ('n', 3), ('s', 1), ('t', 5), ('z', 3)] >>> e = SortedDict(dict(p=4, q=5)) >>> del d["a"] >>> del d["n"] >>> e.update(d) >>> list(e.items()) [('g', 9), ('p', 4), ('q', 5), ('s', 1), ('t', 5), ('z', 3)] >>> del d["s"] >>> del d["z"] >>> d.update(e) >>> list(d.items()) [('g', 9), ('p', 4), ('q', 5), ('s', 1), ('t', 5), ('z', 3)] """ if dictionary is None: pass elif isinstance(dictionary, dict): # This still apply to Sorteddict type super().update(dictionary) else: # to update list type ! for key, value in dictionary.items(): super().__setitem__(key, value) if kwargs: super().update(kwargs) #Sort again self.__keys = SortedList.SortedList(super().keys(), self.__keys.key)
def search(self, current): print("----------") print("Current: {}".format(current.label)) current.visitaded = True if current == self.goal: self.find = True else: sorted_list = SortedList(len(current.adjacent)) for i in current.adjacent: if i.vertex.visitaded == False: i.vertex.visitaded == True sorted_list.add(i.vertex) sorted_list.show() if sorted_list.values[0] != None: self.search(sorted_list.values[0])
def update(self, dictionary=None, **kwargs): """Aktualizuje tento slovník jiným slovníkem a nebo dvojicemi klíč=hodnota, při čemž se zachová pořadí s použitím klíčové funkce slovníku >>> d = SortedDict(dict(s=1, a=2, n=3, i=4, t=5)) >>> d.update(dict(a=4, z=-4)) >>> list(d.items()) [('a', 4), ('i', 4), ('n', 3), ('s', 1), ('t', 5), ('z', -4)] >>> del d["a"] >>> del d["i"] >>> d.update({'g': 9}, a=1, z=3) >>> list(d.items()) [('a', 1), ('g', 9), ('n', 3), ('s', 1), ('t', 5), ('z', 3)] >>> e = SortedDict(dict(p=4, q=5)) >>> del d["a"] >>> del d["n"] >>> e.update(d) >>> list(e.items()) [('g', 9), ('p', 4), ('q', 5), ('s', 1), ('t', 5), ('z', 3)] >>> del d["s"] >>> del d["z"] >>> d.update(e) >>> list(d.items()) [('g', 9), ('p', 4), ('q', 5), ('s', 1), ('t', 5), ('z', 3)] """ if dictionary is None: pass elif isinstance(dictionary, dict): super().update(dictionary) else: for key, value in dictionary.items(): super().__setitem__(key, value) if kwargs: super().update(kwargs) self.__keys = SortedList.SortedList(super().keys(), self.__keys.key)
def generatePool(around, numItems, upperBound, numIters=-1): startTime = time.clock() pool = SortedList([around]) extension = SortedList([around]) iter = 0 lastLength = 0 while (len(pool) < numItems and numIters < 0) or iter < numIters: extension = poolExpansion( extension, around, pool, upperBound ) #iterating on only the last iteration's extension decreases work complexity if len(extension) == 0: print("pool full at " + str(len(pool)) + " items") numItems = -1 lastLength = len(pool) print(".", end="") pool.extend(extension) pool.sort() dedupe(pool) print("iter " + str(iter) + ": added " + str(len(pool) - lastLength) + "/" + str(len(extension)) + " items to pool, it now has " + str(len(pool)) + "/" + str(numItems)) iter += 1 print("generatePool took " + str(time.clock() - startTime) + " seconds") return pool
def __init__(self, dictionary=None, key=None, **kwargs): dictionary = dictionary or {} super().__init__(dictionary) if kwargs: super().update(kwargs) self._keys = SortedList.SortedList(super().keys(), key)
def setUp(self): self.lista = SortedList.SortedList()
def __init__(self): self.day_interval = SortedList()
def test_eq(self): s = SortedList([2, 4, 5, 1]) q = SortedList([1, 2, 4, 5]) self.assertEqual(s, [1, 2, 4, 5]) self.assertEqual(s, q)
def search(self, current): print("----------") print("Current: {}".format(current.label)) current.visitaded = True if current == self.goal: self.find = True else: sorted_list = SortedList(len(current.adjacent)) for i in current.adjacent: if i.vertex.visitaded == False: i.vertex.visitaded == True sorted_list.add(i.vertex) sorted_list.show() if sorted_list.values[0] != None: self.search(sorted_list.values[0]) graph = Graph() graph.arad.show_adjacent() list = SortedList(5) list.add(graph.arad) list.add(graph.craiova) list.add(graph.bucharest) list.add(graph.dobreta) list.show() greedy_search = GreedySearch(graph.bucharest) greedy_search.search(graph.arad)
def test_init(self): s = SortedList() p = SortedList([9, 7, 8]) self.assertEqual(p, [7, 8, 9])
class SortedStack: def __init__(self, inputList, lag=16): self.lag = lag self.base = SortedList(inputList) #self.base = SortedList.__init__(inputList) # if self.lag > 8: # self.hat = SortedStack([],lag=self.lag//2) # else: self.hat = [] def __len__(self): return len(self.base) + len(self.hat) def __str__(self): return str(self.base)[:-1] + ", " + str(self.hat)[1:] def __getitem__(self, index): if index < 0: return self[len(self) + index] return self.base[index] if index < len( self.base) else self.hat[index - len(self.base)] def __setitem__(self, index, value): #if type(value) != int: # raise TypeError if index < 0: self[len(self) + index] = value if index < len(self.base): self.base[index] = value else: self.hat[index - len(self.base)] = value def __delitem__(self, index): if index < len(self.base): self.base.__delitem__(index) else: self.hat.__delitem__(index - len(self.base)) if len(self.hat) == 0: print("SortedStack hat is gone, base length is " + str(len(self.base))) def append(self, item): #if type(item) != int: # raise TypeError if len(self.base) == 0 or self.base[-1] < item: self.base.append(item) else: self.hat.append(item) def extend(self, items): for item in items: self.append(item) def sort(self): #print("SortedStack.sort() - only the hat of this stack will be sorted;"), self.hat.sort() #print(" the hat was sorted") def __contains__(self, value): self.adjust() if len(self.base) < 1: return self.hat.__contains__(value) if value > self.base[-1]: return False return self.hat.__contains__(value) or self.base.__contains__(value) def adjust(self): if len(self.hat) > self.lag: #self.hat.sort() self.base.extend(self.hat) del self.hat[:] self.base.sort() def clear(self): self.base.clear() del self.hat[:]
def test_contains(self): s = SortedList() for i in {2, 4, 6, 7, 8, 9}: s.add(i) for i in {2, 4, 6, 7, 8, 9}: self.assertIn(i, s)
def test_getitem(self): s = SortedList() for i in {1, 3, 5, 7, 9}: s.add(i) for i in range(5): self.assertEqual(s[i], 2 * i + 1)