134k views
6 votes
Given a list of numbers, find the correct function to find the sum of the squares of only the positive elements.

sqsum1
sqsum2
sqsum3
sqsum4
sqsum5

Given a list of numbers, find the correct function to find the sum of the squares-example-1
User Emarref
by
4.0k points

1 Answer

3 votes

Answer:

sqsum4

Step-by-step explanation:

So to raise a number to a power in python, you can use the ** operation, which is usually confused with the ^, which is an operation, but it is not for raising numbers to a power. It is the xor bit operation, which if you don't know at the moment, it's fine, since it's not necessary for this. each of these lists uses a generation comprehension which is generally defined as: (x for x in object if condition) with the if condition being optional, but in this case it's necessary. If it's a bit confusing, you can define a generator using a function so it's a bit more spread out:

def generator(object):

for x in object:

if condition:

yield x

Although in this instance were going to be performing some operation on x, which in this case is squaring it. So let's just look at the two functions that use the **, since they should be the only options that will be correct.

sqsum1(nums):

This function does square x, except it uses incorrect syntax. The condition should come after the for loop. Python likely wont tell you this, because it may think you're trying to do something else. You can do one line if statements like this: a if condition else b, which will return a if the condition is true, and b if it isn't. So it may think that you're trying to do this one line if statement, and say that you're missing an else. The function could even implement in this way: x**2 if x > 0 else 0 for x in nums. This way if the x is negative it counts as 0, or in other words isn't counted towards the sum. But without this fix, the function will raise a syntax error

sqsum4(nums):

This will square each number in x only if the current element "x" is greater than 0, or in other words positive. And then it returns the sum. So this function returns the expected output

User Sanjay Bharwani
by
3.6k points