livepython.net

303. Python Program to Check a Magic Square

HardPhase 3 · Challenge

This one takes a few steps, but you know every tool it uses: split(), a list and for loops. Add up the rows, columns and diagonals of the first example on paper first.

Overview

A magic square is a grid of numbers where every line adds up to the same total. People have drawn them for thousands of years, and checking one is good practice with rows and columns.

Problem Statement

Yara found an old puzzle book and wants to check its answers. Read a 3 by 3 grid of whole numbers. The grid is a magic square when these 8 sums are all the same:

  • the sum of each of the 3 rows,
  • the sum of each of the 3 columns,
  • the sum of each of the 2 diagonals: top-left to bottom-right, and top-right to bottom-left.

Print Magic square if all 8 sums are the same, and Not a magic square if they are not. Print nothing else. Only the sums matter: the numbers do not have to be different.

Examples

Example 1. Input:

2 7 6
9 5 1
4 3 8

gives:

Magic square

Why: every row, every column and both diagonals add up to 15. For example, the first column is 2 + 9 + 4 = 15, and one diagonal is 2 + 5 + 8 = 15.

Example 2. Input:

1 2 3
4 5 6
7 8 9

gives:

Not a magic square

Why: the first row adds up to 6, but the second row adds up to 15. One different sum is enough.

Input

Three lines, one for each row from top to bottom. Each line has 3 whole numbers with one space between them. The numbers can be negative or 0. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.

Output

One line: Magic square or Not a magic square. The tests try 8 different inputs.

Try it first. The solution opens when you solve this question, or after 3 tries with Submit.

Finish this chapter firstChapter 12 · Working With Strings
solution.py
# write your code here

EXPECTED OUTPUT

1Magic square

YOUR OUTPUT

Press Run to see your output here. Lines are compared with the expected output.