| 23 | 23 | |
| 24 | 24 | |
| 25 | 25 | class Graph: |
| 26 | """ |
| 27 | A class representing a graph data structure. |
| 28 | |
| 29 | The graph can be initialized with data that describes nodes, edges, and attributes. |
| 30 | """ |
| 31 | |
| 26 | 32 | def __init__(self, data: list | None = None): |
| 27 | | pass |
| 33 | """ |
| 34 | Initialize a Graph object. |
| 35 | |
| 36 | Args: |
| 37 | data: A list of tuples describing the graph. Each tuple represents either |
| 38 | an attribute, a node, or an edge. |
| 39 | |
| 40 | Raises: |
| 41 | TypeError: If data is not a list or if any graph item is malformed. |
| 42 | ValueError: If an unknown item type is encountered. |
| 43 | """ |
| 44 | # Edge Case: Handle None input |
| 45 | if data is None: |
| 46 | data = [] |
| 47 | |
| 48 | # Edge Case: Graph data is not a list |
| 49 | if not isinstance(data, list): |
| 50 | raise TypeError("Graph data malformed") |
| 51 | |
| 52 | self.nodes = [] |
| 53 | self.edges = [] |
| 54 | self.attrs = {} |
| 55 | |
| 56 | # Process each item in the data list |
| 57 | for item in data: |
| 58 | # Edge Case: Graph item is not a tuple |
| 59 | if not isinstance(item, tuple): |
| 60 | raise TypeError("Graph item malformed") |
| 61 | |
| 62 | # Edge Case: Graph item is empty |
| 63 | if len(item) == 0: |
| 64 | raise TypeError("Graph item malformed") |
| 65 | |
| 66 | item_type = item[0] |
| 67 | |
| 68 | # Edge Case: Unknown item type |
| 69 | if item_type not in [NODE, EDGE, ATTR]: |
| 70 | raise ValueError("Unknown item") |
| 71 | |
| 72 | # Process attribute |
| 73 | if item_type == ATTR: |
| 74 | # Edge Case: Attribute tuple has wrong number of elements |
| 75 | if len(item) != 3: |
| 76 | raise TypeError("Graph item malformed") |
| 77 | |
| 78 | _, key, value = item |
| 79 | self.attrs[key] = value |
| 80 | |
| 81 | # Process node |
| 82 | elif item_type == NODE: |
| 83 | # Edge Case: Node tuple has wrong number of elements |
| 84 | if len(item) != 3: |
| 85 | raise TypeError("Graph item malformed") |
| 86 | |
| 87 | _, name, attrs = item |
| 88 | # Edge Case: Node attributes is not a dict |
| 89 | if not isinstance(attrs, dict): |
| 90 | raise TypeError("Graph item malformed") |
| 91 | |
| 92 | self.nodes.append(Node(name, attrs)) |
| 93 | |
| 94 | # Process edge |
| 95 | elif item_type == EDGE: |
| 96 | # Edge Case: Edge tuple has wrong number of elements |
| 97 | if len(item) != 4: |
| 98 | raise TypeError("Graph item malformed") |
| 99 | |
| 100 | _, src, dst, attrs = item |
| 101 | # Edge Case: Edge attributes is not a dict |
| 102 | if not isinstance(attrs, dict): |
| 103 | raise TypeError("Graph item malformed") |
| 104 | |
| 105 | self.edges.append(Edge(src, dst, attrs)) |
| 106 | |
| 107 | # Handled Edge Cases: None input, data not a list, item not a tuple, empty item, unknown item type, |
| 108 | # attribute tuple wrong length, node tuple wrong length, node attrs not dict, |
| 109 | # edge tuple wrong length, edge attrs not dict |