The Student Room Group

How do i square, add and then square root all the items in a list? (python)

basically the title
What have you tried so far?

number ** 2 -- this squares a number
sum(iterable) -- this sums the items in an iterable
number ** 0.5 -- this square roots a number
(edited 2 years ago)
Original post by Composure
What have you tried so far?

number ** 2 -- this squares a number
sum() -- this sums the items in an iterable
number ** 0.5 -- this square roots a number

I have however, how would i apply that to a tuple I.e. If i had (1,3,5) how would I square, add and square root all those numbers in one step?
Original post by Benjaminepalatty
I have however, how would i apply that to a tuple I.e. If i had (1,3,5) how would I square, add and square root all those numbers in one step?

Uhh, you would do it in the exact same way...
>>> sum(n ** 2 for n in (1, 3, 5)) ** 0.5
5.916079783099616
Original post by Composure
Uhh, you would do it in the exact same way...
>>> sum(n ** 2 for n in (1, 3, 5)) ** 0.5
5.916079783099616


how do i do that for a list that's inputted by the user?
Original post by Benjaminepalatty
how do i do that for a list that's inputted by the user?

numbers = []
for _ in range(3):
numbers.append(int(input("Enter a number: ")))

print(sum(n ** 2 for n in numbers) ** 0.5)
Original post by Composure
numbers = []
for _ in range(3):
numbers.append(int(input("Enter a number: ")))

print(sum(n ** 2 for n in numbers) ** 0.5)


Thank you for the help but i meant as in inputted via a positional argument i.e
def numbers(v1,v2)
......
Original post by Benjaminepalatty
Thank you for the help but i meant as in inputted via a positional argument i.e
def numbers(v1,v2)
......

So you wanted to do all this to a list, then a tuple, then back to a list, then with user inputs except you didn't mean user inputs and actually meant inside a function using parameters...

What is stopping your from doing it with a function? The code is still the same.

What does the function call look like? Are you calling the function like this numbers(1, 3, 5)?
(edited 2 years ago)

Quick Reply

Latest

Trending

Trending