user1176235
user1176235

Reputation: 379

How is this algorithm working?! Can someone explain it to me please..have an interview tomorrow

def sum_in(numbers, sum_):
    """whether any two numbers from `numbers` form `sum_`."""
    return any((sum_-n) in numbers for n in numbers)

It basically takes a list, and checks if any two numbers from it form a sum equalling sum_. I can't seem to get how that sum_-n verifies that TWO numbers equal the sum. Wouldn't it just be checking with one n each loop?!

Upvotes: 0

Views: 128

Answers (2)

johnsyweb
johnsyweb

Reputation: 141770

For each iteration, a bool is generated whether (sum_ - n) is in the set of numbers. If one of these bools is True, the function returns True. It returns False otherwise, clearly.

This is not a great algorithm, to put it mildly.

Consider:

sum_in((3,), 6)

This will return True. Why? Because 6 - 3 is in numbers.

So yes, it is only checking one value in each iteration.

Good luck with the interview!

Upvotes: 1

GuillaumeDufay
GuillaumeDufay

Reputation: 1128

It's checking sum_-n is in numbers. If it is, then that number + n = sum_.

Upvotes: 3

Related Questions