'Python Lo Shu Magic
I am trying to test a Lo Shu Magic Square function, but I am running into a few problems. One of the problems is that I am getting an error message that says TypeError: 'int' object is not iterable, but I do not see what I am doing wrong. Secondly is there a better more efficient way to write this code to check if the lo_shu_square variable is a Lo Shu Magic Square? I am a newb to Python but it just seems inefficient.
ROWS = 3
COLUMNS = 3
def magic():
lo_shu_square = [[8, 1, 6],[3, 5, 7],[4, 9, 2]]
for r in range (ROWS):
for c in range (COLUMNS):
if sum(r) == sum (lo_shu_square[c][c] for c in range(COLUMNS)):
if sum(r)== sum(r[c] for r in lo_shu_square):
answer_output = str('a Lo Shu Magic Square')
else:
answer_output = str('not a Lo Shu Magic Square')
print("The inputs are", answer_output)
magic()
The error message:
if sum(r) == sum (lo_shu_square[c][c] for c in range(COLUMNS)):
TypeError: 'int' object is not iterable
Solution 1:[1]
Thanks @Arman! It was a simple fix.
COLUMNS = 3
def magic():
lo_shu_square = [[8, 1, 6],[3, 5, 7],[4, 9, 2]]
for r in lo_shu_square:
for c in range (COLUMNS):
if sum(r) == sum (lo_shu_square[c][c] for c in range(COLUMNS)):
if sum(r)== sum(r[c] for r in lo_shu_square):
answer_output = str('a Lo Shu Magic Square')
else:
answer_output = str('not a Lo Shu Magic Square')
print("The inputs are", answer_output)
magic()
Solution 2:[2]
#print out our list in the shape of a square
for row in Square:
print(row)
def LoShu(List2d):
if isinstance(List2d,list) and len(List2d)==3:
List1d-sum(List2d,[])
print(List1d)
if max(Listd) >=10 or min(List1d) <=0:
print("out of range, check if you list has a value greater than 9 or less than 0")
return False
if len(List1d) != len(set(List1d)):
print("check your list there are duplicate values")
return False
if len(List1d) != len(set(List1d)):
print("check your list there are duplicate values")
return False
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Part_Time_Nerd |
| Solution 2 | Wojuola Ayotola |
