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