Reputation: 333
I am making a python program to check if the given values represent magic square
import math
r1=[8,1,6]
r2=[3,5,7]
r3=[4,9,2]
c1=zip(r1[:1],r2[:1],r3[:1])
c1= (list(c1))
c2=zip(r1[1:2],r2[1:2],r3[1:2])
c2=(list(c2))
c3=zip(r1[2:3],r2[2:3],r3[2:3])
c3= (list(c3))
print (c1,c2,c3)
print(type(c1),type(c2),type(c3))
t1=math.fsum(r1)
t2=math.fsum(r2)
t3=math.fsum(r3)
t4=math.fsum(c1)
t5=math.fsum(c2)
t6=math.fsum(c3)
print(t1,t2,t3,t4,t5,t6)
if(t1==t2==t3==t4==t5==t6):
print ("yes")
else:
print("no")
But in the line t4=math.fsum(c1)
It gives type error though the type of t4 shows list only.
Upvotes: -1
Views: 49
Reputation: 12005
Store all the rows in one list as a list of list. It would be easier to check if the array represented by that list of list is a magic square
>>> r1=[8,1,6]
>>> r2=[3,5,7]
>>> r3=[4,9,2]
>>> arr = [r1, r2, r3]
>>> row_sum = set(map(sum, arr))
>>> col_sum = set(map(sum, zip(*arr)))
>>> if len(row_sum) == 1 and row_sum == col_sum:
print ('Magic square')
Upvotes: 0
Reputation: 2428
In c1
variable you have list of tuple: [(8, 3, 4)]
. You can construct your c1
(and others) in this way: c1 = [r1[0], r2[0], r3[0]]
.
But I recommend you to store a magic square in one variable like: magic = [[8, 1, 6], [3, 5, 7], [4, 9, 2]]
. Now you can get sum of i-th row's elements as sum(magic[i])
and for columns try list comprehensions:
sum([magic[i][j] for i in range(3)])
where j - number of column.
Upvotes: 1
Reputation: 3816
As is already suggested the zip returns a tuple and making it a list only puts the same tuple in the list the following code however will do what you want
import math
r1=[8,1,6]
r2=[3,5,7]
r3=[4,9,2]
c1=r1[:1]+r2[:1]+r3[:1]
#c1= list(c1)
c2=r1[1:2]+r2[1:2]+r3[1:2]
#c2=(list(c2))
c3=r1[2:3]+r2[2:3]+r3[2:3]
#c3= (list(c3))
print (c1,c2,c3)
print(type(c1),type(c2),type(c3))
t1=math.fsum(r1)
t2=math.fsum(r2)
t3=math.fsum(r3)
t4=math.fsum(c1)
t5=math.fsum(c2)
t6=math.fsum(c3)
print(t1,t2,t3,t4,t5,t6)
if(t1==t2==t3==t4==t5==t6):
print ("yes")
else:
print("no")
The output will be:
[8, 3, 4] [1, 5, 9] [6, 7, 2]
<class 'list'> <class 'list'> <class 'list'>
15.0 15.0 15.0 15.0 15.0 15.0
yes
Upvotes: 0