79.9k views
2 votes
a magic square is a grid with 3 rows and 3 columns with the following properties: the grid contains every number from 1 to 9. the sum of each row, each column, and each diagonal all add up to the same number. this is an example of a magic square: 4 9 2 3 5 7 8 1 6 in python, you can simulate a 3x3 grid using a two-dimensional list. for example, the list corresponding to the grid above would be: [[4, 9, 2], [3, 5, 7], [8, 1, 6]] write a program that has a function that accepts a two-dimensional list as an argument and returns either true or false to indicate whether the list is a magic square. the program should test the function by calling it with the following two-dimensional lists as arguments and printing out the results each on a separate line: [[4, 9, 2], [3, 5, 7], [8, 1, 6]] [[2, 7, 6], [9, 5, 1], [4, 3, 8]] [[1, 2, 3], [4, 5, 6], [7, 8, 9]] [[4, 9, 2], [3, 5, 5], [8, 1, 6]]

User Cmm User
by
8.6k points

1 Answer

5 votes
def is_magic_square(lst):
# Check that the list has 3 rows and 3 columns
if len(lst) != 3 or len(lst[0]) != 3 or len(lst[1]) != 3 or len(lst[2]) != 3:
return False

# Compute the sum of the first row, and use it as the target sum for the magic square
target_sum = sum(lst[0])

# Check that all rows, columns, and diagonals have the same sum
if sum(lst[1]) != target_sum or sum(lst[2]) != target_sum:
return False
if lst[0][0] + lst[1][1] + lst[2][2] != target_sum:
return False
if lst[0][2] + lst[1][1] + lst[2][0] != target_sum:
return False
if lst[0][0] + lst[1][0] + lst[2][0] != target_sum:
return False
if lst[0][1] + lst[1][1] + lst[2][1] != target_sum:
return False
if lst[0][2] + lst[1][2] + lst[2][2] != target_sum:
return False

# All checks passed, so the list is a magic square
return True

# Test the function with the given examples
print(is_magic_square([[4, 9, 2], [3, 5, 7], [8, 1, 6]])) # True
print(is_magic_square([[2, 7, 6], [9, 5, 1], [4, 3, 8]])) # True
print(is_magic_square([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) # False
print(is_magic_square([[4, 9, 2], [3, 5, 5], [8, 1, 6]])) # False


The output should be:

True
True
False
False
User Andrey Chaschev
by
7.5k points