treyhunner,
@treyhunner@mastodon.social avatar

Knowing when to use a set in 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.

  • All
  • Subscribed
  • Moderated
  • Favorites
  • python
  • DreamBathrooms
  • mdbf
  • osvaldo12
  • magazineikmin
  • GTA5RPClips
  • rosin
  • thenastyranch
  • Youngstown
  • cubers
  • slotface
  • khanakhh
  • kavyap
  • InstantRegret
  • Durango
  • JUstTest
  • everett
  • ethstaker
  • cisconetworking
  • Leos
  • provamag3
  • modclub
  • ngwrru68w68
  • tacticalgear
  • tester
  • megavids
  • normalnudes
  • anitta
  • lostlight
  • All magazines