Counting and generating perfect squares

2019-02-11 09:53发布

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.

6条回答
放荡不羁爱自由
2楼-- · 2019-02-11 09:58

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]
查看更多
时光不老,我们不散
3楼-- · 2019-02-11 10:07

Use a list comprehension:

[ a*a for a in xrange(1, n + 1) ]
查看更多
一夜七次
4楼-- · 2019-02-11 10:07
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)
查看更多
姐就是有狂的资本
5楼-- · 2019-02-11 10:09

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))
查看更多
手持菜刀,她持情操
6楼-- · 2019-02-11 10:13

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))
查看更多
beautiful°
7楼-- · 2019-02-11 10:17

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

查看更多
登录 后发表回答