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.
this what i have. and my program works only for odd numbers.

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)

i want the following output,i need help making it better.thanks

Recommended Answers

All 17 Replies

That is not recursive function

i actualy dont know how to do it, i had something like this but not sure.

def magic(n):
	if n > 2 and n % 2 == 0:
		print "You need an odd number."
	elif n <=2:
		print "You need a number greater or equal to 3."
	else:
		print "Magic Square: ", n, 'x', n
		grid = [ [ 0 for c in xrange(n) ] for r in xrange(n) ]
		row, col = 0, n/2
		n2, v = n*n, 1;
		r, c = 0, 0
		grid[row][col] = v
		while v != n2:
			v += 1
			if (row-1) >= 0:
			    r = row-1
			else:
			    r = n-1
			if (col+1) < n:
			    c = col+1
			else: c = 0
			if grid[r][c]:
				if (row+1) < n:
					r = row+1
					if grid[r][col]:
					    break
					c = col
			grid[r][c] = v
			row = r
			col = c
		for r in xrange(n):
			for c in xrange(n):
				print "%2d" % grid[r][c],
			print

A recursive function calls itself (or calls a function that calls a function that ... calls the original). If you think about a magic square, where would there be a chance to recurse? Since we need to test the main diagonals as well as the rows and columns, we can't recurse on the test for magicness. So, I suppose the only option is to write a recursive function to build the square to test. I'll leave that as an exercise...

this is my permutation

from itertools import permutations
x=[1,2,3,4,5,6,7,8,9]
for a in permutations(x,9):
    if a[0]+a[1]+a[2]==15 and a[3]+a[4]+a[5]==15:
        if a[6]+a[7]+a[8]==15 and a[0]+a[3]+a[6]==15:
            if a[1]+a[4]+a[7]==15 and a[2]+a[5]+a[8]==15:
                if a[0]+a[4]+a[8]==15 and a[2]+a[4]+a[6]==15:
                    print(a[0:3])
                    print(a[3:6])
                    print(a[6:])
                    print()

but ma problem is to Use a recursive permute to give all of the permutations of the square.

Ok, I help little in pseudocode: Empty lists permutations are only empty list else permutations are each of llist value followed permutations of other values.

Another hint is this: for every permutation of 1, .. 6, like

(3, 2, 5, 1, 6, 4)

you can generate 7 permutations of 1, ... 7 by inserting 7 somewhere, like in

(3, 2, 7, 5, 1, 6, 4)

This what i have but wont work

def makeSquare(n):
  mSquare = [ [ 0 for c in xrange(n) ] for r in xrange(n) ]
  row = n-1
  col = (n-1)/2
  M = n*n #
  v = 1
  r = 0
  c = 0
  mSquare[row][col] = v
  while v != M:
    v =v + 1
    if (row+1) >= n:
      r = 0
    else:
      r = row + 1
    if (col+1) < n:
      c = col+1
    else: c = 0
    if mSquare[r][c]:
      if (row+1) < n:
        r = row+1
        c = col
      grid[r][c] = v
      row = r
      col = c
  
  #print Magic Square
  for r in xrange(n):
    for c in xrange(n):
      print mSquare[r][c],
    print
    


def checkSquare(mSquare):
  #Calculates if square is valid
  d = 0
  for i in range(len(b)):
    r = c = 0
    d += b[i][i]
    for j in range(len(b)):
      r += b[i][j]
      c += b[j][i]

  if (r != c):
    return False

  if (d != r):
    return False
  else:
    return True

def main():
  # Prompt the user to enter an odd number 3 or greater and check the input
  while True:
    n = int(raw_input("Please enter an odd number: "))
    if n > 2 and n % 2:
      break

  # Create the magic square
  makeSquare(n)

  # Verify that it is a magic square
  if checkSquare(mSquare) == True:
    print "This is a magic Square"
  else:
    print "Not a magic Square"
  

main()

mSquare is local variable in makeSquare, you must return it as value to use it.

i dont get it

i dont get it

Simplified you are doing:

def function():
    # local variable visible only in function
    my_local = 4

def other():
    function()
    print(my_local) # my_local not defined here

other()

"""Output:
Traceback (most recent call last):
  File "K:/test/scope.py", line 9, in <module>
    other()
  File "K:/test/scope.py", line 7, in other
    print(my_local) # my_local not defined here
NameError: global name 'my_local' is not defined
>>> """

i actually have to use a list, i dont know how to use it in this case

commented: Use proper sentences! -3

1,2,3,4,5,6,7,8,9

can form this magic square:

123
456
789

and will be represented as

[[1,2,3],[2,1,2],[3,2,1]]

def read_file(file_name):
    f = open(file_name, "r")

    ## creating the new file name
    new_file_name = "new_" + file_name

    ## creating the new file with writing permissions
    n = open(new_file_name, "w")

    for line in f:
        line = line.replace("\n","")
        num = line.split(",")

        ## appending the information to the end of each line
        if fill_array(num) is True:
            ## formatting
            entry = line + " (is a magic number)\n"
            n.write(entry)
        else:
            ## formatting
            entry = line + " (is not a magic nummber)\n"
            n.write(entry)

    n.close()
    f.close()

"""


import sys

def is_identical(list):
    return max(list) == min(list)
    
def check_array(A, length):
    h_sum_list = []
    v_sum_list = []
    
    h_sum = 0
    v_sum = 0
    for i in range(length):
        for j in range(length):
            h_sum += int(A[i][j])
            v_sum += int(A[j][i])
        h_sum_list.append(h_sum)
        v_sum_list.append(v_sum)
        h_sum = 0
        v_sum = 0

    left_to_right_diagonal = 0
    right_to_left_diagonal = 0
    for i in range(length):
        left_to_right_diagonal += int(A[i][i])
        right_to_left_diagonal += int(A[i][length-i-1])
    
    is_horizontal = is_identical(h_sum_list)
    is_vertical = is_identical(v_sum_list)
    if is_horizontal and is_vertical:
        if left_to_right_diagonal == right_to_left_diagonal:
            if left_to_right_diagonal == h_sum_list[0]:
           
                return True
    return False

def fill_array(num):

    A = [[None,None,None],
         [None,None,None],
         [None,None,None]]

    length = 3

    iteration = 0
    for i in range(length):
        for j in range(length):
            A[i][j] = num[iteration]
            iteration += 1

            
    if check_array(A, length):
        return True

    return False
        

def read_file(file_name):
    f = open(file_name, "r")
    new_file_name = "new_" + file_name
    n = open(new_file_name, "w")
    for line in f:
        line = line.replace("\n","")
        num = line.split(",")
        if fill_array(num) is True:
            entry = line + " (is a magic square)\n"
            n.write(entry)
        else:
            entry = line + " (is not a magic square)\n"
            n.write(entry)

    n.close()
    f.close()
    
def main():
    file_name = sys.argv[1]
    read_file(file_name)

if __name__ == "__main__":
    main()

my prof say he doesnt want an array, he wants a list instead and i am having a hard time doing it

You still have no recursion and you have most of your code commented out. And you are using list not array.

never mind, i figure this out on my own

import operator, random, sys, time, math
from math import*

square = []

def userinput(): #demands input from the user
    return input('enter a value for n: ')

def isvalid(n): #checks whether n is valid
    if n == 0 :
        print 'invalid arguments for magic square'
        return 0
    elif n==2:
        print 'invalid arguments for magic square'
        return 0
    elif n>3:
        print 'warning: n is greater than 3 so it will take a long time to compute'
        return 1
    else:
        return 1

def thesquare(n): #creates a NxN matrix
    for i in range(n):
        square.append([])
        for j in range(n):
            square[i].append(0)
            return square

def thesum(n): #computes the required sum
    s = (n*(n*n + 1))/2
    return s

def allpossiblevals(n): #lists all possible values
    vals = range(1, (n*n)+1, 1)
    return vals

def allpermutations(vals): #lists all possible arrangements of all possible values
    length = len(vals)
    if length <= 1:
        yield vals
    else:
        for permut in allpermutations(vals[1:]):
            for i in range(len(permut)+1):
                yield permut[:i]+vals[0:1]+permut[i:]

def perm(): #evaluates which permutations are valid magic squares
    n = userinput()
    v = isvalid(n)
    if v == 1:
        squares = thesquare(n)

but program wont run

You are not calling any function!

i have to have a main function but dont know how to call it in the functions in it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.