import random
import math

# Boltzmann generator for binary trees with the specification T = E + ZT^2
# the generating function for such trees is T(x) = (1-sqrt(1-4x))/(2x)

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.24999999999999)
