Lecture Notes on 17 Apr 2017
def is_magic (b):
# sum the first row
canon_sum = 0
for j in range (len(b[0]):
canon_sum += b[0][j]
# sum each row and compare with canon_sum
for i in range (len(b)):
sum_n = 0
for j in range (len(b[i])):
sum_n += b[i][j]
if (sum_n != canon_sum):
return False
# sum each column and compare with canon_sum
for j in range (len(b[0])):
sum_n = 0
for i in range (len (b)):
sum_n += b[i][j]
if (sum_n != canon_sum):
return False
# sum the diagonal elements going left to right
sum_lr = 0
for i in range (len(b)):
sum_lr += b[i][i]
if (sum_lr != canon_sum):
return False
# sum the diagonal elements going right to left
sum_rl = 0
for i in range (len(b)):
sum_rl += b[i][len(b) - 1 - i]
if (sum_rl != canon_sum):
return False
return True
def main():
b = [[4, 9, 2], [3, 5, 7], [8, 1, 6]]
print (is_magic (b))
main()
# go through a 2D list in groups of four elements
def main():
# open the file
in_file = open ("./grid.txt", "r")
# read the dimension of the grid
dim = in_file.readline()
dim = dim.strip()
dim = int(dim)
# create an empty grid
grid = []
# populate that grid
for i in range (dim):
line = in_file.readline()
line = line.strip()
row = line.split()
for j in range (dim):
row[j] = int (row[j])
grid.append (row)
# print the grid
# print (grid)
# read each row in blocks of four
for row in grid:
for i in range (dim - 3):
prod = 1
for j in range (i, i + 4):
prod = prod * row[j]
print(prod, end = " ")
print()
# read each column in blocks of four
for j in range (dim):
for i in range (dim - 3):
for k in range (i, i + 4):
print (grid[k][j], end = " ")
print (end = " ")
print ()
# go along all diagonals L to R in blocks of 4
for i in range (dim - 3):
for j in range (dim - 3):
for k in range (4):
print (grid[i + k][j + k], end = " ")
print (end = " ")
print ()
main()