def test_intersection(self): fridge_parts = Set( ["Philistine", "Rodedenrinator", "Turitron", "Coldness"]) freezer_parts = Set(["Rodedenrinator", "Turitron", "Coldness"]) boat_parts = fridge_parts.get_intersection(freezer_parts) assert (boat_parts.size) is 3
def generate(self, elems): """ Returns the subgroup of self generated by GroupElems elems If any of the items aren't already GroupElems, we will try to convert them to GroupElems before continuing. elems must be iterable """ elems = Set(g if isinstance(g, GroupElem) else GroupElem(g, self) \ for g in elems) if not elems <= self.group_elems: raise ValueError("elems must be a subset of self.group_elems") if len(elems) == 0: raise ValueError("elems must have at least one element") oldG = elems while True: newG = oldG | Set(a * b for a in oldG for b in oldG) if oldG == newG: break else: oldG = newG oldG = Set(g.elem for g in oldG) return Group(oldG, self.bin_op.new_domains(oldG * oldG, oldG))
def test_union(self): car_parts = Set(["Smuffler", "Dongler", "Transplanifier"]) assert (car_parts.size) is 3 soup_ing = Set(["Lettuce", "Lentils", "Ginger Snaps", "Tangelos"]) assert (soup_ing.size) is 4 new_soup = car_parts.get_union(soup_ing) assert (new_soup.size) is 7
def test_difference(self): fridge_parts = Set( ["Philistine", "Rodedenrinator", "Turitron", "Coldness"]) freezer_parts = Set(["Rodedenrinator", "Turitron", "Coldness"]) accordian_parts = fridge_parts.get_difference(freezer_parts) assert (accordian_parts.size) is 1 assert (accordian_parts.contains("Philistine")) sump_parts = freezer_parts.get_difference(fridge_parts) assert (sump_parts.size) is 0
def __div__(self, other): """ Returns the quotient group self / other """ if not other.is_normal_subgroup(self): raise ValueError("other must be a normal subgroup of self") G = Set(Set(self.bin_op((g, h)) for h in other.Set) for g in self.Set) def multiply_cosets(x): h = x[0].pick() return Set(self.bin_op((h, g)) for g in x[1]) return Group(G, Function(G * G, G, multiply_cosets))
def testProdCart(self): newSet = Set([1, 2, 3, 4, 1, 3, 7]) newSetB = Set([1, 2, 3, 4, 1, 8, 3, 7]) self.assertTrue( newSet.prodCart(newSetB) == [(1, 1), (1, 2), (1, 3), (1, 4), ( 1, 8), (1, 7), (2, 1), (2, 2), (2, 3), (2, 4), (2, 8), ( 2, 7), (3, 1), (3, 2), (3, 3), (3, 4), (3, 8), ( 3, 7), (4, 1), (4, 2), (4, 3), (4, 4), (4, 8), ( 4, 7), (7, 1), (7, 2), (7, 3), (7, 4), (7, 8), (7, 7)])
def subgroups(self): """Returns the Set of self's subgroups""" old_sgs = Set([self.generate([self.e])]) while True: new_sgs = old_sgs | Set(self.generate(list(sg.group_elems) + [g]) \ for sg in old_sgs for g in self \ if g not in sg.group_elems) if new_sgs == old_sgs: break else: old_sgs = new_sgs return old_sgs
def test_set_equals(): equalsset1 = Set([100, 500, 2, 1, 5, 0, -1, 2000, 2000]) equalsset2 = Set([0, 5, 1, 2, -1, 500, 100, 2000]) assert equalsset1.equals(equalsset2), "Test Case Failed" equalsset1.rm(2000) equalsset2.rm(2000) equalsset1.add(-1) equalsset1.add(-1) assert equalsset1.equals(equalsset2), "Test Case Failed" equalsset1.add(101) assert equalsset1.equals(equalsset2) is False, "Test Case Failed"
def main(): SetA = Set([1, 3, 5, 7, 9, 10, 11, 13, 15, 17, 19]) SetB = Set([2, 4, 6, 8, 10, 12, 14, 16, 18]) print(SetA.Size()) SetUnion = SetA | SetB SetInt = SetA & SetB for i in SetUnion: print(i) for i in SetInt: print(i)
def get_alpha_G(self, K): robot_ids = Set([e.id for e in self.robots]) task_ids = Set([e.id for e in self.tasks]) V = Set.descartes_product(robot_ids, task_ids) V_K = Set([Set(e) for e in itertools.combinations(V, K)]) S_K = self.history S_K_1 = Set(self.history[:-1]) print("...Calculating alpha_G...") alpha_G = -float('inf') N = len(V_K) progress_bar = ProgressBar(N) instrument = Instrument() instrument.start() k = 0 for Omega in V_K: progress_bar.progress(k) k = k + 1 for j_i in S_K_1.setminus(Omega): i = S_K.index(j_i) S_i_1 = Allocation(self.history[0:i]) lhs = Allocation(S_i_1.union(Omega)).get_derivative(Set([j_i])) rhs = S_i_1.get_derivative(Set([j_i])) frac = (lhs - rhs) / lhs if frac > alpha_G and rhs != 0 and lhs != 0: alpha_G = frac progress_bar.progress(N, 'Finished!\n') calculation_time = instrument.stop() print("Calculation time [s]:", calculation_time) print("Finished calculating alpha_G!\n") return alpha_G
def checkFreedom(self, x1, y1, x2, y2, x3, y3, name): bordMax = 8 bordMin = 0 #this check if theres a stone piece in front of behind him. If that's true and it is the same color #than those pieces will share there freedoms if self.stone.posx != bordMax: if self.stone.board.printBoard[self.stone.posx + x1][ self.stone.posy + y1] == 'bl' or self.stone.board.printBoard[ self.stone.posx + x1][self.stone.posy + y1] == 'wh': if self.stone.board.playBoard[self.stone.posx + x1][ self.stone.posy + y1].color == self.stone.color: self.stone.set = self.stone.board.playBoard[ self.stone.posx + x1][self.stone.posy + y1].set # print(self.stone.set.freedom) self.stone.set.freedom = self.stone.set.freedom + self.stone.freedom - 2 if self.stone.posy != bordMax: if self.stone.board.printBoard[self.stone.posx + x2][ self.stone.posy + y2] == 'bl' or self.stone.board.printBoard[ self.stone.posx + x2][self.stone.posy + y2] == 'wh': if self.stone.board.playBoard[ self.stone.posx + x2][self.stone.posy + y2].color == self.stone.color: self.stone.set.freedom = self.stone.set.freedom - 1 if self.stone.posy != bordMin: if self.stone.board.printBoard[self.stone.posx + x3][ self.stone.posy + y3] == 'bl' or self.stone.board.printBoard[ self.stone.posx + x3][self.stone.posy + y3] == 'wh': if self.stone.board.playBoard[ self.stone.posx + x3][self.stone.posy + y3].color == self.stone.color: self.stone.set.freedom = self.stone.set.freedom - 1 elif name: self.stone.set = Set(self.stone.freedom) elif name: self.stone.set = Set(self.stone.freedom) elif name: self.stone.set = Set(self.stone.freedom) if name: print(self.stone.set.teamTag) print(self.stone.set.freedom)
def makeGraphFromEdges2(self, edges): """ Constructs an un-directional graph from edges (a list of tuple). Each tuple contains 2 vertices. An un-directional graph is implemented as a directional graph where each edges runs both directions. @param edges: list of edges @type edges: list of 2-element tuples""" if type(edges) != list: raise GraphParameterError('Edges must be a \ list of tuples') from Set import Set from Matrix import Matrix vertices = list(Set([x[0] for x in edges] + [x[1] for x in edges])) adj = Matrix(len(vertices)) adj = adj.m for e in edges: row = vertices.index(e[0]) col = vertices.index(e[1]) # fill values into lower triangular matrix adj[row][col] = adj[row][col] + 1 # repeat on the upper triangular matrix for undirectional graph adj[col][row] = adj[col][row] + 1 adj.insert(0, vertices) self.makeGraphFromAdjacency(adj)
def makeGraphFromEdges1(self, edges): """ Constructs a directional graph from edges (a list of tuple). Each tuple contains 2 vertices. For example, P -> Q is written as ('P', 'Q'). @param edges: edges @type edges: list of 2-element tuple @status: Tested method @since: version 0.1 """ if type(edges) != list: raise GraphParameterError('Edges must be a \ list of tuples') from Set import Set from Matrix import Matrix vertices = list(Set([x[0] for x in edges] + [x[1] for x in edges])) adj = Matrix(len(vertices)) adj = adj.m for e in edges: row = vertices.index(e[0]) col = vertices.index(e[1]) # fill values into lower triangular matrix adj[row][col] = adj[row][col] + 1 adj.insert(0, vertices) self.makeGraphFromAdjacency(adj)
def generate_Tasks(self): tasks=Set([]) for i in range(len(self.targets)): id_a=self.task_ids[i] target_a=self.targets[i] tasks.add(Task(id_a,target_a)) self.tasks=tasks
def testPot(self): newSet = Set([1, 2, 3, 4, 1, 8, 3, 7]) self.assertTrue((newSet.pot() == [ [], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3], [4], [1, 4], [2, 4], [1, 2, 4], [3, 4], [1, 3, 4], [2, 3, 4], [1, 2, 3, 4], [8], [1, 8], [2, 8], [1, 2, 8], [3, 8], [1, 3, 8], [2, 3, 8], [1, 2, 3, 8], [4, 8], [1, 4, 8], [2, 4, 8], [1, 2, 4, 8], [3, 4, 8], [1, 3, 4, 8], [2, 3, 4, 8], [1, 2, 3, 4, 8], [7], [1, 7], [2, 7], [1, 2, 7], [3, 7], [1, 3, 7], [2, 3, 7], [1, 2, 3, 7], [4, 7], [1, 4, 7], [2, 4, 7], [1, 2, 4, 7], [3, 4, 7], [1, 3, 4, 7], [2, 3, 4, 7], [1, 2, 3, 4, 7], [8, 7], [1, 8, 7], [2, 8, 7], [1, 2, 8, 7], [3, 8, 7], [1, 3, 8, 7], [2, 3, 8, 7], [1, 2, 3, 8, 7], [4, 8, 7], [1, 4, 8, 7], [2, 4, 8, 7], [1, 2, 4, 8, 7], [3, 4, 8, 7], [1, 3, 4, 8, 7], [2, 3, 4, 8, 7], [1, 2, 3, 4, 8, 7] ]) and len(newSet.pot()) == 2**len(newSet.diff(Set([]))))
def test_equals_with_nonequal_sets(self): test = Set([]) length = len(self.test_set.to_seq()) for i in range(0, length): # some arbitrary values not equal to those in test_set test.add(i * -1) assert not self.test_set.equals(test)
def test_set_member(): memberset = Set([-0, 0, 0, 0, 0, 1]) assert memberset.member(-0), "Test Case Failed" assert memberset.member(+0), "Test Case Failed" assert memberset.member(1), "Test Case Failed" assert memberset.member(-1) is False, "Test Case Failed"
def runalgorithm(self): for i in range(0, len(graph)): s = Set() s.vertices.append(i) self.listset.append(s) for i in range(0, len(graph)): for j in range(i, len(graph)): if i != j and graph[i][j] > 0: e = Edge() e.v1 = i e.v2 = j e.weight = graph[i][j] self.listedges.append(e) self.listedges.sort() while len(self.listedges) > 0 and not self.not_found_mst(): removed_edge = self.listedges[0] self.listedges.remove(removed_edge) v1 = removed_edge.v1 v2 = removed_edge.v2 s1 = self.find_set(v1) s2 = self.find_set(v2) if not self.is_same_set(s1, s2): self.union(s1, s2) self.MSTEdges.append(removed_edge) print("MST Found") self.print_mst_result()
def startSet(self): self.currSet = Set() while (not self.currSet.complete): if self.exit: return currMap = None print("Waiting to detect game...") while (currMap is None): currMap = Map.checkMap(maps=self.maps, state=self.updateState()) if self.exit: return currGame = Game(currMap, self.scoreboardKey) print("Detected: " + currGame.map.name) while (not currGame.update(self.updateState())): if self.exit: return currWinner = None endTime = time.time() while (currWinner is None): currWinner = WinCon.checkWinCon(self.updateState()) if self.exit: return currGame.endGame(currWinner[0], currWinner[1], endTime) self.currSet.addGame(currGame) self.currSet.checkWinner() if (self.stats): self.currSet.toCSV() if (self.logging): self.currSet.log()
def generate_Hazards(self): hazards=Set([]) for i in range(len(self.y_0)): id_h=self.hazard_ids[i] y_0_h=self.y_0[i] p_f_h=self.p_f[i] hazards.add(Hazard(id_h,y_0_h,p_f_h)) self.hazards=hazards
def generate_Robots(self): robots=Set([]) for i in range(len(self.robot_positions)): id_r=self.robot_ids[i] x_0_r=self.robot_positions[i] linestyle_r=self.robot_linestyles[i] robots.add(Robot(id_r,x_0_r,self.goal,linestyle_r)) self.robots=robots
def test_set_add(): addset = Set([0, 0, -2, -5, 28392, 9, 2, 2]) addset.add(0) addset.add(1) assert addset.member(1), "Test Case Failed" assert addset.to_seq() == [0, -2, -5, 28392, 9, 2, 1], "Test Case Failed" assert addset.size() == 7, "Test Case Failed"
def addDataSet(self, setId): if (setId in self.dataSetIds): return (self.dataSetIds[setId]) domain = self.session.getDomain(self.observationDomainId) dataSet = Set.createDataSet(domain, setId) self.dataSets.append(dataSet) self.allSets.append(dataSet) self.dataSetIds[setId] = dataSet return (dataSet)
def test_set_add(self): car_parts = Set() car_parts.add("Smuffler") assert (car_parts) assert (len(car_parts.get_items())) is 1 car_parts.add("Noodler") assert (len(car_parts.get_items())) is 2 car_parts.add("Smuffler") assert (len(car_parts.get_items())) is 2 assert ("Noodler" in car_parts.get_items()) assert ("Smuffler" in car_parts.get_items()) computer_parts = Set(['Ycombinator', 'North Shore', 'East Bridge']) assert (len(computer_parts.get_items())) is 3 assert (computer_parts.size) is 3 assert (computer_parts.contains("North Shore")) car_parts.add(['one']) assert (car_parts.size) is 3
def get_gamma_G(self, K): robot_ids = Set([e.id for e in self.robots]) task_ids = Set([e.id for e in self.tasks]) V = Set.descartes_product(robot_ids, task_ids) V_K = Set([Set(e) for e in itertools.combinations(V, K)]) print("...Calculating gamma_G...") gamma_G = float('inf') N = len(self.history) * len(V_K) progress_bar = ProgressBar(N) instrument = Instrument() instrument.start() k = 0 for t in range(len(self.history)): S_t = Allocation(self.history[0:t]) for Omega in V_K: progress_bar.progress(k) k = k + 1 lhs = 0 for omega in Omega.setminus(Set(S_t)): lhs = lhs + S_t.get_derivative(Set([omega])) rhs = S_t.get_derivative(Omega) frac = rhs / lhs if frac < gamma_G and rhs != 0 and lhs != 0: gamma_G = frac progress_bar.progress(N, 'Finished!\n') calculation_time = instrument.stop() print("Calculation time [s]:", calculation_time) print("Finished calculating gamma_G!\n") return gamma_G
def __init__(self, cache_size, set_size, tag_amount, methodology): self.cache_size = cache_size self.set_size = set_size self.tag_amount = tag_amount self.cache_map = {} self.num_of_hits = ZERO_HITS self.methodology = methodology for x in range(cache_size): self.cache_map[x] = Set(set_size, x, methodology)
def test_set_remove(self): car_parts = Set() car_parts.add("Smuffler") car_parts.add("Turbidity Turbine") car_parts.add("Rolfoganger") car_parts.remove("Rolfoganger") assert (len(car_parts.get_items())) is 2 with self.assertRaises(KeyError): car_parts.remove("Fluffykins")
def test_set_size(): sizeset = Set([]) assert sizeset.size() == 0, "Test Case Failed" sizeset.add(100) sizeset.add(100) assert sizeset.size() == 1, "Test Case Failed" sizeset.rm(100) assert sizeset.size() == 0, "Test Case Failed"
def readFile(): # open notes.txt file with open("res/notes.txt", "r") as f: days = [] skip_first = False list_ex = [] line = f.readline().rstrip('\n') while 1: if 'new' in line: print('\033[94m' + "New day!" + "\033[0m") if skip_first is True: day = Day(line, list_ex) days.append(day) skip_first = True line = f.readline().rstrip('\n') # ex name if ':' in line: reps = 0 ex_time = line.split(":") ex = Exercise(ex_time[0], ex_time[1]) while 1: line = f.readline().rstrip('\n') # Set if ('[' in line) & (']' in line): reps = reps + 1 set_info = re.split('x |- ', line) slice_object = slice(4, -1) # Set has no weight if len(set_info) == 2: sets = Set(int(set_info[0][slice_object]), int(set_info[1])) else: sets = Set(int(set_info[0][slice_object]), int(set_info[2]), int(set_info[1])) ex.addSet(sets) # save exercise else: ex.setNReps(reps) list_ex.append(ex) break if line == '': break f.close() return days
class MT_try1(InstanceMacro ): # deprecated MT_try1 as of 070208, since MT_try2 works better # WARNING: compare to ToggleShow - lots of copied code -- also compare to the later _try2 version, which copies from this # args node = Arg(Node) #### type? the actual arg will be a node instance... # state refs open = State(bool, False) # other formulae # Note, + means openable (ie closed), - means closable (ie open) -- this is the Windows convention (I guess; not sure about Linux) # and until now I had them reversed. This is defined in two files and in more than one place in one of them. [bruce 070123] open_icon = Overlay(Rect(0.4), TextRect('-', 1, 1)) closed_icon = Overlay(Rect(0.4), TextRect('+', 1, 1)) openclose_spacer = Spacer(0.4) #e or Invisible(open_icon); otoh that's no simpler, since open_icon & closed_icon have to be same size anyway # the openclose icon, when open or close is visible (i.e. for openable nodes) openclose_visible = Highlightable(If(open, open_icon, closed_icon), on_press=Set(open, not_Expr(open))) openclose_slot = If(call_Expr(node_openable, node), openclose_visible, openclose_spacer) icon = Rect( 0.4, 0.4, green ) ##stub; btw, would be easy to make color show hiddenness or type, bfr real icons work ###k is this a shared instance (multiply drawn)?? any issue re highlighting? need to "instantiate again"? ##e Better, this ref should not instantiate, only eval, once we comprehensively fix instantiation semantics. # wait, why did I think "multiply drawn"? it's not. nevermind. ##e selection behavior too label = TextRect( call_Expr(node_name, node) ) ###e will need revision to Node or proxy for it, so node.name is usage/mod-tracked ##e selection behavior too -- #e probably not in these items but in the surrounding Row (incl invis bg? maybe not, in case model appears behind it!) ##e italic for disabled nodes ##e support cmenu _value = SimpleRow( openclose_slot, SimpleColumn( SimpleRow(CenterY(icon), CenterY(label)), #070124 added CenterY, hoping to improve text pixel alignment (after drawfont2 improvements) -- doesn't work If( open, MT_kids_try1( call_Expr(node_kids, node) ), ###e implem or find kids... needs usage/mod tracking Spacer( 0 ) ###BUG that None doesn't work here: see comment in ToggleShow.py ))) pass # end of class MT_try1
def contains(self, element): if element > self.capacity: return false else: return Set.contains(self, element)
def add(self, element): self.checkIndex(element) Set.add(self, element) print element, "successfully added."
def delete(self, element): self.checkIndex(element) Set.delete(self, element) print element, "successfully removed."
def __init__(self, *corpora): # No inverses and closures in the test set Set.__init__(self, False, False, False, *corpora) self.relations_optimized = []
def __init__(self, inverse=False, closure=False, best_settings=True, *corpora): Set.__init__(self, inverse, closure, best_settings, *corpora)