I am working on the odd number magic square problems.
I start the first number in the last row and center column. It worked on the 3x3 square, but not on any other odd numbers. Can anybody check my code?

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

Actually, it seems fine. I have no problems with magic(5) and magic(7). Only trouble I had was your %2d format was too narrow for magic(15), but a quick fix to that worked as well.

Why do you think it's not working?

Sorry the code I posted is before I made change. I wrote a new code so that the starting number is on the last row and center column. when I made this change, the sum doesn't add up same.

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 = n-1
		col = (n-1)/2
		M = n*n #largest number on the grid
		v = 1
		r = 0
		c = 0
		grid[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 grid[r][c]:
				if (row+1) < n:
					r = row+1
					c = col
			grid[r][c] = v
			row = r
			col = c
		for r in xrange(n):
			for c in xrange(n):
				print grid[r][c],
			print

Hmmm ... if you go down and to the right, shouldn't you head UP when you've hit a nonempty square? Your code seems to go down, which ruins the symmetry.

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.