treyhunner, ![]()
Knowing when to use a set in #Python can be VERY handy sometimes.
no_neighbors = [
n
for n in nums
if n-1 not in nums
and n+1 not in nums
]If "nums" is a list of 500,000 numbers, this takes 54 minutes.
Convert "nums" to a set and this taken less than 1 second.
Why?
It's all about that "in" operator.
Checking for containment in a list requires looping over the whole list.
Checking for containment in a set uses the magic of hashing to return an answer without looping.