magic squares in python

Page 1 of 1

13 Replies - 7660 Views - Last Post: 11 December 2011 - 01:14 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=257964&amp;s=e664491ecec1f8e931eea138b9ea16e0&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

#1 asong84

Reputation: -2
• Posts: 16
• Joined: 29-October 09

magic squares in python

Posted 01 December 2011 - 10:43 AM

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)
```

Is This A Good Question/Topic? 0

Replies To: magic squares in python

#2 atraub

• Pythoneer

Reputation: 822
• Posts: 2,198
• Joined: 23-December 08

Re: magic squares in python

Posted 01 December 2011 - 01:01 PM

This post has been edited by atraub: 01 December 2011 - 01:02 PM

#3 Simown

• Blue Sprat

Reputation: 321
• Posts: 650
• Joined: 20-May 10

Re: magic squares in python

Posted 01 December 2011 - 02:01 PM

The line:
```if m%2!=0:
```

Means that only odd numbers are going to be evaluated, what is the purpose of this? I can't tell exactly because of your formatting how far this if statement covers.

+ what atraub said.

This post has been edited by Simown: 01 December 2011 - 02:03 PM

#4 hiddenghost

Reputation: 39
• Posts: 621
• Joined: 15-December 09

Re: magic squares in python

Posted 03 December 2011 - 06:20 AM

Holy crap! I tried.

This is one hell of a thing.

My little magic-square program will have to lay unfinished for now.

I did notice a pattern related to how the numbers are arranged which looks very interesting.

It looks like an infinite sequence could be used to find each position of the numbers.
You know. Kind of like adding area to a shape instead of multiplying its sides.

Maybe there is something I'm overlooking. Oh well.

It'll be a while before I try that again.

#5 Simown

• Blue Sprat

Reputation: 321
• Posts: 650
• Joined: 20-May 10

Re: magic squares in python

Posted 03 December 2011 - 10:31 AM

So, you're giving up for now? Assuming we won't help you any more? You told us that your program only works with odd numbers, and gave us the assignment. I said why it only works with odd numbers.

We won't write the code for you, but are happy to help if you give us more than "the code's not working properly". Maybe you could apply what you noticed about the numbers to the problem and come back with a more specific question if you are stuck?

#6 asong84

Reputation: -2
• Posts: 16
• Joined: 29-October 09

Re: magic squares in python

Posted 08 December 2011 - 07:13 AM

i havent ask you to answer the question for me, i am a first time porogrammer and i just needed some help in where am wrong.I have this so far but still not giving me the output, dont know where i went wrong
```import operator, random, sys, time, math
from math import*
import string
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)
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)
a = allpossiblevals(n)
b = allpermutations(a)
c = list(B)/>
psize = len(c)
total = thesum(n)
for i in range(psize):
count = 0
for j in range(n):
for k in range(n):
squares[j][k] = c[i].pop()
for l in range(n):
if sum(square[l]) == total:
count = count + 1
transpose = zip(*square)
for m in range(n):
if sum((transpose)[m]) == total:
count = count + 1
if count == n+n:
print' square'

```

#7 atraub

• Pythoneer

Reputation: 822
• Posts: 2,198
• Joined: 23-December 08

Re: magic squares in python

Posted 08 December 2011 - 01:01 PM

Are the answers wrong? Is it not printing out any answers? Can you give us an example of sample input, what should come out, and what actually comes out? Help us help you.

#8 asong84

Reputation: -2
• Posts: 16
• Joined: 29-October 09

Re: magic squares in python

Posted 09 December 2011 - 05:34 AM

sorry about that, the program 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.so the program must use command line arguments. At the command line the user must enter (in this order):
the name of the executable file,
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.This is where my problem is, i dont know how to use command line arguments, i know rawinput but they want us to use command line

#9 atraub

• Pythoneer

Reputation: 822
• Posts: 2,198
• Joined: 23-December 08

Re: magic squares in python

Posted 09 December 2011 - 11:14 AM

First off, thank you for the additional information. Secondly, I hope you can recognize that prior to your most recent post, no one could have possibly had any idea that your issue was surrounding command line arguments.

There's a module that you can learn more about called argparse, but it doesn't actually do what your teacher wants, and it's a bit more complex than you need for this project.

Instead, the easiest way to accomplish this is with argv from the sys module. Here is a demonstration of argv in action which should tell you everything you need to know.

```#commandLine.py
#My first command line argument will be my first name
#My second argument will be my Dog's name

import sys

moduleName = sys.argv[0]
myName = sys.argv[1]
dogsName = sys.argv[2]

print "The name of my module is: "+ moduleName
print "My name is: "+ myName
print "My dog's name is: "+ dogsName

```

Now, when I run the module, I say python commandLine.py Adam Fido
and my program outputs:

```The name of my module is: commandLine.py
My dog's name is: Fido

```

Notice the command line statement. The position of each argument in sys.argv coincides with the position of each argument after the word 'python'.

Do you think you can solve your problem with the information I've provided you?

EDIT:
I doubt your professor requires that you do error checking, but if you want to be awesome, you could give your user a nasty message if he doesn't enter in enough arguments

This post has been edited by atraub: 09 December 2011 - 12:50 PM

#10 asong84

Reputation: -2
• Posts: 16
• Joined: 29-October 09

Re: magic squares in python

Posted 10 December 2011 - 10:25 PM

my problem is how can i used it my program, sorry if i ask a lot of questions, i am still going to figure it out.

#11 atraub

• Pythoneer

Reputation: 822
• Posts: 2,198
• Joined: 23-December 08

Re: magic squares in python

Posted 10 December 2011 - 11:14 PM

We are not a code writing service. I gave you an example demonstrating how to utilize command line arguments in the way your teacher specified. Please try to incorporate it on your own rather than asking us to do it for you. If you run into trouble, please show us your updated code and explain what your problem is.

#12 asong84

Reputation: -2
• Posts: 16
• Joined: 29-October 09

Re: magic squares in python

Posted 11 December 2011 - 10:23 AM

i didnt say u are a code writing service.I odnt know what you are talking about,if you dont want to help or give advice on code then dont comment please.

#13 atraub

• Pythoneer

Reputation: 822
• Posts: 2,198
• Joined: 23-December 08

Re: magic squares in python

Posted 11 December 2011 - 11:02 AM

It seems we have a misunderstanding. Let me try this again from a different angle.

Quote

At the command line the user must enter (in this order):
the name of the executable file,
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.

i dont know how to use command line arguments

I then proceeded to give you a lengthy explanation as to how to create an application that leverages command line arguments in which:

Quote

My first command line argument will be my first name
My second argument will be my Dog's name
Is this not the exact same in concept as yours?

We provide help on good faith that you'll attempt to solve problems on your own. When someone needs help understanding a concept I tend to teach them the concept so that they can incorporate it into their programs themselves. I have given you a detailed explanation of how you can utilize command line arguments for your program, but your response was

Quote

my problem is how can i used it my program

If you still don't understand how command line arguments work, please explain what about them you don't understand. Otherwise, please show us an effort to incorporate them into your program; the example I gave you demonstrates exactly how to do it. If you still have trouble after you've given it an attempt on your own, show us your attempt and we'll try to assist you further.

This post has been edited by atraub: 11 December 2011 - 11:04 AM

#14 asong84

Reputation: -2
• Posts: 16
• Joined: 29-October 09

Re: magic squares in python

Posted 11 December 2011 - 01:14 PM