Issue with logic check Space Complexity - Page 6

Screen Link: Learn data science with Python and R projects

My Code:

def find_sums_balanced(values, target_sums):
    value_set = set(values)
    sums = {}
    for target in target_sums:
        sums[target] = False
        
        for value1 in values:
            value2 = target - value1
            
        sums[target] = value2 in value_set
            
    return sums, value_set

What I expected to happen: I happen to expect the expected output

What actually happened: Am seeing incorrect answer.

Replace this line with the output/error

When I look at the answer I see that a if clause is being used to validate the results -

if value2 in value_set:
      sums[target] = True

I expect my code to behave in the same manner. Can someone explain why this is wrong? In the page prior same code was used but it’s not working here.

The above code line runs after your for loop.

Print out value2 both inside and outside the loop to see what you get to understand the above better.

Secondly, after you fix the above, when you use value2 in value_set, you will get either a True or False. However, that’s not what the instructions ask you to do -

If it does, assign True to sums[target].

You only assign True IF value2 is in value_set.

Thanks @the_doctor for the reply. It makes sense now.

1 Like