Skip to content

Instantly share code, notes, and snippets.

@timfi

timfi/bf.py Secret

Last active September 2, 2023 00:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timfi/6bab3480ab439f0e98f18d88750d3b38 to your computer and use it in GitHub Desktop.
Save timfi/6bab3480ab439f0e98f18d88750d3b38 to your computer and use it in GitHub Desktop.
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