Skip to content

Instantly share code, notes, and snippets.

@joekreu
joekreu / 1_infix_parser.py
Last active April 16, 2022 13:10
Iterative and recursive precedence parsers for infix expressions, in Python. This gist contains four scripts with increasing complexity.
#! /usr/bin/env python3
''' Script for precedence climbing parsing for infix operators, based
on binding powers; iterative and recursive implementation. Binding
powers are in range 1 to 99. - Separate tokens in DEMOS by spaces.
'''
LBP = {"+": 14, "*": 17, "^": 21, ":=": 22, "$END": -1}
RBP = {"+": 15, "*": 18, "^": 20, ":=": 8}
DEMOS = ['x + 3.4 * y', 'a + b + c', 'n ^ m ^ k', '3 * x := v + 1']