This should be written in Python. The program will determine all of the magic sq
ID: 3634443 • Letter: T
Question
This should be written in Python. The program will determine all of the magic squares when given an n, display permutations that match the magic squares to the screen AND write it to a file.It will only test when n == 3!!! But code it for n of ANY number!! It must come up with every possible arrangement (permutation) of numbers within the square. These are known as the permutations of that list of numbers. Each permutation needs to be checked to see if it has formed a magic square.
The program must:
Use command line arguments. At the command line the user must enter (in this order):
1. The name of the executable file,
2. n (which will ALWAYS be 3, but again could be run with other numbers)
and the name of the output file in which to write the squares.
Use a recursive permute to give all of the permutations of the square.
In other words, your function called "permute", must be a recursive function. So for each permutation, you should check to see if it is a magic square, display it and write it to the file. Write only the unique magic squares to the SCREEN and FILE. No duplicates allowed. Close any files that you have opened as soon as you have finished using them. Time how long your program takes to find the magic square and print that time at the end of the SAME file.
SAMPLE OUTPUT:
2 7 6
9 5 1
4 3 8
2 9 4
7 5 3
6 1 8
4 3 8
9 5 1
2 7 6
4 9 2
3 5 7
8 1 6
6 1 8
7 5 3
2 9 4
6 7 2
1 5 9
8 3 4
8 1 6
3 5 7
4 9 2
8 3 4
1 5 9
6 7 2
Total running time: 4.76 seconds.
Explanation / Answer
def printsquare(m):
if m%2!=0:
k =[[0 for i in range(m)] for j in range(m)]
r=0;
c=m/2;
for i in range(1,m*m+1):
k[r][c]= i;
br = r+1;
bc = c+1;
r=(r+m-1)%m;
c=(c+1)%m;
if k[r][c]!=0:
r=br;
c=bc-1;
for row in k:
print row
printsquare(3)
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.