Skip to content

Instantly share code, notes, and snippets.

@timfi

timfi/bf.py Secret

Last active Jun 25, 2020
Embed
What would you like to do?
Brainfuck Interpreter in a single Python expression
(i:=__import__,k:=i("itertools"),g:=lambda s,a,b,p:p+next(i for i,d in enumerate(k.accumulate({a:1,b:-1}.get(c,0)for c in s[p:]))if 0==d),f:=lambda s,p,m,c:(s,*{"+":lambda:(p,m[:p]+[m[p]+1]+m[p+1:],c+1),"-":lambda:(p,m[:p]+[m[p]-1]+m[p+1:],c+1),">":lambda:(p+1,m+[0]*(p+1>=len(m)),c+1),"<":lambda:(max(p-1,0),[0]*(p-1<0)+m,c+1),".":lambda:print(chr(m[p]),end="") or(p,m,c+1),",":lambda:(p,m[:p]+[ord(input()[0])]+m[p+1:],c+1),"[":lambda:(p,m,(g(s,"[","]",c)if 0==m[p]else c)+1),"]":lambda:(p,m,len(s)-g(s[::-1],"]","[",len(s)-c-1)if 0!=m[p]else 1+c)}.get(s[c],lambda:(p,m,c+1))()),i("functools").reduce(lambda s,_:exit(0)if len(s[0])<=s[3]else f(*s),k.count(1),(open(i("sys").argv[1]).read(),0,[0],0)))
(
i := __import__,
k := i("itertools"),
g := lambda s, a, b, p: p
+ next(
i
for i, d in enumerate(k.accumulate({a: 1, b: -1}.get(c, 0) for c in s[p:]))
if 0 == d
),
f := lambda s, p, m, c: (
s,
*{
"+": lambda: (p, m[:p] + [m[p] + 1] + m[p + 1 :], c + 1),
"-": lambda: (p, m[:p] + [m[p] - 1] + m[p + 1 :], c + 1),
">": lambda: (p + 1, m + [0] * (p + 1 >= len(m)), c + 1),
"<": lambda: (max(p - 1, 0), [0] * (p - 1 < 0) + m, c + 1),
".": lambda: print(chr(m[p]), end="") or (p, m, c + 1),
",": lambda: (p, m[:p] + [ord(input()[0])] + m[p + 1 :], c + 1),
"[": lambda: (p, m, (g(s, "[", "]", c) if 0 == m[p] else c) + 1),
"]": lambda: (
p,
m,
len(s) - g(s[::-1], "]", "[", len(s) - c - 1) if 0 != m[p] else 1 + c,
),
}.get(s[c], lambda: (p, m, c + 1))(),
),
i("functools").reduce(
lambda s, _: exit(0) if len(s[0]) <= s[3] else f(*s),
k.count(1),
(open(i("sys").argv[1]).read(), 0, [0], 0),
),
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment