File size: 1,371 Bytes
bbba039
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec0de3f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import json

from langchain_core.tools import tool


@tool(parse_docstring=True)
def check_commutativity(table_data: list[list[str]]) -> str:
    """
    Checks the commutativity of a given table represented as a 2D list.

    Args:
        table_data (list[list[str]]): A 2D list representing the table to check.
            Should not contain the header row, only the data rows.

    Returns:
        str: A JSON-formatted string containing:
            - "commutative" (bool): True if the table is commutative, False otherwise.
            - "non_commutative_pairs" (list[tuple[int, int]]): A list of tuples
              representing the indices of non-commutative pairs in the table.
              If the table is commutative, this list will be empty.
            If an error occurs during processing, the function returns an error message.
    """
    result = set()
    try:
        for i, row in enumerate(table_data):
            for j, _ in enumerate(row[:i]):
                if table_data[i][j] != table_data[j][i]:
                    result.add((i, j))
                    result.add((j, i))

        return json.dumps(
            {
                "commutative": len(result) == 0,
                "non_commutative_pairs": list(result),
            }
        )

    except Exception as e:
        return f"Error: {e}"


if __name__ == "__main__":
    pass