Lecture Notes on 14 Apr 2017
Read Chapter 11: Multidimensional Lists
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
def main():
b = [[4, 9, 2], [3, 5, 7], [8, 1, 6]]
print (b[2][1])
# sum all elements
sum_n = 0
for row in b:
for col in row:
sum_n += col
print (sum_n)
# sum all elements
sum_n = 0
for i in range (len(b)):
for j in range (len(b[i])):
sum_n += b[i][j]
print (sum_n)
# find the max in the 2D list
max_n = b[0][0]
for i in range (len(b)):
for j in range (len(b[i])):
if (b[i][j] > max_n):
max_n = b[i][j]
print (max_n)
# make a deep copy of a 2D list
c = []
for i in range (len(b)):
d = []
for j in range (len(b[i])):
d.append (b[i][j])
c.append (d)
# transpose a 2D list
c = []
for j in range (len(b[0])):
d = []
for i in range (len(b)):
d.append (b[i][j])
c.append (d)
print (c)
# add two 2-D lists
d = []
for i in range (len(b)):
e = []
for j in range (len (b[i])):
f = b[i][j] + c[i][j]
e.append (f)
d.append (e)
print (d)
main()