Linked structures¶
A search tree with parent links and a singly linked list, written the way
TheAlgorithms/Python writes its data structures: classes with no
annotations, fields set to None in __init__ and linked up by methods,
and the work in a function the main block calls. The folder's
pyproject.toml turns strict mode off. ppy run types every field from
what the program stores into it, and runs the methods that relink the
nodes as native code.
Run it¶
python trees.ppy
ppy run trees.ppy
ppy explain trees.SearchTree.rotate_up
ppy explain trees.Node
ppy explain --summary trees.ppy
What it prints¶
python trees.ppy
ppy run trees.ppy
ppy explain trees.SearchTree.rotate_up
function: rotate_up
qualname: trees.SearchTree.rotate_up
semantic type: (trees.SearchTree, trees.Node) -> NoneType
effects: ReadObject, WriteObject
purity: impure
optimization: O2
python backend: optimized
llvm backend: native; called from Python, its Python body runs: the boundary crossing costs more than the body saves
jit: not requested
parallel: rejected
reason: the function contains no parallelizable loop
representation:
self: trees.SearchTree -> LLVM aggregate (guarded)
node: trees.Node -> LLVM aggregate (guarded)
return: NoneType -> void
inferred (not annotated):
node: trees.Node, from 1 call (trees.ppy:80)
(the Python boundary checks these at each call, and runs the Python body otherwise)
return: NoneType, from the body's return statements
ppy explain trees.Node
27 lines
class: Node
qualname: trees.Node
fields:
left: NoneType | trees.Node, from what the program stores into it:
NoneType at trees.ppy:7 in `__init__`
NoneType | trees.Node at trees.ppy:57
trees.Node at trees.ppy:65
trees.Node at trees.ppy:71
trees.Node at trees.ppy:35
right: NoneType | trees.Node, from what the program stores into it:
NoneType at trees.ppy:8 in `__init__`
NoneType | trees.Node at trees.ppy:99
trees.Node at trees.ppy:60
NoneType | trees.Node at trees.ppy:62
NoneType | trees.Node at trees.ppy:108
trees.Node at trees.ppy:73
trees.Node at trees.ppy:40
parent: NoneType | trees.Node, from what the program stores into it:
NoneType at trees.ppy:9 in `__init__`
trees.Node at trees.ppy:43
trees.Node at trees.ppy:66
NoneType | trees.Node at trees.ppy:67
trees.Node at trees.ppy:59
trees.Node at trees.ppy:64
key: int, from what the program stores into it:
int at trees.ppy:6 in `__init__`
methods: __init__
ppy explain --summary trees.ppy
12 functions, 94 statements
native, called from Python 6 functions ( 50%) 45 statements ( 48%)
native, called from native code 6 functions ( 50%) 49 statements ( 52%)
Python 0 functions ( 0%) 0 statements ( 0%)
native, but Python calls the Python body (why its boundary is not used):
4 functions the boundary crossing costs more than the body saves
2 functions the objects it makes cost more to hand to Python than its loops save
The program¶
Node(key)has akeyand three links,left,right, andparent, allNoneat first.SearchTree.insert(key)walks down from the root, hangs a new node on the first empty side, and links it back to its parent.SearchTree.find(key)walks down and returns the node orNone.SearchTree.rotate_up(node)rotatesnodeabove its parent: it moves one subtree across, swaps the two nodes' places, and fixes the three parent links and the root or the grandparent's child.SearchTree.access(key)finds a key and rotates its node up to the root, one rotation at a time, so keys that are asked for often stay near the top (the "move to root" heuristic).LinkedListreusesNode:pushlinks a new node in front of the head throughright,reverserelinks every node in place, andtotalwalks the list.workload(count, seed)insertscountkeys from a linear congruential generator, accesses20 * countkeys of a small range, pushescountvalues onto a list and reverses it 100 times, and returns three numbers.- The main block runs
workload(50_000, 7), then builds a five-node list in Python, reverses it, and prints its total.
Where the field types come from¶
No field is annotated, and every link starts as None. In strict mode
ppy check trees.ppy reports 15 errors: nine E1201 for the parameters,
and six E1202 for reads of key through a node whose type it could not
settle. With strict = false the compiler reads every store into a field
anywhere in the project, not only __init__'s:
here.left = nodeininsert, withnode = Node(key), addsNodetoleft'sNone, soNode.leftis aNode | None.rightandparentget the same frominsert,rotate_up, andpush.self.root = nodemakesSearchTree.rootaNode | None, andself.head = nodedoes the same forLinkedList.head.self.size += 1andself.length += 1from0makeintfields.keyis anintfrom the calls that make nodes:Node(key)ininsert, whosekeycomes fromtree.insert(state % (count * 4)).
With the fields typed, every method is an ordinary native function over
Node handles. rotate_up's node is a Node from its one call in
access, and ppy explain (below) lists it.
ppy explain trees.Node (below) lists each field with the stores that
typed it and their lines.
One shape common in such code does not settle, and the
Classes guide
says why: a recursive insert(node, key) that stores its own result
(node.left = insert(node.left, key)) and is not annotated. A local that
starts as None and later holds a node (prev = None in a list reversal)
does settle: it takes the type of all its bindings, Node | None.
What crosses¶
workload takes two ints and returns a tuple of three, so the call from
Python crosses three numbers. The tree of 50,000 nodes and the list are
made, relinked, and freed inside native code, and every method call is a
native call between native functions.
The methods are native too. When Python calls one, as the main block does after the workload, the cost model decides whether the crossing pays:
small.reverse()andsmall.total()loop over the list, so Python calls them natively. The first of them copies the list's five nodes into native memory; the second finds them resident and hands native code the same records (PPY_RESIDENT_REPORT=1prints6 admitted, 1 calls: the list and its five nodes, one resident call).reverserelinks the nodes natively, and the changedrightlinks are set on the Python nodes when the call answers.pushmakes aNode. An object native code makes has to be made in Python too when the call answers, which costs more thanpushsaves, so Python runs its Python body ("the objects it makes cost more to hand to Python than its loops save").insertis the same.rotate_upand the three__init__methods have no loop, and the crossing costs more than their bodies.
ppy explain --summary counts the six that Python calls through their
Python bodies as native and called from native code, and gives each
reason.
Timing¶
Wall time for the whole program, the mean of five runs, measured from a
checkout under /tmp on one machine (Python 3.14, an Intel Core Ultra 9
386H under WSL2):
| seconds | |
|---|---|
python trees.ppy |
0.79 |
ppy run trees.ppy, after the first run built the cache |
0.44 |
workload(50_000, 7) alone, as the program prints it, the mean of five
runs: 0.77 s under CPython and 0.40 s under ppy run.
There is no standalone build: the program has no main(), and a
standalone binary needs a native main to start from.
Where the code comes from¶
trees.ppy is hand-written.
Read on: Classes and Types from call sites.
55_linked_structures/trees.ppy¶
import time
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.parent = None
class SearchTree:
"""
>>> tree = SearchTree()
>>> for key in [5, 3, 8, 1]:
... tree.insert(key)
>>> tree.access(1), tree.root.key, tree.access(4)
(True, 1, False)
"""
def __init__(self):
self.root = None
self.size = 0
def insert(self, key):
node = Node(key)
self.size += 1
if self.root is None:
self.root = node
return
here = self.root
while True:
if key < here.key:
if here.left is None:
here.left = node
break
here = here.left
else:
if here.right is None:
here.right = node
break
here = here.right
node.parent = here
def find(self, key):
node = self.root
while node is not None and node.key != key:
node = node.left if key < node.key else node.right
return node
def rotate_up(self, node):
parent = node.parent
if parent is None:
return
grand = parent.parent
if parent.left is node:
parent.left = node.right
if node.right is not None:
node.right.parent = parent
node.right = parent
else:
parent.right = node.left
if node.left is not None:
node.left.parent = parent
node.left = parent
parent.parent = node
node.parent = grand
if grand is None:
self.root = node
elif grand.left is parent:
grand.left = node
else:
grand.right = node
def access(self, key):
node = self.find(key)
if node is None:
return False
while node.parent is not None:
self.rotate_up(node)
return True
def depth(self, key):
steps = 0
node = self.root
while node is not None and node.key != key:
node = node.left if key < node.key else node.right
steps += 1
return steps
class LinkedList:
def __init__(self):
self.head = None
self.length = 0
def push(self, value):
node = Node(value)
node.right = self.head
self.head = node
self.length += 1
def reverse(self):
node = self.head
self.head = None
while node is not None:
following = node.right
node.right = self.head
self.head = node
node = following
def total(self):
result = 0
node = self.head
while node is not None:
result += node.key
node = node.right
return result
def workload(count, seed):
tree = SearchTree()
state = seed
for _ in range(count):
state = (state * 1103515245 + 12345) % 2147483648
tree.insert(state % (count * 4))
found = 0
for step in range(count * 20):
key = (step * step) % (count // 10)
if tree.access(key):
found += 1
chain = LinkedList()
for key in range(count):
chain.push(key)
for _ in range(100):
chain.reverse()
return found, tree.depth(0), chain.total()
if __name__ == "__main__":
start = time.perf_counter()
print("found, depth of 0, total:", workload(50_000, 7))
print(f"# workload: {time.perf_counter() - start:.2f} s")
small = LinkedList()
for item in range(5):
small.push(item)
small.reverse()
print("reversed in place:", small.total(), small.length)
Source: examples/55_linked_structures.