Ask Your Question
1

other way of creating a list of perfect squares

asked 2021-10-07 12:34:38 +0100

jhonvi2 gravatar image

Hi there! I am currently explaining a certain exercise to my buddy and part of it consists in creating a list of perfect squares up to root of 64 (included) therefore the list has to look like this [0, 1, 4, 9, 16, 25, 36, 49, 64] My first idea was this

squares=[i*i for i in range(sqrt(64)+1)]

which works but I am now trying to do it in a way so that is not compressed such us

 for i in range(sqrt(64)+1)
        squares=[i*i]
    print(squares)

But I keep getting this error

 for i in range(sqrt(Integer(64))+Integer(1))
                                                ^
SyntaxError: invalid syntax

Any ideas of what I am doing wrong?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-10-07 13:05:22 +0100

tmonteil gravatar image

updated 2021-10-07 13:10:45 +0100

In a for loop, the line must end with a colon :

By the way, here are some hints for the exercise:

  • if L is a list, you can add an element to L with L.append(element)
  • the empty list is denoted by []
  • if you want to avoid the use of the square root, you can replace the for loop with a while loop
edit flag offensive delete link more

Comments

Hi! thank you so much for your help my code is better now! I just do not really understand your last statement 'if you want to avoid the use of the square root, you can replace the for loop with a while loop' Isn't it the same the for loop and the wwhile loop?

jhonvi2 gravatar imagejhonvi2 ( 2021-10-07 18:36:02 +0100 )edit

In a for loop, you have to know in advance where to stop, in a while loop, you test on-the-fly.

tmonteil gravatar imagetmonteil ( 2021-10-07 20:15:36 +0100 )edit

@tmonteil ok so I could do something like

   n =95    
   cuadrados=[ ]
    i=0
    root= int(sqrt(n)+1)
     while i < root:  
       cuadrados.append(i*i)

but it does not seem to work I keep getting an error in cuadrados.append(i*i)

jhonvi2 gravatar imagejhonvi2 ( 2021-10-08 22:40:44 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2021-10-07 12:34:38 +0100

Seen: 534 times

Last updated: Oct 07 '21