4. An x matrix that is filled wit tmbers 1,2,32 is a magic square if the sum of
ID: 3699397 • Letter: 4
Question
4. An x matrix that is filled wit tmbers 1,2,32 is a magic square if the sum of the elements in each row, in each column, and in the two diagonals is the same value. Write a program that reads in 16 values from a file containing each row of 4 values in each line, and tests whether they form a magic square when put into a 4 x 4 table as a list of lists. You need to test two features: (a) Does each of the numbers 1,2,... , 16 occur in the the file? (b) When the numbers are put into a square, are the sums of the rows, columns and diagonals equal to each other? 5. Create a python functions that rotates the elements of a list by one position Consider a function rotate(a list, direction) that takes as arguments the ist to rotate, and the direction (left or right) of rotation. Rotate the list in place.Explanation / Answer
# first_question answer
fname = open('data.txt','r') #open file and read
line = fname.readline()
a=[]
diagonal1_sum=diagonal2_sum=0
i = 0
allow = True
x=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
while(line != ""):
a.append(map(int,line.split()))
for j in xrange(4): # to check the numbers btwn 1 to 16
if a[i][j] not in x:
allow = False
break
i=i+1
line = fname.readline()
if(allow==False):
break
if(allow):
row_sum = 0
is_same = 1
for i in xrange(4): # row_sum
if(i==0):
row_sum = sum(a[i])
else:
if(row_sum != sum(a[i])):
is_same = 0
break
if(is_same):
col_sum = 0
is_col_same = 1
for i in xrange(4): #col_sum
sum1 = 0
if(is_col_same):
for j in xrange(4):
sum1+=a[j][i]
if(i==0):
col_sum = sum1
else:
if(col_sum!=sum1 and col_sum!=row_sum):
is_col_same = 0
break
else:
break
if(is_col_same):
diag_sum = 0
for i in xrange(4): #diag_sum
diag_sum+=a[i][i]
if(diag_sum == col_sum and col_sum == row_sum):
print "GIVEN MATRIX IS MAGIC SQUARE"
else:
print "GIVEN MATRIX IS NOT MAGIC SQUARE"
else:
print "GIVEN MATRIX IS NOT MAGIC SQUARE"
else:
print "GIVEN MATRIX IS NOT MAGIC SQUARE"
else:
print "GIVEN MATRIX VALUE IS NOT BETWEEN 1 TO 16"
#second_ques answer
# function to rotate list left or right by one position
def rotate(a,direction):
b=[]
if(direction == "right"): #right_position
print "rotate right"
for j in range(0,len(a)):
b.append(a[len(a)-1])
for i in range(0,len(a)-1):
b.append(a[i])
print b
a=b
b=[]
elif(direction == "left"): #left_position
print "rotate left"
for j in range(0,len(a)):
for i in range(1,len(a)):
b.append(a[i])
b.append(a[0])
print b
a=b
b=[]
else:
print "INvalid Direction"
a=map(int,raw_input().split())
rotate(a,'right')
rotate(a,'left')
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.