Reputation: 590
I'm trying to write a function sum_of_squares(xs) that computes the sum of the squares of the numbers in the list xs. For example, sum_of_squares([2, 3, 4]) should return 4+9+16 which is 29:
Here's what I tried:
import random
xs = []
#create three random numbers between 0 and 50
for i in range(3):
xs.append(random.randint(0,50))
def sum_of_squares(xs):
#square the numbers in the list
squared = i ** i
#add together the squared numbers
sum_of_squares = squared + squared + squared
return sum_of_squares
print (sum_of_squares(xs))
Right now this always prints
12
Because it's taking i as in the number of integers in the list as opposed to the value of the integer. How do I say "multiply the value by the value of the integer" for as many integers are in the list to get the squared values?
Asking that question led me to try this:
import random
xs = []
#create three random numbers between 0 and 50
for i in range(3):
xs.append(random.randint(0,50))
def sum_of_squares(xs):
#square the numbers in the list
for i in (xs):
squared = i ** i
#add together the squared numbers
sum_of_squares = squared + squared + squared
return sum_of_squares
print (sum_of_squares(xs))
But it doesn't seem to be squaring the values of the integers correctly - I'm not sure what it's doing. See this screenshot of a Visualize Python walkthrough.
Upvotes: 2
Views: 12126
Reputation: 92
Right the concept first on paper.
You have to parse the List, do the square and save it to some variable.
import random
xs = []
#create three random numbers between 0 and 50
for i in range(3):
xs.append(random.randint(0,50))
def sum_of_squares(xs):
result = 0
for i in xs:
result += i*i
return result
Upvotes: 1
Reputation: 341
you are doing silly mistakes. try this:
import random
xs = []
for i in range(3):
xs.append(random.randint(0,50))
def sum_of_squares(xs):
sum_of_squares=0 #mistake 1 : initialize sum first. you are making new sum variable in loop everytime.
for i in (xs):
squared = i * i #mistake 2 : ** is exponent and not multiply.
sum_of_squares += squared #mistake 3
return sum_of_squares
print (sum_of_squares(xs))
Upvotes: 3