stupid python tricks

6 thoughts
last posted April 25, 2016, 8:24 a.m.

2 earlier thoughts

1

Dave's Stupid Python Tricks (mark II) Fun: a toy for interpreting GFM Tables per McCarthy 1960:

Fun = lambda s: min( globals().update(eval(com(par(s))))
    for par in [lambda txt: [[f.strip() for f in pline(l.split('|'))]
            for pline in [ lambda xs:
                ((xs[0],'') if len(xs)==1 else
                  xs        if len(xs)==2 else
                  xs[1:3]   if len(xs)==4 else None) ]
            for l in txt.strip().split('\n') ]]
    for com in [lambda xs: compile(xs[0],xs[1:])
            if xs and None not in xs else '[]'
            for nonsep  in [lambda s: any(c not in ' -:' for c in s)]
            for compile in [lambda hdr,bdy:
                '[("{}",(lambda {}:{} None))]'.format(
                    hdr[0], hdr[1], ' '.join(clause(b)
                for b in bdy if nonsep(b[0]+b[1])))
        for clause in [lambda b:
                    '({}) if ({}) else'.format(
                      b[0],   b[1] or 'True')]]])

if __name__ == "__main__":
    Fun('''
        | fact        | n   |
        |------------:|:----|
        | 1           | n<2 |
        | n*fact(n-1) |     |
    ''')
    print(fact(5))

    Fun('''
        gcd        | x,y
        ----------:|:---
        gcd(x-y,y) | y<x
        gcd(x,y-x) | x<y
        x          |
    ''')
    print(gcd(10,2014))

3 later thoughts