def kruskal(g: Graph): """Kruskal's algorithm""" Edge = namedtuple("Edge", ["src", "dst", "weight"]) vertices = [set(v) for v in g.get_vertices()] edges = [Edge(e[0][0], e[0][1], e[1]) for e in g._edges.items()] edges.sort(key=lambda edge: edge.weight, reverse=True) min_span_tree = set() min_span_tree_size = len(vertices) - 1 while len(min_span_tree) < min_span_tree_size: candidate = edges.pop() for v_set in vertices: if candidate.src in v_set: src_set = v_set break # else: # src_set = set() for v_set in vertices: if candidate.dst in v_set: dst_set = v_set break # else: # dst_set = set() if src_set != dst_set: min_span_tree.add(candidate) src_set.update(dst_set) vertices.remove(dst_set) yield candidate
def read_file(filename: str) -> Graph: """Build a graph from the file""" graph = Graph() combo: dict = {} with open(filename, "r") as file: content = file.readlines() for i in content[1:]: val = i.strip().split("|") if val[0] not in combo: combo[val[0]] = [] combo[val[0]].append(val[1]) for movie in combo: for actor in combo[movie]: for loc in range(len(combo[movie])): if actor != combo[movie][loc]: graph.add_edge(actor, combo[movie][loc], 1) return graph
def read_file(filename): """Build a graph from the file""" kb_graph = Graph() old_movie = "" first_movie = True v_list = [] file_read = open(filename, "r") first_line = True for line in file_read: if first_line: first_line = False else: line2 = line.strip() act_list = line2.split("|") movie = act_list[0] actor = act_list[1] if first_movie: old_movie = movie first_movie = False if movie != old_movie: for actor1 in v_list: for actor2 in v_list: if actor1 != actor2: kb_graph.add_edge(actor1, actor2, movie) v_list = [] old_movie = movie v_list.append(actor) else: v_list.append(actor) for actor1 in v_list: # Needed for the last movie to ensure that edges are added for actor2 in v_list: if actor1 != actor2: kb_graph.add_edge(actor1, actor2, movie) return kb_graph
def buildGraph(wordFile): d = {} g = Graph() wfile = open(wordFile, 'r') # create buckets of words that differ by one letter for line in wfile: word = line[:-1] for i in range(len(word)): bucket = word[:i] + '_' + word[i + 1:] addBucket(d, bucket, word) ### Ajout des distances de 2 lettres word_remain = word[i + 1:] for j in range(len(word_remain)): bucket = word[:i] + '_' + word_remain[:j] + '_' + word_remain[ j + 1:] # add vertices and edges for words in the same bucket for bucket in d.keys(): for word1 in d[bucket]: for word2 in d[bucket]: if word1 != word2: g.add_edge(word1, word2) return g
def find_max_kbn_actors(graph: Graph) -> List[str]: """Find actor(s) with the highest KBN value""" key: list = [] val: list = [] for i in graph.get_vertices(): if len(key) == 0: key.append(i) val.append(traverse(graph, "Kevin Bacon", i)) else: trav = traverse(graph, "Kevin Bacon", i) if sys.maxsize > trav > val[-1]: key.clear() val.clear() key.append(i) val.append(traverse(graph, "Kevin Bacon", i)) if trav == val[-1] and trav < sys.maxsize and i not in key: key.append(i) val.append(traverse(graph, "Kevin Bacon", i)) return key
async def _calculate_symbol_route(self, symbol: str): ''' 查找symbol的跨市场价格计算路径 :param symbol : 依据交易对 :return: ''' symbols_result = await (asyncio.create_task if sys.version >= '3.7' else asyncio.ensure_future)(self.symbols()) if symbols_result['errno'] == 0: A_symbols = [ A_symbol['symbol'] for A_symbol in symbols_result['result'] ] # 货币对Graph currency_pairs = Graph() # 建立无向图Graph for A_symbol in A_symbols: base, quote = A_symbol.split('-') currency_pairs.add_edge(base, quote) currency_pairs.add_edge(quote, base) c1, c2 = symbol.split('-') start = currency_pairs.get_vertex(c1) end = currency_pairs.get_vertex(c2) # BFS路径 start.distance = 0 start.previous = None vert_queue = [start] while vert_queue: current_vert = vert_queue.pop(0) for neigh in current_vert.get_neighbors(): if neigh.color == "white": neigh.color = "gray" neigh.distance = current_vert.distance + 1 neigh.previous = current_vert vert_queue.append(neigh) current_vert.color = "black" if current_vert.get_key() == c2: route = [] while bool(current_vert.previous): route.append( f'{current_vert.get_key()}-{current_vert.previous.get_key()}' if f'{current_vert.get_key()}-{current_vert.previous.get_key()}' in A_symbols else f'{current_vert.previous.get_key()}-{current_vert.get_key()}' ) current_vert = current_vert.previous return route[::-1]
def buildGraphAuteur(rep_texts, mode): if os.path.isabs(rep_texts): rep = rep_texts else: rep = os.path.join(cwd, rep_texts) rep = os.path.normpath(rep) # print("path : ", rep) textes = os.listdir(rep) first = 0 graphe = Graph() for text in textes: if first is 0: graphe = buildGraph(rep + "\\" + text, mode) else: graphe = additionnerGraph(graphe, rep + "\\" + text, mode) return graphe
def main(): """This is the main function""" g = Graph() g.add_edge("A", "B", 7) g.add_edge("A", "D", 5) g.add_edge("B", "A", 7) g.add_edge("B", "C", 8) g.add_edge("B", "D", 9) g.add_edge("B", "E", 7) g.add_edge("C", "B", 8) g.add_edge("C", "E", 5) g.add_edge("D", "A", 5) g.add_edge("D", "B", 9) g.add_edge("D", "E", 15) g.add_edge("D", "F", 6) g.add_edge("E", "B", 7) g.add_edge("E", "C", 5) g.add_edge("E", "D", 15) g.add_edge("E", "F", 8) g.add_edge("E", "G", 9) g.add_edge("F", "D", 6) g.add_edge("F", "E", 8) g.add_edge("F", "G", 11) g.add_edge("G", "E", 9) g.add_edge("G", "F", 11) min_span_tree = kruskal(g) min_span_tree_weight = 0 print("Edges of the minimum spanning tree") for edge in min_span_tree: print(edge) min_span_tree_weight += edge.weight print(f"Total weight of the tree is {min_span_tree_weight}")
def set_up(): '''Setting up''' graph = Graph() return graph
def buildGraph(wordFile, mode): g = Graph() wfile = open(wordFile, 'r', encoding="utf-8") last = "" firstWord = 0 lastWord = "" lastBigram = "" #Traverse le fichier ligne par ligne for line in wfile: ligne = line[:-1] words = re.split(r'[_;,.:;\[\]?!\"\'\s\t()\-]\s*', ligne.lower()) #Traverse la liste de words mot par mot for word in words: if mode is 1: #unigramme if len(word) > 2: if g.get_vertex(word) is None: g.set_vertex(word) g.get_vertex(word).set_discovery_time(1) else: frequence = g.get_vertex(word).get_discovery_time() g.get_vertex(word).set_discovery_time(frequence + 1) if firstWord == 0: firstWord = 1 elif last != word: g.add_edge(last, word) last = word elif mode is 2: #bigramme if len(word) > 2: if firstWord == 0: lastWord = word + " " firstWord = 1 else: bigram = lastWord + word if g.get_vertex(bigram) is None: g.set_vertex(bigram) g.get_vertex(bigram).set_discovery_time(1) else: frequence = g.get_vertex( bigram).get_discovery_time() g.get_vertex(bigram).set_discovery_time(frequence + 1) g.add_edge(lastBigram, bigram) lastBigram = bigram lastWord = word + " " return g
def set_up(): """Setting up""" graph = Graph() return graph