6

How do you write a Python code to check if the operation āˆ— on the set {0,1,..,nāˆ’1} defined by a Cayley table is associative or not.

My attempted code is:

def is_associative_cayley_table(table):
    if not is_cayley_table(table):
        return False

    for i in range (0,len(table)):
        for j in range (0,len(table)):
            for k in range (0,len(table)):
                if (table[table[i][j])][k])==(table[i][(table[j][k])]):
                   print("Okay")
                else
                   return False
Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63
Scream98
  • 63
  • 1
  • 4

2 Answers2

4

Instead of printing "Okay" n^3 times, you might just want to return the bool.

def is_associative_cayley_table(table):
    if not is_cayley_table(table):
        return False

    for i in range (0,len(table)):
        for j in range (0,len(table)):
            for k in range (0,len(table)):
                if (table[table[i][j])][k])!=(table[i][(table[j][k])]):
                   return False
    return True

Also, there is no algorithm to check the associativity of a set, yet.
You have to use brute-force.

The best you can do is use Light's Associativity Test, which "does not improve the worst case runtime of O(n^3). It just simplifies the task in some cases."

frederick99
  • 1,033
  • 11
  • 18
0

Or with generator comprehension in python:

def is_associative(table, n):
    return all(table[x][table[a][y]] == table[table[x][a]][y] \
           for a in np.arange(n) for x in range(n) for y in range(n))

# calay table for ({0,1,...,n-1}, +n), addition modulo n, which is an Abelian group

n = 4
calay_table = np.zeros((n, n), dtype=int)
calay_table[0] = np.arange(n)
for i in range(1, n):
    calay_table[i] = np.roll(calay_table[i-1],-1)

print(calay_table)
# [[0 1 2 3]
# [1 2 3 0]
# [2 3 0 1]
# [3 0 1 2]]

is_associative(calay_table, n)
# True

We could have clever implementations of Light's Associativity Test.

Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63