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.
Use a list comprehension:
[ a*a for a in xrange(1, n + 1) ]
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
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)
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))
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))
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]
来源:https://stackoverflow.com/questions/4161475/counting-and-generating-perfect-squares