El recuento y la generación de cuadrados perfectos
-
08-10-2019 - |
Pregunta
necesito algunos consejos sobre cómo escribir un programa Python donde se le da una lista de los primeros n perfectos cuadrados en formato de lista. La salida debe tener este aspecto:
How many squares?: 5 [1, 4, 9, 16, 25]
Esto es lo que tengo hasta ahora:
n = int(raw_input("How many squares? "))
Ahora para la siguiente parte que necesita para crear una lista de los primeros n cuadrados. Alguna sugerencia sobre cómo? Gracias por su tiempo y sus consejos.
Solución
Use a list comprehension:
[ a*a for a in xrange(1, n + 1) ]
Otros consejos
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]