Working with arrays and matrices is easiest with numpy. So if this is an option for you, this is how you could go about checking the diagonal of your table
:
import numpy as np
table = [['1', ' ', '1'],
[' ', '1', ' '],
['1', ' ', '1']]
nptable = np.array(table)
# now we can simply get the unique values in the diagonal:
diag_values = np.unique(nptable.diagonal())
If you have a single value in diag_values
then you know that all diagonal values are equal.
Now if you want to also check the other diagonal, you can use np.fliplr and redo the same:
diag_values = np.unique(np.fliplr(nptable).diagonal())
If you want to stick to lists then you could loop over the rows of table
until you encounter a change if the value of the diagonal:
diag_val = table[0][0]
for i, row in enumerate(table):
if row[i] != diag_val: # row[i] is basically table[i][i]
print(f'diagonal value changes in row {i=}.')
break # we stop the loop as we encoutered a change
Checking the other diagonal is just as easy, simply access the element -i-1
instead of element i
in each row:
diag_val = table[0][-1]
for i, row in enumerate(table):
if row[-i-1] != diag_val:
print(f'diagonal value changes in row {i=}.')
break # we stop the loop as we encoutered a change
Or, if the value in both cases should be the same, say diag_val='1'
, you can do it in one go:
diag_val = '1'
for i, row in enumerate(table):
if row[i] != diag_val or row[-i-1] != diag_val:
print(f'diagonal value changes in row {i=}.')
break # we stop the loop as we encoutered a change
Hope that helped!