| 24 | 24 | |
| 25 | 25 | class Graph: |
| 26 | 26 | def __init__(self, data: list | None = None): |
| 27 | | pass |
| 27 | """ |
| 28 | Initialize a Graph with optional data. |
| 29 | |
| 30 | Parameters: |
| 31 | data (list | None): A list of tuples describing the graph. Each tuple should be of the form: |
| 32 | - (ATTR, key, value) for graph attributes |
| 33 | - (NODE, name, attrs) for nodes |
| 34 | - (EDGE, src, dst, attrs) for edges |
| 35 | |
| 36 | Raises: |
| 37 | TypeError: If data is not a list or if any tuple is malformed. |
| 38 | ValueError: If an unknown item type is encountered. |
| 39 | """ |
| 40 | # Edge Case: Data is None |
| 41 | if data is None: |
| 42 | data = [] |
| 43 | |
| 44 | # Edge Case: Data is not a list |
| 45 | if not isinstance(data, list): |
| 46 | raise TypeError("Graph data malformed") |
| 47 | |
| 48 | self.nodes = [] |
| 49 | self.edges = [] |
| 50 | self.attrs = {} |
| 51 | |
| 52 | # Edge Case: Process each item in the data list |
| 53 | for item in data: |
| 54 | # Edge Case: Item is not a tuple |
| 55 | if not isinstance(item, tuple): |
| 56 | raise TypeError("Graph item malformed") |
| 57 | |
| 58 | # Edge Case: Item is empty |
| 59 | if len(item) == 0: |
| 60 | raise TypeError("Graph item malformed") |
| 61 | |
| 62 | item_type = item[0] |
| 63 | |
| 64 | # Edge Case: ATTR item with incorrect number of elements |
| 65 | if item_type == ATTR: |
| 66 | if len(item) != 3: |
| 67 | raise TypeError("Graph item malformed") |
| 68 | self.attrs[item[1]] = item[2] |
| 69 | |
| 70 | # Edge Case: NODE item with incorrect number of elements |
| 71 | elif item_type == NODE: |
| 72 | if len(item) != 3: |
| 73 | raise TypeError("Graph item malformed") |
| 74 | # Edge Case: Node attributes is not a dict |
| 75 | if not isinstance(item[2], dict): |
| 76 | raise TypeError("Node attributes must be a dictionary") |
| 77 | self.nodes.append(Node(item[1], item[2])) |
| 78 | |
| 79 | # Edge Case: EDGE item with incorrect number of elements |
| 80 | elif item_type == EDGE: |
| 81 | if len(item) != 4: |
| 82 | raise TypeError("Graph item malformed") |
| 83 | # Edge Case: Edge attributes is not a dict |
| 84 | if not isinstance(item[3], dict): |
| 85 | raise TypeError("Edge attributes must be a dictionary") |
| 86 | self.edges.append(Edge(item[1], item[2], item[3])) |
| 87 | |
| 88 | # Edge Case: Unknown item type |
| 89 | else: |
| 90 | raise ValueError("Unknown item") |
| 91 | |
| 92 | # Handled Edge Cases: Data is None, Data is not a list, Item is not a tuple, Item is empty, |
| 93 | # ATTR item with incorrect number of elements, NODE item with incorrect number of elements, |
| 94 | # Node attributes is not a dict, EDGE item with incorrect number of elements, |
| 95 | # Edge attributes is not a dict, Unknown item type |