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