Python Forum
Magic Square Puzzle - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Magic Square Puzzle (/thread-4340.html)



Magic Square Puzzle - Harnick - Aug-09-2017

my question here
Hi I'm new to python and i have been tasked with creating a magic square puzzle. However the inputs for the magic square puzzle have to be provided through a file. This is the task:
 The program should prompt the user for the filename of a text file to open – some Python error handling should be used in case the user enters the name of a file that does not exist.

 The program should read the contents of the given text file and store this in a suitable Python data structure.

 Appropriate validation should be in place to ensure the supplied file contains a complete n x n square grid of digits, and ensure the digits are all integers in the range 1 to n2; a suitable error message should be returned where necessary.

 Assuming a suitable n x n square grid of integers is successfully loaded into the chosen data structure; further checks should then be performed to ensure that the sums of each row, each column, and each of the two diagonals are all equal.

 If any errors are detected in the puzzle board then details of these errors should be given to the user.

 If the puzzle board passes all the validation checks, then it should be written into a new text file using the same format as the original input file (see the example text files above) – the name for this new text file should be the original filename entered by the user prefixed with “VALID_”.
I would really appreciate it if anyone could help me with this task as I have been struggling.

Many Thanks

Further adding to this, this is the code i have so far:
fr = open('magicsquare1.txt', 'r')
#Calculating Totals for each row
for line in fr:
    total = 0
    line = line.split()
    c = len(line)
    print(line)

    for i in range(c):
        total = total +int(line[i])

print("total:", total)



RE: Magic Square Puzzle - nilamo - Aug-09-2017

Break the problem into small pieces, and get each small piece working by itself.  Once you have that, you can combine them to have the overall project complete.

For example, I'd suggest ignoring file handling, user input, and parsing file contents.  Start with hard-coding a magic square, and write a function that checks whether or not it's valid.  Something like:
def is_square_valid(square):
    # I actually have no idea what a magic square is, so they all look invalid to me
    return False

test_square = [
    [2, 3, 4],
    [6, 1, 2],
    [1, 5, 3]
]

print(is_square_valid(test_square))
Once that works with various input, then you can start making things more complicated.