-1

I need some advice on how to write a Python program where it gives you a list of the first n perfect squares in list format. The output should look like this:

How many squares?: 5  
[1, 4, 9, 16, 25]

This is what I have so far:

n = int(raw_input("How many squares? "))

Now for the next part I need to create a list of the first n squares. Any suggestions on how? Thank you for your time and advice.

  • 3
    @justin: There are two parts to problem. Knowing the algorithm and implementing it in python. Provide the algorithm and then you can be guided on how to implement it with python – pyfunc Nov 12 '10 at 03:54
  • 116
    Thanks to all who helped Justin with his university assignment: your solutions are his solutions. Justin has been monitored by the course staff for some time now and will meet shortly with the Dean to discuss his future academic career. –  Dec 11 '10 at 19:10

6 Answers6

10

Use a list comprehension:

[ a*a for a in xrange(1, n + 1) ]
jimmyb
  • 4,227
  • 2
  • 23
  • 26
4

Now for the next part i need to start to create a list of the first n squares. Any suggestions on how? Thank You for your time and advice.

This is something you can be helped with. For the other part, post your algorithm.

Use range to generate a list:

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Use list comprehension to get list of x^2

>>> [x**2 for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> 

A more elegant answer is provided by Novikov

pyfunc
  • 65,343
  • 15
  • 148
  • 136
2
n = int(raw_input("How many squares? "))
map((2).__rpow__, range(1, n+1))

or

from operator import mul
n = int(raw_input("How many squares? "))
map(mul, *[range(1, n+1)]*2)
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
1

Somebody mentioned generators - this is how you use them in this case:

def sq(n):
    i=0
    while i<n:
        i+=1
        yield i*i

if __name__=="__main__":
    n = int(raw_input("How many squares? "))
    print list(sq(n))
vonPetrushev
  • 5,457
  • 6
  • 39
  • 51
0

Or with map and a lambda function

n = int(raw_input("How many squares? "))
map(lambda x: x*x, range(n))

if you want it starting at 1

map(lambda x: x*x, range(1, n+1))
Novikov
  • 4,399
  • 3
  • 28
  • 36
  • can u explain what map and lambda does? –  Nov 12 '10 at 04:03
  • @justin: these things are generally discouraged. No need to learn it, and it's bad style to write it. http://www.artima.com/weblogs/viewpost.jsp?thread=98196 – bukzor Nov 12 '10 at 05:44
0

code:

list_squares=[]
for a in xrange(1, n+1):
 list_squares.append(a*a)
print list_squares

where n is user input for number of squares he wants.

If n=5 then the output looks like:

[1, 4, 9, 16, 25]
Arnab Ghosal
  • 483
  • 1
  • 4
  • 11