import random
import math

# Boltzmann generator for binary trees with the specification T = E + ZT^2
# This one generates many small trees because the distribution is awkward

def BoltzmannTree(x):
    # set up	
    u = random.random()

    # handle union		
    if u < 1/((1-math.sqrt(1-4*x))/(2*x)):
        return 'E'
    
    # handle product
    return ['Z', BoltzmannTree(x), BoltzmannTree(x)]

print(BoltzmannTree(0.24))
print(BoltzmannTree(0.2499))
