Skip to content

Instantly share code, notes, and snippets.

@talyian talyian/arithmetic
Last active Jun 30, 2017

Embed
What would you like to do?
Not a good interview problem
EVAL=(lambda F,B,V,P,T:lambda e:F(T(e),F,P,B(B,V))[0])(
lambda t,f,p,b: [p(p,t,(lambda x:b(('+','-'),b(('*','/'),x))))],
lambda b,e: lambda ops,t,i=0: t if i >= len(t) else b(b,e)(ops,(t.__setslice__(i-1,i+2,[e(t[i],t[i-1],t[i+1])]) or t),i) if t[i] in ops else b(b,e)(ops,t,i+1),
lambda o,x,y: {'+':lambda a,b:a+b, '-':lambda a,b:a-b, '*':lambda a,b:a*b, '/':lambda a,b:a/b}[o](float(x), float(y)),
lambda p, t, f: f((lambda s,e:t.__setslice__(s,e+1,[p(p,t[s+1:e], f)]) or t)(t.index('('),len(t)-1-t[::-1].index(')')) if '(' in t else t)[0],
lambda e: [x for x in __import__('re').split('(\\d+|.)', e.replace(' ', '')) if x],
)
print EVAL("3 - 5 - 4 - 3");
print EVAL("3 * 5 + 4 / 3");
print EVAL("3 * (5 + 4) / 2");
print EVAL("3 + 3 * 9 + 3 / 3 + 1");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.