Skip List Probabilistic Ordered Set (Python)
Implement a skip list supporting insert, delete, and search with probabilistic level assignment in Python.
Code
import random
class SkipNode:
def __init__(self, val, level):
self.val = val
self.next = [None] * (level + 1)
class SkipList:
def __init__(self, p=0.5, max_level=16):
self.p = p
self.max_level = max_level
self.head = SkipNode(float("-inf"), max_level)
self.level = 0
def _random_level(self):
lvl = 0
while random.random() < self.p and lvl < self.max_level:
lvl += 1
return lvl
def insert(self, val):
update = [self.head] * (self.max_level + 1)
cur = self.head
for i in range(self.level, -1, -1):
while cur.next[i] and cur.next[i].val < val:
cur = cur.next[i]
update[i] = cur
lvl = self._random_level()
if lvl > self.level:
for i in range(self.level + 1, lvl + 1):
update[i] = self.head
self.level = lvl
node = SkipNode(val, lvl)
for i in range(lvl + 1):
node.next[i] = update[i].next[i]
update[i].next[i] = nodeHow it works
Count the classes SkipNode and SkipList and the functions __init__, _random_level and insert as the entire surface area of Skip List Probabilistic Ordered Set (Python).
Repetition is confined to while random.random() < self.p and lvl < self.max_level — the rest of the file is straight-line.
Using it
Entry signature: def insert(self, val)
insert is the public entry point; everything else in the file exists to support it.
Key statements
def __init__(self, p=0.5, max_level=16):
self.p = p
self.max_level = max_level
self.head = SkipNode(float("-inf"), max_level)
self.level = 0
def __init__(self, val, level):
self.val = val
self.next = [None] * (level + 1)
def _random_level(self):
lvl = 0
while random.random() < self.p and lvl < self.max_level:
lvl += 1
return lvl
Interactive Tools for This Topic
FAQ
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used. Every import resolves inside the standard library — `random`. The file defines `__init__`, `_random_level`, `insert` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.