def parse_matrix(lines): if len(lines) <= 0: fatal_parse_error(f'Zero length matrix.') row0 = parse_row(lines[0]) n = len(row0) if len(lines) != n: fatal_parse_error(f'Expecting square matrix but the matrix given is {len(lines)} x {n}', line=0) matrix = [] for i, line in lines: row = parse_row((i, line)) if any(map(lambda x: x != 0 and x != 1, row)): fatal_parse_error(f'Expecting binary matrix.', line=line) matrix.append(row) g = SimpleGraph(n) for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == 1: g.connect(i, j) return g
def parse_adj_list(lines): V = None try: V = int(lines[0][1]) except: fatal_parse_error(f'Failed to parse number of nodes from {lines[0][1]}', line=0) g = SimpleGraph(V) for line_number, line in lines[1:]: src_dist_strings = line.split("-") if "-" not in line or len(src_dist_strings) != 2: fatal_parse_error(f"Couldn't parse line: {line}, expecting format: source_node - dest1, dest2, ...", line=line_number) src_string = src_dist_strings[0] dst_string = src_dist_strings[1] src = None dests = None try: src = int(src_string) except: fatal_parse_error(f"Non-integer source node: {src_string}", line=line_number) try: dests = list(map(int, dst_string.split(","))) except: fatal_parse_error(f"Non-integer(s) found in destination nodes: {dst_string}", line=line_number) for dest in dests: g.connect(src, dest) return g
def example1(): g = SimpleGraph(4) g.connect(0, 1) g.connect(0, 2) g.connect(1, 2) g.connect(2, 3) print(fleury_algorithm(g))
def example3(): g = SimpleGraph(5) g.connect(1, 0) g.connect(0, 2) g.connect(2, 1) g.connect(0, 3) g.connect(3, 4) g.connect(3, 2) g.connect(3, 1) g.connect(2, 4) print(fleury_algorithm(g))
def example2(): g = SimpleGraph(5) g.connect(0, 1) g.connect(1, 2) g.connect(2, 0) print(fleury_algorithm(g))