Counting and generating perfect squares

匆匆过客 提交于 2019-11-30 00:08:17

问题


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.


回答1:


Use a list comprehension:

[ a*a for a in xrange(1, n + 1) ]



回答2:


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




回答3:


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)



回答4:


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



回答5:


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:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!