#esoteric-python
1 messages · Page 141 of 1
x = something
y = -x
z = -y
it will decrement x, it isnt obvious for user
i would probably need to check if it isn't in quotation marks
not with the bytecode solution
like "i++"
we aren't interpreting a string, we are interpreting python code
i.e. modifying the runtime environment from within the runtime environment
also we can get parent frame and check bytecode, if there are -- or ++ - implement different behavior
we only need to modify the present level frame
what you're thinking of is probably just an interpreter for an entirely different language, which is easy but tedious
also we can implement postfix dec/increment in this way: x++ XXX
in bytecode it will be equal to x + (+XXX), but we can replace something + (+XXX) with custom increment call
(XXX - is reserved name in this implementation)
(this is ugly)
!e
class Int():
def __init__(s,v):s.v = v
__pos__ = lambda s:Int(s.v+1)
__str__ = lambda s:f'{s.v}'
a = Int(2)
print(+a)
@severe canyon :white_check_mark: Your eval job has completed with return code 0.
3
lol, now make it work with two to increment it once, and a single plus does nothing\
mhm, ill do that tomorrow
there was similar implementation:
+i returns i+0.5
+f returns rounded f+0.5
(f - float, i - int)
make a flag as optional input to the __init__
ints is too simple, make it smarter!
i have implemented bitsets (arrays of bits) based on python int (it is possible, because python ints has no limit)
!e
class Int():
def __init__(s,v,state=0):
s.v = v
s.state = state
def __pos__(s):
if s.state: return Int(s.v+1,0)
return Int(s.v,1)
__str__ = lambda s:f'{s.v}'
a = Int(2)
b = Int(2)
print(+a)
print(++b)
@severe canyon :white_check_mark: Your eval job has completed with return code 0.
001 | 2
002 | 3
the worst solution ever
what should i return, if i dont know how to compare object with self?
False or NotImplemented?
🥳
ints with dicts!
sure it wasnt you?
nope
!e ```py
class Int(int):
def init(self, n, flag=0):
super().init(n)
self.flag=flag
def pos(self):
if self.flag:
self.flag=0
return Int(self+1, 0)
self.flag=1
return self
def neg(self):
if self.flag:
self.flag = 0
return Int(self-1, 0)
return Int(0-self, 1)
import ctypes
p = ctypes.py_object.from_address(id(globals())+8)
class flogbals(p.value):
def setitem(self, item, value):
if type(value)in(int,Int):
value = Int(value, 0)
dict.update(self,{item:value})
p.value = flogbals
a = 1
print(++a, a)
print(--a, a)
@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).
001 | Traceback (most recent call last):
002 | File "<string>", line 26, in <module>
003 | File "<string>", line 22, in __setitem__
004 | TypeError: int() can't convert non-string with explicit base
https://www.toptal.com/developers/hastebin/oxafosirov.rb
small implementation of pointer in python
imo it is simpler to use, than ctypes
ok it happens before the error i found
the last underscore in __name__ is blue
it's freaking me out
the syntax highlight is brok
the last underscore is thinner than the others
why second file is markdown (.md), but first - .rb ?
it probably autodetected and detected wrong
class str(Sequence[str]):
the most weird place in typeshed
str is subclass of Sequence[str]
!e
class Dict(dict):
...
d = Dict({'a': 1, 'b': 2})
print(d)
assert type(d) is Dict
print(d.__dict__)
assert type(d.__dict__) is dict
d.__dict__.update(d)
print(d.__dict__)
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
001 | {'a': 1, 'b': 2}
002 | {}
003 | {'a': 1, 'b': 2}
dict with dict, you can use dict while using dict

lol, d.__dict__.update(d) as a one-liner to create a frozen dotteddict
it is possible to set .__dict__ to some value
and i can set d.__dict__ to d
and d.__dict__ will be syncronized with d
should I count scrolling up and seeing this as a bug?
if you don't scroll, there's nothing to see...
but if you do, the ghost of the startup sequence can be seen
>>> class D(dict): ...
...
>>> d = D()
>>> d.__dict__
{}
>>> d.__dict__ = d
>>> d.__dict__ is d
True
>>> d[1] = 2
>>> d.a = 3
>>> d
{1: 2, 'a': 3}
i think it is the most efficient implementation of namespace
>>> class X: ...
...
>>> x1, x2 = X(), X()
>>> x1.__dict__ = x2.__dict__
>>> x1.a = 5
>>> x2.a
5
Is this in console?
I'm sure there is a flag or smthing that disables scrolling
Wow okay it's really that simple
class attrdict(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__dict__ = self
wholesome error message
completely obfuscating the original line that raised the error
миша
"[Previous line repeated 1 more time]"
I tried making itertools.product, it couldn't be brokener
maybe I've lost my grip on programming
!e okay i finally got it to work ```py
def product(*iters,repeat=1,_vars=()):
iters=[*iters]*repeat
if not iters:return()
if len(iters)==1:
for e in iters[0]:
yield _vars+(e,)
else:
for e in iters.pop(0):
yield (*product(*iters,_vars=_vars+(e,)),)
print(*product(range(3),[3,2,3]))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
((0, 3), (0, 2), (0, 3)) ((1, 3), (1, 2), (1, 3)) ((2, 3), (2, 2), (2, 3))
wait that doesn't look right
!e this is getting worse ```py
def product(*iters,repeat=1,_vars=(),_fr=None):
if _fr is None:_fr=[]
iters=[*iters]*repeat
if not iters:return _vars
if len(iters)==1:
for e in iters[0]:
_fr += [_vars+(e,)]
else:
for e in iters.pop(0):
*product(*iters,_vars=_vars+(e,),_fr=_fr),
for e in _fr:yield e
print(*product(range(3),repeat=2))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
(0, 0) (0, 1) (0, 2) (1, 0) (1, 1) (1, 2) (2, 0) (2, 1) (2, 2)
def product(*args, repeat=1):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = [tuple(pool) for pool in args] * repeat
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
example from docs
yeah but tail end recursion is cool
and that has pools I don't like getting water near my laptop
my style of code has progressed much
def aligned(_0, _1):
_=[int()]*6
_[:2] = _1.coords
_[2:4] = _[0]-(_[0]%3),_[1]-(_[1]%3)
return{
_0[_[4],_[1]] for _[4] in range(9)
}|{
_0[_[0],_[5]] for _[5] in range(9)
}|{
_0[_[4],_[5]] for _[4] in range(_[2],_[2]+3)
for _[5] in range(_[3],_[3]+3)
}^{_0[_[0],_[1]]}
it feels so wrong to put int() there, doesn't it?
that's why it's there
XD
i just initialising an int[] array of length 6
and using that for all the local variables
that's more readable to me than what would be considered "readable"
what about functools.reduce?
(lambda: chr(sum(map(lambda i: True,
range(-3 * True + 5 * eval('l' + chr(sum(map(lambda i: True, range(eval(
''.join(
[str(bool.__int__(what)) for what in [True, False, True]])))))) + 'n(str(id(\'id\')))'))
))))()
my first esoteric code
!e
(lambda: chr(sum(map(lambda i: True,
range(-3 * True + 5 * eval('l' + chr(sum(map(lambda i: True, range(eval(
''.join(
[str(bool.__int__(what)) for what in [True, False, True]])))))) + 'n(str(id(\'id\')))'))
))))()
@finite blaze :warning: Your eval job has completed with return code 0.
[No output]
Nope
does it work when writing to string?
It's just because it returns, not prints @grizzled zenith
my memaddr class was messing around with bytes, and only worked for int
hmm
basically write method is the same as in your code
except that im __setattr__ng it
No, it works only with atomic types
!e ```py
import ctypes as c
class memaddr:
init=lambda s,addr:s.setattr("addr",addr)
def write(s,d):
return 0if((lambda a:True if a is None else False)(({
int:c.c_int,
str:c.c_char_p,
bytes:c.c_char_p,
float:c.c_float,
}.get(type(d))).from_address(s.addr+type(d).basicsize).setattr("value",d)))else 1
get=lambda s,t:(t).from_address(s.addr)
repr=lambda s:"[memoryaddr: %s]"%(hex(s.addr),)
class mem_impl:
init=lambda s:s.setattr("cells",[])
def getitem(s,*cls):
with import("contextlib").suppress((SkipExc:=type("SkipExc",(Exception,),{"init":lambda s:None}))):raise[Exception("expected memaddr object, got %s"%(type(c),))if not isinstance(c,memaddr) else SkipExc for c in cls][0]
s.cells=cls[0]if type(cls[0])is tuple else cls
return s
get=lambda s,c:s.cells[c]
repr=lambda s:"[memorypack%s%s]"%(";"if len(s.cells)<1else": "," ".join([c.repr()for c in s.cells]),)
mem=mem_impl()
var = b"Test"
a = memaddr(id(var))
b = mem[a]
print(a, b)
print(b.get(0))
b.get(0).write(b"TEST")
print(var)
@sly root :white_check_mark: Your eval job has completed with return code 0.
001 | [memoryaddr: 0x7f4df32ac6f0] [memorypack: [memoryaddr: 0x7f4df32ac6f0]]
002 | [memoryaddr: 0x7f4df32ac6f0]
003 | b'TP\xc9*'
if the string isnt bytes it will not change
@sly root :white_check_mark: Your eval job has completed with return code 0.
001 | [memoryaddr: 0x7f7efe09e930] [memorypack: [memoryaddr: 0x7f7efe09e930]]
002 | [memoryaddr: 0x7f7efe09e930]
003 | Test
ok I think it's over
it's the start of the day so let's start the daily process: how can I torture python today?
!e ```py
from ctypes import py_object
p = py_object.from_address(id(0)+8)
class Int(p.value):
def pow(self, other):
return'1/'
p.value = Int
print(0**-0)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
1
it's still one
even ctypes agrees
unless this is one of those double dunder operators
!e
print(0**-0)
@sick hound :white_check_mark: Your eval job has completed with return code 0.
1
that's my new favourite way of writing 1
fuck ([]==[])
fatal error is going to be influential on this channel
like that one guy who completely changed how we wrote maths
you see I love this channel so much because we copy someone else's idea to death, until we can actually read it well. we then steal someone else's idea.
!e
print((([]!=[[()]][0])-1)**-0)
@sick hound :white_check_mark: Your eval job has completed with return code 0.
1
is there like
a way to do JS lambda notation through some preprocesser
lambda x: x + 1 is so much more ugly than x => x+1
No 
not without recompiling cpython
i might add something like that to xonsh and do my scripting exclusivity in xonsh
but you could make it so your editor shows you lambda as λ
its like
if i wanna just filter a list I wanna use filter
if i wanna just map a list I wanna use map
but they're always longer
q = list(map(lambda x: 1 + 1, some_list))
q = [i + 1 for i in some_list]
q = list(map(λ x: x+1), some_list) # I'm fine with this
the closest you can get in pure python is λ.x("x + 1")
well yea
theres rlly no way without recompiling? you used to be able to change True to something else
I've seen some solutions on code.golf and they have like 100 characters but 95 bytes. How is this possible?
though it would be pretty funny to have λ.x.y.z("x*y-z")
Hm which language?
thats some metaclass stuff isn't it
python
i could prob implement it; actually dont spoil it
thats why i am asking here ;p
i wanna do that myself later
>>> from toolib.magic import ƒ
>>> list(map(ƒ**2, range(5)))
[0, 1, 4, 9, 16]
ƒ is easy to type on a Mac :P
(but this only works as a single-argument lambda)
does that just interface all functiosn with some metaclass and return a lambda?
every operator except __call__ just returns a composed function
manually?
well it would be convenient with a metaclass to just iterate over a list of dunder methods
My throwaway
!e
print(~~(not ((c:=__import__("cmath")).pi)) ** int(str(not 0.0 and (c.exp(c.sqrt(~0)*c.pi) + ~-2)**24).strip('j')))
@primal idol :white_check_mark: Your eval job has completed with return code 0.
1
import antigravity
so 0100 -> 1011?
!e print(bin(~int("0100", 2)))
@primal idol :white_check_mark: Your eval job has completed with return code 0.
-0b101
okeeey
its because of two's complement
Oh yeah right, that is how it works on ints
Is there an actual not operaotr?
what do you mean by that?
Like Theos expect, in python "1001" & "1010" is "1000", "1001" | "1010" is "1011" and "1101" ^ "1111" is "0010"
so you would expect there to be a not operator
welll
thats ~
its just because of how we choose to interpret it, that it was the effect of - x - 1
Humm, I wonder what would happen if you used ~ on a unsigned ctype
try it
Doing it
hmm
too obvious what its doingw
>>> a = np.uint8(255)
>>> ~a
0
a = 11111111 = 255
~a = 00000000 = 0
numpy has you covered tho :)
True
l,n,p,cd,r,m,ru,wi,t,d,a,b = lambda:True if b[a].count(1)>0 else False,lambda:[i if x!=a else [*[1 for j in range(b[a-1].count(1))],*[0 for j in range(7-b[a-1].count(1))]] for x,i in enumerate(b)],lambda: [i if x!=a else [1 if (b[a-1][j]==1 and b[a][j]==1) else 0 for j in range(7)] for x,i in enumerate(b)],lambda: True if b[a][0]==1 else False if b[a][-1]==1 else None,lambda w:[0]+w[:-1] if d else w[1:]+[0],lambda:[i if x!=a else r(i) for x,i in enumerate(b)],True,__import__("pygame").display.set_mode((350,600)),__import__("time").time(),True,0,[[0,0,1,1,1,0,0],*[[0,0,0,0,0,0,0] for i in range(11)]]
# LINE BREAK HERE --------------------------------
while ru:[[b:=p() if a!=0 else b,a:=a+1,b:=n(),ru:=l()] for event in __import__("pygame").event.get()if event.type == __import__("pygame").KEYDOWN and event.key == __import__("pygame").K_SPACE]+[d := cd() if cd() is not None else d]+[(b:=m(),t:=t+0.1) if __import__("time").time()-t > 0.1 else None]+[wi.fill((255,255,255))]+[__import__("pygame").draw.rect(wi,(0,0,0),(i2*50,i1*50,50,50)) for i1,s in enumerate(b) for i2,e in enumerate(s) if e==1]+[__import__("pygame").display.flip()]
Is this esoteric enough? Fully working game in only 2 lines lol
can you show a screenshot of it running? :O
convert what into one line?
[d := cd() if cd() is not None else d]
could be
[d := cd() or d]
lol I tried but couldn't do it
unless running cd twice is useful
cd stands for change direction
fair enough, i assumed it wouldnt
True direction means block moving to right, false is left
ah :)
hopefully this will be possible soon :)
But you can try converting my code into one line 😄
lol
Actually let me ask one - can we write match-cases in one-liners?
i mean you know, py x if b1 else x2 if b2 else x3 if b3...
works, but how ugly lol
oooh fancy
however anything can be written in 1 line.
.
AnYthInG? Is it proven?
yes.
wow
we should pin it honestly.
it's used semifrequently
like 2 lines without extended use of list comp is still impressive tho
Without what? If this is not extended use of list comp, I don't know what is
[_ for _ in iter(lambda:0,1)] is a cool way to do while True
what does it do exactly? How is iter defined for lambdas?
its essentially an infinite list
actually how many ways are there to make infinite loops with for?
well it's any callable
!d iter
iter(object[, sentinel])```
Return an [iterator](https://docs.python.org/3/glossary.html#term-iterator) object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, *object* must be a collection object which supports the [iterable](https://docs.python.org/3/glossary.html#term-iterable) protocol (the `__iter__()` method), or it must support the sequence protocol (the `__getitem__()` method with integer arguments starting at `0`). If it does not support either of those protocols, [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") is raised. If the second argument, *sentinel*, is given, then *object* must be a callable object. The iterator created in this case will call *object* with no arguments for each call to its [`__next__()`](https://docs.python.org/3/library/stdtypes.html#iterator.__next__ "iterator.__next__") method; if the value returned is equal to *sentinel*, [`StopIteration`](https://docs.python.org/3/library/exceptions.html#StopIteration "StopIteration") will be raised, otherwise the value will be returned.
like the most basic I can think of is py a = [0] for i in a: a.append(0)

__import__("time") is clearly the correct way of doing it smh
i wonder if it would be possible to make a game without whitespace
I would gently say I'm here for you, but hell nah
I think it would, because parantheses don't count as tuples
[(i)for(i)in(range(10))] should work
wtf is that xd
I mean I probably know it in code, but I didn't know this is what it's called
oh so that is list comp
lool
and I believe semi-colon-less and exec-less
@sick hound you can just try and recreate this game in a completely different approach
no then its not even esoteric
send the code
I also have an old piano tiles code in 3 lines, and a game of life in 3 lines, but there, I used import - what a mistake
it worked for a bit
imagine using pygame instead of doing everything on the terminal
wha?
lol cool stuff
import pygame as pg, time as t,random as r
s,g,k,f,kp,ki,u,w = 0.01,[[-1000],[],[],[]],"dfjk",lambda:[g[i][0] if len(g[i]) > 0 else -1000 for i in range(4)],lambda n: g[n].pop(0) if f().index(max(f())) == n else pg.quit(),lambda:[w.fill((255,255,255)),[pg.draw.rect(w,(0,0,0),(id * 100,j,100,200)) for id,i in enumerate(g) for j in i],pg.display.flip()],lambda n=800: [ g[r.randint(0,3)].append(-1000) if min([i for j in g for i in j]) >= -800 else None] + [pg.quit() for j in g if len(j)>0 and j[0]>n],pg.display.set_mode((400,800))
while True:s,g=[[kp(k.index(e.unicode)) for e in pg.event.get()if e.type == pg.KEYDOWN and e.unicode in k],[ki(),u(),t.sleep(s)], s*0.9997,[[i+4 for i in j] for j in g]][-2:]
Now there you go, here is my piano tiles, but it's 3 lines what a shame
you fast bro
Do you want to convert a game of life as well? xd
I mean I could probably do it as well, as I can see you just change thing to walrus, and the while to iter
show us first, then he decides xD
Hey @west cipher!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
thoughts?
dangit the encoding is messed up on the file, whatever should be fine once u download it i think maybe
!e
import sys
sys.rlimit = 1
@lambda c: c
class g:
def __repr__(self):
return repr(h)
def __str__(self):
return "%s" % g
h = g()
def f() -> h: ...
"%s" % f.__annotations__```
@rapid sparrow :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 11, in <module>
003 | File "<string>", line 6, in __repr__
004 | File "<string>", line 6, in __repr__
005 | File "<string>", line 6, in __repr__
006 | [Previous line repeated 330 more times]
007 | RecursionError: maximum recursion depth exceeded while calling a Python object
is there some kind of minimum recursion limit?
and anyone know anything abt the symtable module?
!d symtable
Source code: Lib/symtable.py
Symbol tables are generated by the compiler from AST just before bytecode is generated. The symbol table is responsible for calculating the scope of every identifier in the code. symtable provides an interface to examine these tables.
I would like to know if there's a way to
- get an existing symbol table instead of providing new strings of code to symtable, and
- find a way to relate the function objects in symtable back to a real python function object
the _symtable_symtable function is accessible as symtable._symtable.symtable()
looking at the C, it's this:
PyObject *_symtable_symtable(PyObject *module, PyObject *const *args, Py_ssize_t nargs);
which calls
PyObject *_symtable_symtable_impl(PyObject *module, PyObject *source, PyObject *filename, const char * startstr);
rlimit is wrong? Minimum recursion limit is 4.
!e
import sys
sys.setrecursionlimit(4)
sorted([],key=len)
huh.
Huh, crashes for me locally
thats weird. maybe it changes if interactive?
But in a repl we're probably one or two levels deeper already, yes
interesting
!e I found something that's about halgway to what I'd like to do
import ctypes; import sys; PyFunction_New = ctypes.pythonapi.PyFunction_New; PyFunction_New.restype = ctypes.py_object; PyFunction_New.argtypes = [ctypes.py_object, ctypes.py_object]
def f(arg):
def g(arg2=arg):
print(f"{arg=} {arg2=}")
return g
g_code = next(co for co in f.__code__.co_consts if type(co).__name__ == "code" and co.co_name == "g")
g = PyFunction_New(g_code, f.__globals__)
print(f"{f=}")
print(f"{g=}")
print(f"g()", end="=")
sys.stdout.flush()
print(g("hmm"))```
@rapid sparrow :x: Your eval job has completed with return code 139 (SIGSEGV).
001 | f=<function f at 0x7f9f0e5e0c10>
002 | g=<function g at 0x7f9f0e63a200>
003 | g()=
it's not too surprising that it segfaults there because there was no context created for the g function yet , I guess
another way functions are created, which is passing &f->func_globals which seems kind of odd:
#define PyFunction_AS_FRAME_CONSTRUCTOR(func) \
((PyFrameConstructor *)&((PyFunctionObject *)(func))->func_globals)``` to call:
PyFunctionObject * _PyFunction_FromConstructor(PyFrameConstructor *constr);```
there seems to be a connection between a frame in memory and the globals, somehow
OK, I figured out why it segfaults - it is trying to read sometghing from a closure tuple, but the closure is NULL.
Hey guys, is it possible to write a function, that goes in it's own code, and puts the length of lines in a list? It'd be sick
!d inspect.getsource
inspect.getsource(object)```
Return the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string. An [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError "OSError") is raised if the source code cannot be retrieved.
Changed in version 3.3: [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError "OSError") is raised instead of [`IOError`](https://docs.python.org/3/library/exceptions.html#IOError "IOError"), now an alias of the former.
χ.range(10).reversed.map(Φ ** 2, Ψ).list.reduce(λ.x.y("x - y"), Ψ).print()() # prints -123
i should not be doing this
but i am
xd. Contribute to GanerCodes/Useful_Python_tomfoolery development by creating an account on GitHub.
for {()+(...,):{}}[(...,)+()][()+((),)] in range(4):
pass
```this style of thing can be nested pretty deeply
Unfortunately I don't think you can create an object without __slots__ using non-alnum ascii characters
Otherwise you could also do for thing._
why does w,h=map(int,open(0)) iterate thrice?
i didn't realize python accepted unicode identifiers lol
good lord that's a clever solution
because of how the iterator protocol works. just hit ctrl-d after you enter the two numbers
evening chat
print this in the stupidest way possible
A little girl goes into a pet show and asks for a wabbit. The shop keeper looks down at her, smiles and says:
"Would you like a lovely fluffy little white rabbit, or a cutesy wootesly little brown rabbit?"
"Actually", says the little girl, "I don't think my python would notice."
Oh right, I got it now, I was just confused by the open(0) as the iterable
I have never seen that before
!e
a=lambda:(s:=map.__doc__[17])+(y:=(li()()))(n:=104)+y(n:=n+11)*2+s+str(...)[0].lower()
li=lambda:lambda:lambda lambd=(a):chr([lambd+int(True),None][:-1][0])
print(" ".join([a(),chr(range(int(str(int(True))*2+"5"),0,-1)[2**2**2*2*2-2**2**2+2])][::-1]))
@coarse void :white_check_mark: Your eval job has completed with return code 0.
A little
This is how far I've gotten lol and I thought there is no God I'll have the patience to do this for the whole text lol
@sick hound
!e
print(int('4UKGYCY3P3W1PL5SKAKBDE12NRU29CTIKXBIKHGCMLTNX7HAFPFSPJBMG3WM2CNZR13Q7HM7XDUHWEAZWOLO6OFP6I67MTVYHMLO9KNW81ME11ERBZ0PQMLLKCK0DC5FMQ1NU2NA5GW14P1TZU2NSHG0JEAT0EAI6LC5RPBW453J3YVUD3UWPI9TFH63JC0ISSTEPSDLG87SPJ1NJ3S0CYAAH5UO4NO09TQ2OONV24SV9LRDZWKM0ERHR2AZCP4G059QLYE8AZRXD1KBNFD8LE4KGGESKRGLATA7CAWNM7RR8SDELA2NZXOO938HHVE5B2H25UH23QN7DC7EY3SIEWJZOCW0AQN78VBWWQSYAP549BLYD6X053WFIVPJQTPYYUMB743WC7H1B4Z3MJZ7VK4EHZ3RBK5JH25XWUUPVBK6AEEINMQ',36).to_bytes(281,'big').decode())
@restive void :white_check_mark: Your eval job has completed with return code 0.
001 | A little girl goes into a pet show and asks for a wabbit. The shop keeper looks down at her, smiles and says:
002 |
003 | "Would you like a lovely fluffy little white rabbit, or a cutesy wootesly little brown rabbit?"
004 |
005 | "Actually", says the little girl, "I don't think my python would notice."
bit boring
I've almost worked out of way to turn little into x^2
and do you like mine? xd
I do
!e
import random
def get_largest_factor(i: int) -> str:
for h in range(i // 2, 0, -1):
if not i % h:
return h
return 1 # stop pylint from complaining
def get_int_as_true(i: int, self=None) -> str:
if i == 0:
return '~True'
elif i == 1:
return 'True'
elif i == 2:
return random.choice(['True << True', 'True + True', '-~True'])
elif i < 0:
return '-(' + get_int_as_true(-i) + ')'
else:
c = random.randint(0, 10)
rand = random.randint(0, i)
if c in range(7):
factor = get_largest_factor(i)
if factor == 1:
return f'-~({get_int_as_true(i-1)})'
return f'({get_int_as_true(factor)}) * ({get_int_as_true(int(i / factor))})'
else:
return f'-~({get_int_as_true(i-1)})'
def true_convert(string: str) -> str:
res = ''
for char in string:
res += f'chr({get_int_as_true(ord(char))}) + \n'
return res[:-3]
if __name__ == '__main__':
print(true_convert("python"))
@near gust :white_check_mark: Your eval job has completed with return code 0.
001 | chr(-~((-~(-~((-~((-~(-~True)) * (True << True))) * (-~((True << True) * (True << True)))))) * (-~(True << True)))) +
002 | chr((-~((-~(-~(-~(-~True)))) * (True + True))) * (-~((-~((-~True) * (True << True))) * (True + True)))) +
003 | chr(((-~(-~((-~(((True + True) * (True << True)) * (True + True))) * (-~(True + True))))) * (-~True)) * (-~True)) +
004 | chr((((-~(((-~(True + True)) * (True << True)) * (True << True))) * (-~True)) * (True << True)) * (True << True)) +
005 | chr((-~(((-~(-~(-~((-~(-~True)) * (-~True))))) * (True + True)) * (True + True))) * (-~(True << True))) +
006 | chr((-~(-~(-~(((-~(((-~(True << True)) * (-~True)) * (True + True))) * (True + True)) * (-~True))))) * (True << True))
oops forgot to remove the newline
oh hey there. wasn't expecting to to see you here
bonus points for smiley faces in your code
[:-3]
honestly true_convert should've been a list comprehension
yes
I was originally going to convert the string into binary and generate the Trues based on the bits, but that was stupid
replace True with 0**0
How would you implement in seeding in Python?
Specifically protocols, like xmur3 and sfc32
https://github.com/GanerCodes/Useful_Python_tomfoolery/blob/master/main.py
print('e' * χ.range(φ['k']('x * 10')).len()(k = 3))
print((Φ * 10)(2))
print(ζ("x**y + v")(2, 5, v = 5))
print(λ.a.b.c("str(a) + str(b) + str(c) + x * 15")(2, 3, 4, x = "xd"))
pjmap(χ(ρ[0]).ƒ(Φ ** 3 + 7).str(), range(5))
pjmap(Φ * 10, range(5))
pjmap(Φ ** 3 + 7, range(20))
pjmap(λ.x("x * 10"), range(5))
pjmap((Φ ** 2)._str_()[::-1], range(9))
χ.range(10).reversed.map(Φ ** 2, Ψ).list.reduce(ζ("x - y"), Ψ).print()()
χ(5).range(Ψ).map((Φ ** 3 + 7)._str_(), Ψ('x[::-1]')).ƒ(''.join).print()(5)
thoughts?
looks like discount avl
APL? sorta the style i was going for lol
but i wanted to keep it useful and still valid python syntax
meant apl
autocorrect loves trees apparently
what the hell
hmmm i have an idea
says he has an idea
doesn't elaborate
leaves
sigma grindset
right my idea has been developed
it is a golfing tournament
essentialyl
def game_problem(x,y):
for selection in range(0,1):
functions = [x,y]
game_table = {
(0,0) : (rand(0,5),rand(0,5)),
(1,0) : (rand(0,5),rand(0,5)),
(0,1) : (rand(0,5),rand(0,5)),
(1,1) : (rand(0,5),rand(0,5)),
}
choice_a = functions[0](game_table,selection)
choice_b = functions[1](game_table,not selection)
results = game_table[(choice_a,choice_b)]
return (results[0],results[1])
this is a non esoteric function that does a game theory table
it gives both function_a and function_b 2 variables: the table, and the order.
so essentially, you need to write a function that selects the choice (either quiet or fink for the above) that will gve them the highest score out of 100 rounds. their score being the amount of points they get out of the table
how fun would it be if * character didn't count as a byte?
and how much would that effect the code?
omg
!e (t:="") and eval(''.join(chr(int(''.join(map(lambda x:str("".index(x)),t[i:i+8])),2))for i in range(0,len(t),8)))
@west cipher :white_check_mark: Your eval job has completed with return code 0.
hi
interesting
of this one
dang that obvious
i should come back and obfuscate more at some point
add some red harrings so its impossible to realize
also on an unrelated note it would be way too easy to trick someone into running a whitespace based eval
!e (t:="") and eval(''.join(chr(int(''.join(map(lambda x:str("".index(x)),t[i:i+8])),2))for i in range(0,len(t),8)))
@west cipher :white_check_mark: Your eval job has completed with return code 0.
['Pipfile.lock', 'Pipfile', 'config', 'snekbox', 'user_base', 'tests', 'LICENSE']
!e (t:='0123456789') and eval(''.join(chr(int(''.join(c.index(x).str()for x in t[i:i+8]),2))for i in range(0,len(t)-10,8)if bool(c:='')|bool(t:=''.join(filter(c.contains,t)))))
@west cipher :white_check_mark: Your eval job has completed with return code 0.
['Pipfile.lock', 'Pipfile', 'config', 'snekbox', 'user_base', 'tests', 'LICENSE']
what
(t:='1576408392')and eval(''.join(chr(int(''.join(c.index(x).__str__()for x in t[i:i+8]),2))for i in range(0,len(t)-10,8)if bool(c:='')|bool(t:=''.join(filter(c.__contains__,t)))))
yall should run this
!e (t:='1576408392')and eval(''.join(chr(int(''.join(c.index(x).str()for x in t[i:i+8]),2))for i in range(0,len(t)-10,8)if bool(c:='')|bool(t:=''.join(filter(c.contains,t)))))
@finite blaze :warning: Your eval job has completed with return code 0.
[No output]
why is it cut
!e
(t:='1576408392')and eval(''.join(chr(int(''.join(c.index(x).__str__()for x in t[i:i+8]),2))for i in range(0,len(t)-10,8)if bool(c:='')|bool(t:=''.join(filter(c.__contains__,t)))))
@finite blaze :warning: Your eval job has completed with return code 0.
[No output]
!e (t:="") and eval(''.join(chr(int(''.join(map(lambda x:str("".index(x)),t[i:i+8])),2))for i in range(0,len(t),8)
@lime smelt :x: Your eval job has completed with return code 1.
Code block escape attempt detected; will not output result
Full output: https://paste.pythondiscord.com/afecamagic.txt?noredirect
it feels like an oversight that you can't match an ellipsis in structural pattern matching. You have to bind a variable and then test if it is Ellipsis
class range:
def __new__(cls, *args):
if ... in args:
match args:
case (start, e, stop) if e is ...:
return __builtins__.range(start, stop + 1)
case (start, other, e, stop) if e is ...:
ret = __builtins__.range(start, stop + other - start, other - start)
if stop not in ret:
raise ValueError("Invalid Ellipsis range")
return ret
case (start, e, other, stop) if e is ...:
ret = __builtins__.range(start, 2*stop - other, stop - other)
if stop not in ret:
raise ValueError("Invalid Ellipsis range")
return ret
return __builtins__.range(*args)
and using the name Ellipsis rebinds a local variable
looking for genuine advice
does this code look dirty to anyone?
i find it neat yet my friend dont
just rate it for neatness
/10
class CustomDict(dict):
def __setitem__(self, key, value):
if key in self.keys():
new = [self[key], value] if not isinstance(self[key],list) else self[key] + [value]
dict.__setitem__(self, key, new)
else: dict.__setitem__(self, key, value)
class overloads(type):
def __prepare__(name, bases):
return CustomDict()
def __new__(cls, name, bases, dct):
def choose(lst):
annotate = [list(fn.__annotations__.values()) for fn in lst]
def wrapper(*args):
for num , a in enumerate(annotate):
check = [type(arg) == annotation for arg, annotation in zip(list(args)[1:], a)]
if all(check): return lst[num](*args)
return None
return wrapper
edited_dct = {}
for key, value in dct.items():
if isinstance(value, list) and callable(value[0]): edited_dct[key] = choose(value)
else: edited_dct[key] = value
return type(name, bases, edited_dct)
class Funcs(metaclass=overloads):
def add(self, a: int, b: int): return a + b
def add(self, a: str, b: str): return f'{a} {b} it worked!'
def add(self, a: int, b: str): return b*a
no that isn't what i meant. but, what i meant is that theres... clues. mostly the chr part
stop
you're not healthy
most lambdas would become variadic
also there is now a maximum score that any possible challenge can take on
!e print("123")
@fleet bridge :warning: Your eval job has completed with return code 0.
[No output]
!e ```py
s = '`'
print(s * 3 + '!' + s * 3)
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
Code block escape attempt detected; will not output result
Full output: https://paste.pythondiscord.com/hoxeyadeqo.txt?noredirect
hmmm
we are going to break it.
if ESCAPE_REGEX.findall(output):
paste_link = await self.upload_output(original_output)
return "Code block escape attempt detected; will not output result", paste_link
found the code that manages that.
ESCAPE_REGEX = re.compile("[`\u202E\u200B]{3,}")
no idea what this is doing tho...
ah nvm i understand.
so its checking for 3 repetitions of the backtick
hmm.
its impossible.
sad
!e print("Code block escape attempt detected; will not output result")
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
Code block escape attempt detected; will not output result
exec("""print((l:=["print", "('<{}>>')", "format"])[0],[1],f"{l[0]}.format('[({l})==({l})]'.join(l))")""")
!e
exec("""print((l:=["print", "('<{}>>')", "format"])[0],[1],f"{l[0]}.format('[({l})==({l})]'.join(l))")""")
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
print [1] print.format('[(['print', "('<{}>>')", 'format'])==(['print', "('<{}>>')", 'format'])]'.join(l))
funny
you see it looks like a complete mess of code and outputs a complete mess of code
i know you can do this : )
!e
print ("`\u200b`\u200b`\u200a")
@near gust :white_check_mark: Your eval job has completed with return code 0.
Code block escape attempt detected; will not output result
Full output: https://paste.pythondiscord.com/epigerawoh.txt?noredirect
!e
print("``\u200a`")
@near gust :white_check_mark: Your eval job has completed with return code 0.
`` `
!e
print("``\u200b`")
@near gust :white_check_mark: Your eval job has completed with return code 0.
Code block escape attempt detected; will not output result
Full output: https://paste.pythondiscord.com/icoqaxebop.txt?noredirect
interesting
🙂
You can break out of it btw, it's a known issue
with how discord handles large amounts of escape sequences
@vague cairn :white_check_mark: Your eval job has completed with return code 0.
!e `print("hello world!")`
Ok, so that's not what you're worrying about happening, what is the problem and the strategy that you're investigating?
@dense skiff :x: Your eval job has completed with return code 1.
001 | File "<string>", line 2
002 | print("
003 | ^
004 | SyntaxError: unterminated string literal (detected at line 2)
!e
print("```this?```")
@dense skiff :white_check_mark: Your eval job has completed with return code 0.
\`\`\`this?
lmao
xd
Acceptable
@sick hound :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | print("
003 | ^
004 | SyntaxError: unterminated string literal (detected at line 1)
@sick hound :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | print("
003 | ^
004 | SyntaxError: unterminated string literal (detected at line 1)
!e print("`"*(2**8))
@finite blaze :white_check_mark: Your eval job has completed with return code 0.
Code block escape attempt detected; will not output result
Full output: https://paste.pythondiscord.com/emixezusup.txt?noredirect
Stuff trying to break the bot should be going in #bot-commands please
This channel is for esoteric python, not bot testing
!e
f=1 .__and__
print(f(3))
@severe canyon :white_check_mark: Your eval job has completed with return code 0.
1
its very esoteric
!e
wait you can access int methods by adding a space
also dot notation works with a space
how am i still learning about this langauge
!e ```py
print(chr(((~~(l:=lambda:(f:=~(((lambda x:3x)(((f:=lambda:7)()).and(2^63))))))())-630)+4))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
❤
❤️
Space because otherwise the dot is treated as a continuation of the number
need to learn about all these __thingy__
https://docs.python.org/3.10/reference/datamodel.html
almost all __dunder__ methods are described in this page
thanks
https://www.toptal.com/developers/hastebin/iyayemadiw.md
this is a list of all __dunders__ that are mentioned in docs
I have rearranged this list a little
i haven't really experimented with pattern matching, anyone know some weird stuff you can do with it?
I tried, but it's fairly stubborn; __match_args__ must be a tuple.
Most notations work with any sort of spacing
@type.__call__
class rm:
def __sub__(s,o):
import os
os.system(f"[insert the rm command here, retracted for safety] {o}")
# ...
rm -rf"/"
that's a good way to recreate ruby blocks in python lol
made new dsl
@use structures;
@use datetime;
struct human {
name: str
age: int
born: datetime.timedelta
};
this gets parsed to
{
'name': 'human',
'fields': {
'name': <class 'str'>,
'age': <class 'int'>,
'born': <class 'datetime.timedelta'>
}
}
integrated with my structures snippet:
>>> human["",0,datetime.timedelta(days=0)]
<structure human, {'name': '', 'age': 0, 'born': datetime.timedelta(0)}>
>>>```
use keyword is just literally __import__
why not a dataclass
they're too overcomplicated, when my implementation is just one class
also this is #esoteric-python channel so i think channel name explains why :)
heh, fair point
!e
for type(
type.__name__,
(),
{
type.__name__: type(
type.__name__,
(),
{
"__{0}__".format(
type({0}).__name__
): lambda * type: print(type[(type==type)+(type==type)])
},
)(),
},
)().type in range(7): pass
@restive void :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
hey people, im just curious, how did you get into esoteric py? i didnt even know it existed, did you guys want an extension of python for a challenge? or?
I didn't know it had a name, but I've always liked breaking things, or using them in unintended ways. Made esoteric languages before, too (before even knowing about Python).
Also I miss doing art in my job :D
Ohh wow that’s so cool, so does mean only you will understand your code? Or are there certain syntax’s with esoteric that known amongst others?
There's a whole community of people making esolangs, see esolangs.org
My most mature ones are OIL and Aceto, they are easy to understand in principle, just hard to write.
Wow, that’s super cool, I’ll definitely check it out. And these esolangs can be implemented like any standard Lang right?
I think there are some that can't, but mine are all implemented at least once
@sick hound :white_check_mark: Your eval job has completed with return code 0.
12
@finite blaze :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | print((* +2 +2))
003 | ^^^^^^^
004 | SyntaxError: cannot use starred expression here
Naaah
adding a comma to make it a tuple would work (apart from the type error)

!e ```py
globals().clear()
builtins={}
no brackets after this
build_class=lambda*a:0
name='main'
sub = ....class.base.subclasses
@sub.class.call
@lambda _:sub
class a:0
try:
@a.getitem
@lambda _:84
class b:0
a.load_module
except:
@a.getitem
@lambda _:104
class b:0
@b.load_module
@lambda _:'sys'
class a:0
@a.stdout.write
@lambda _:"Hello World!\n"
class a:0
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
honestly I think that obfuscating code is best when the output is completely expected
ok
In a function's __code__ attribute, where are the argument names located?
!e ```py
def foo(a, b):
pass
print(foo.code.co_varnames)```do you mean this?
@last locust :white_check_mark: Your eval job has completed with return code 0.
('a', 'b')
>>> def foo(a, *, b, c=None):
pass
>>> foo.__code__.co_varnames
('a', 'b', 'c')```note that it doesn't distinguish between different types of args
That seems to be what I'm looking for, thanks!
The reason is kinda cursed so that's why I'm here
Heh
something like:
def decorate(...):
...
@decorate(3):
def f():
return a+b+c
print(f(1,2,3))#6
should be relatively easy to implement
!e ```python
def foo(a, b):
x = 123
print(foo.code.co_varnames)``` it is not only arguments
@polar plover :white_check_mark: Your eval job has completed with return code 0.
('a', 'b', 'x')
!e from what can tell the arguments are orderd first in that tuple, so ```py
def foo(a, b):
x = 123
print(foo.code.co_varnames[:foo.code.co_argcount])```
@polar plover :white_check_mark: Your eval job has completed with return code 0.
('a', 'b')
I suggest using inspect here
!e
for i in range(100):globals()[f'sh{"e"*i}sh']=i
print(shsh)
print(sheesh)
print(sheeeeesh)
@severe canyon :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 2
003 | 5
why do i find this funny
!e
LETTER = lambda x:chr(x + ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss0)
letter = lambda x:chr(x + ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss0)
letters = lambda *xs:''.join([letter(x) for x in xs])
Letters = lambda *xs: LETTER(xs[0]) + letters(*xs[1:])
print(Letters(ssssssss0, sssss0,ssssssssssss0,ssssssssssss0,sssssssssssssss0, -ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss0, sssssssssssssssssssssss0, sssssssssssssss0, ssssssssssssssssss0,ssssssssssss0,ssss0,-sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss0))
looks like peano arithmetic to me.
@vague cairn :white_check_mark: Your eval job has completed with return code 0.
Hello world!
🐍
looks like the start of a new obfuscation class: you get two '1's and as many '0's as you want, but no other digits...
!e
actually... the first '1' is easy to replace with True, the second shouldn't be very much more difficult...
You could just implement Unary https://esolangs.org/wiki/Unary
!e
f=lambda i:'0'*int(f'1{"".join("{0:03b}".format("><+-.,[]".index(l))for l in i)}',2)
print(len(f(",[.,]")))
@severe canyon :white_check_mark: Your eval job has completed with return code 0.
56623
brainfuck to unary converter :D
please golf this more
nvm this doesnt actually work
ok, now it should
Hi
I have a question about threading
I use
threadName.start()
To start the thread but i dont know how to stopeed
Someone can help me?
#❓|how-to-get-help Please read the rules
!e
f=lambda i,a=0:'0'*([a:=a*8+"><+-.,[]".index(l)for l in i][-1]+2**len(i*3))
print(len(f(",[.,]")))
@severe canyon :white_check_mark: Your eval job has completed with return code 0.
56623
shorter ¯_(ツ)_/¯
Oh, im sorry
Can't you make it a oneliner?
it is
It's two different scripts, the preprocessor and the driver.
They could be concatenated or intermingled, but that would be pointless.
It’s just one of the attributes of the compiled bytecode
can you get around this?
Is the error trying to assign to __code__ or to co_code because for the latter you can just replace(...) and assign the copied code object instead
!e ```py
def foo(): print("hey")
foo.code = foo.code.replace(co_consts=(None, "hi there"))
foo()
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
hi there
ty
!e
f=lambda n:n*n
n=bytes([124,0,124,0,23,0,83,0])
print(f(3))
f.__code__ = f.__code__.replace(co_code=n)
print(f(3))
@severe canyon :white_check_mark: Your eval job has completed with return code 0.
001 | 9
002 | 6
fun!, gonna mess around with this
!e
print("Hello")
whats co code?
bytecode of the function
damn, the dis module gives you a lot of info to work with
all bytecode opcodes and disassembly of functions :O
!e
import dis
f=lambda n:1if n<2else f(n-1)*n
print(dis.dis(f))
@severe canyon :white_check_mark: Your eval job has completed with return code 0.
001 | 2 0 LOAD_FAST 0 (n)
002 | 2 LOAD_CONST 1 (2)
003 | 4 COMPARE_OP 0 (<)
004 | 6 POP_JUMP_IF_FALSE 6 (to 12)
005 | 8 LOAD_CONST 2 (1)
006 | 10 RETURN_VALUE
007 | >> 12 LOAD_GLOBAL 0 (f)
008 | 14 LOAD_FAST 0 (n)
009 | 16 LOAD_CONST 2 (1)
010 | 18 BINARY_SUBTRACT
011 | 20 CALL_FUNCTION 1
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/goyuluzika.txt?noredirect
https://sourceb.in/w7aXsAQN5VOkay this is my filetree and I have a function called timestamps_av in my info.py file but when I do from .info import timestamps_av,fromcogs .info import timestamps_av or from info import timestamps_avin events.py it errors telling me it can't find it
(Also asked in #discord-bots a few mins ago but thought this might be better place to ask)
this channel is for doing cursed shit with python, not a good fit for your question
also your source bin link doesn't work
yep ik the link died, managed to get a answer in #discord-bots but couldn't really find a general python help channel which is why i posted it here
yeah I also tried those help channels (twice) and the bot flagged them as dormant bc a response took so long
good to know.
how to generate primes
[i for i in range(2,100) if i in (2,3,5,7) or (i%6==1 or i%6==5) and i%5!=0 and i%7!=0]
!e ```py
[i for i in range(2,100) if i in (2,3,5,7) or (i%6==1 or i%6==5) and i%5!=0 and i%7!=0]
@gleaming timber :warning: Your eval job has completed with return code 0.
[No output]
!e ```py
print([i for i in range(2,100) if i in (2,3,5,7) or (i%6==1 or i%6==5) and i%5!=0 and i%7!=0])
@gleaming timber :white_check_mark: Your eval job has completed with return code 0.
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
!e ```py
print(*filter(lambda i:i in(2,3,5,7)or(i%6 in(1,5))and i%5 and i%7,range(2,100)))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
!e
print(2,3,5,7,*[i for i in range(2,100)if(i%6 in(1,5))and not(i%5==0 or i%7==0)])
@gleaming timber :white_check_mark: Your eval job has completed with return code 0.
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
!e ```py
print(2,3,5,7,*filter(lambda i:all([(i%6 in(1,5)),i%5,i%7]),range(2,100)))
mine's shorter
almao what
don't need a list with all
you can pass a generator/iterable i forgot what it's calle
!e
print(2,3,5,7,*filter(lambda i:all((i%6 in(1,5)),i%5,i%7),range(2,100)))```
@jovial monolith :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | File "<string>", line 1, in <lambda>
004 | TypeError: all() takes exactly one argument (3 given)
UHH
told you
oh i misread it xD
@sick hound :white_check_mark: Your eval job has completed with return code 0.
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
@sick hound :white_check_mark: Your eval job has completed with return code 0.
2 3 5 7 1 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
You know how std[::cout] << "Hello World!"? I took it another step further because I was bored in class today.
https://paste.pythondiscord.com/useserajac.rb
std[::vector]<int,_> 'a';
a.push_back(10);
a.push_back(1);
a.push_back(69420);
for i in a:
std[::cout] << i << " ";
std[::cout] << '\n'
now with templates (kinda not really)
@sick hound :warning: Your eval job has completed with return code 0.
[No output]
nothing happened
Hey, what would be the shortest way to open a file and save all lines into a list
with all lines stripped
x=[*map(str.rstrip,open("i"))]
x=[l.rstrip()for l in open("i")]
hmm it's actually longer
wait no it's shorter the chat textbox was just bad
thanks
why rstrip and not strip?
rstrip only strips from the right, hence the r prefix
Whitespace at the beginning of a line could be indentation etc
full stripping is usually desired, however not when indents could be important
I'm almost done with a version that can have nested templates
it required a complete redo of the template code by making template_base a metaclass
and doing other stuff
template<(T, template<(U, V),_>_), _>'name'
what does H mean
no, that's U+1D129 𝄩
std[::vector]<int,_>'vec',_ == {1, 2, 3}
std[::vector]<int,_>'vec',_('iterator', 'constructor here')
time to implement the actual vector interface
oh god
iterators
having to hack ++i
chained comparison
also that would try to call the string
operator precedence
I also tried == directly but that doesn't work because of chained comparison
_ is a temp variable that here gets assigned to be the class object
template_meta.__gt__(self, other: typing.Union[str, template_meta]) returns the class if both sides are the same object, otherwise assigns the namespaces variable of that name to the class
then == calls __call__, which constructs an instance of the class with the args. If self._var is defined on the class (which it is defined when there's a call to > when the right argument is not self), it sets the variable named by that variable to be the instance of the class and returns the instance (the same object)
print((lambda: getattr(getattr, '__name__')[0])() + __import__('string').ascii_lowercase[0 << 69] + getattr(any, '__name__')[int(hex(343433234222)[((-2 << 2) / 4).__int__()])])
made it myself 🙂
!e print((lambda: getattr(getattr, 'name')[0])() + import('string').ascii_lowercase[0 << 69] + getattr(any, 'name')[int(hex(343433234222)[((-2 << 2) / 4).int()])])
@finite blaze :white_check_mark: Your eval job has completed with return code 0.
gay

!e
print((lambda: getattr(getattr, '__name__')[0])() + __import__('string').ascii_lowercase[0 << 69] + getattr(any, '__name__')[int(hex(343433234222)[((-2 << 2) / 4).__int__()])])
@rough mulch :white_check_mark: Your eval job has completed with return code 0.
gay
aww the very misleading pair of messages got deleted
how
it's called obfuscation
🧐
unary pos the first time on the iterator will return a proxy object, and then calling unary pos again on the proxy will increment
cant even understand single line
it smg convert 343433234222 to msg
!e then there's the opposite:
@type.__call__
class cout:
def __lshift__(self, string):
print(string)
return self
endl = '\n'
cout << "Hello World!" << endl;
epic
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
i can do this simply
!e
print("Hello World!")
@rough mulch :white_check_mark: Your eval job has completed with return code 0.
Hello World!
😂
getattr(getattr, '__name__')[0] gets the first character of 'getattr'
ok
0 << 69 is 0
ok
first ascii lowercase character is a
__import__('string').ascii_lowercase[0 << 69] + getattr(any, '__name__')[int(hex(343433234222)[((-2 << 2) / 4).__int__()])])
```???
and the crazy integer stuff simplifies to 2
ok..
so the third character of "any"
..
Quad Et Deobfuscatum
i have no idea
interview bl:
Print("Hello")
make it so complex that anyone cant understand lol
who likes my abuse of Latin?
Didnt understand
-2th index is '2'
!e
print(getattr'[0] + 'abcdefghijklmnopqrstuvwxyz'[0] + 'any'[int('0x4ff637472e'[-2])])
@rough mulch :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | print(getattr'[0] + 'abcdefghijklmnopqrstuvwxyz'[0] + 'any'[int('0x4ff637472e'[-2])])
003 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
004 | SyntaxError: invalid syntax. Perhaps you forgot a comma?
lol
`oh
!e
'getattr'[0] + 'abcdefghijklmnopqrstuvwxyz'[0] + 'any'[int('0x4ff637472e'[-2])]
@rough mulch :warning: Your eval job has completed with return code 0.
[No output]
!e ```py
a, i = [0,0,0,0,0,0], 0
a[i] = a[i] + 10
while a[i]:
i += 1
a[i] = a[i] + 3
i += 1
a[i] = a[i] + 7
i += 1
a[i] = a[i] + 8
i += 1
a[i] = a[i] + 10
i += 1
a[i] = a[i] + 11
i -= 5
a[i] = a[i] - 1
i += 2
a[i] = a[i] + 2
print(end=chr(a[i]))
i += 2
a[i] = a[i] + 1
print(end=chr(a[i]))
a[i] = a[i] + 7
print(end=chr(a[i])*2)
i += 1
a[i] = a[i] + 1
print(end=chr(a[i]))
i -= 4
a[i] = a[i] + 2
print(end=chr(a[i]))
i += 2
a[i] = a[i] + 7
print(end=chr(a[i]))
i += 2
print(end=chr(a[i]))
a[i] = a[i] + 3
print(end=chr(a[i]))
i -= 1
print(end=chr(a[i]))
a[i] = a[i] - 8
print(end=chr(a[i]))
i -= 3
a[i] = a[i] + 1
print(chr(a[i]))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
huh
!e
print(__builtins__.str().join(map(chr,[q:=-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0,u:=-~-~-~-~q,u-ord('>')//(-~-~-~0),sum(map(ord, filter(lambda m: isinstance(ord(m), int), list('%>')))),u-(-~-~-~-~-~-~-~-~-~-~0)])))
@terse oriole :white_check_mark: Your eval job has completed with return code 0.
quack
That... worked?
woah
google?
!e
getattr'[0] + 'abcdefghijklmnopqrstuvwxyz'[0] + 'any'[int('0x4ff637472e'[-2])]
@rough mulch :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | getattr'[0] + 'abcdefghijklmnopqrstuvwxyz'[0] + 'any'[int('0x4ff637472e'[-2])]
003 | ^
004 | SyntaxError: unterminated string literal (detected at line 1)
hec
!e
'getattr'[0] + 'abcdefghijklmnopqrstuvwxyz'[0] + 'any'[int('0x4ff637472e'[-2])]
@rough mulch :warning: Your eval job has completed with return code 0.
[No output]
I typed the damn thing manually
imposibble
although I could make a script to generate that given any message
how u learned it
I made it
what is it called
!e
(lambda _, __, ___: (lambda p, ____________________, ___: [print(__import__('this').d.get(____, ____), end='', file=p) for ____ in ___])(__.stdout, setattr(__, 'stdout', open(_.devnull, 'w')), ___))(__import__('os'), __import__('sys'), 'frperg zrffntr')
@terse oriole :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | File "<string>", line 1, in <lambda>
004 | FileNotFoundError: [Errno 2] No such file or directory: '/dev/null'
This is based on the concept of a Turing Machine
Doesnt work in here...
Works fine in an IDLE shell I think?
however I only used 6 memory cells so it isn't Turing Complete
..
the concept behind it is turing complete though
what are these use for
it is a transpilation from python to brainfuck, and back to python again
manually
that's kinda what this channel is for
lol
@floral meteor print 5 table with 1 line
!e Yo how's this workin
print(__builtins__.str().join(map(chr,[q:=-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0,u:=-~-~-~-~q,u-ord('>')//(-~-~-~0),sum(map(ord, filter(lambda m: isinstance(ord(m), int), list('%>')))),u-(-~-~-~-~-~-~-~-~-~-~0)])))
@maiden river :white_check_mark: Your eval job has completed with return code 0.
quack
huh
🪐 . .✦˚ . ✦˚ . ˚ . ✦ ˚ .🌍
˚ . ✦ . ˚ * ✦ . . ˚
. ✦ 🌒 . ˚ .
yoooooo
i was searching for this status for soo long
inderesdin
!e
print(__builtins__.str().join(map(chr,[q:=-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0,u:=-~-~-~-~q,u-ord('>')//(-~-~-~0),sum(map(ord, filter(lambda m: isinstance(ord(m), int), list('%>')))),u-(-~-~-~-~-~-~-~-~-~-~0)])))```
@rough mulch :white_check_mark: Your eval job has completed with return code 0.
quack
!e
print(__builtins__.str().join(map(chr,[s:=-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0,u:=-~-~-~-~q,u-ord('>')//(-~-~-~0),sum(map(ord, filter(lambda m: isinstance(ord(m), int), list('%>')))),u-(-~-~-~-~-~-~-~-~-~-~0)])))```
@rough mulch :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'q' is not defined
!e
print(__builtins__.str().join(map(chr,[s:=-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0,u:=-~-~-~-~s,u-ord('>')//(-~-~-~0),sum(map(ord, filter(lambda m: isinstance(ord(m), int), list('%>')))),u-(-~-~-~-~-~-~-~-~-~-~0)])))```
@rough mulch :white_check_mark: Your eval job has completed with return code 0.
quack
hec?
% precedence is higher than +
woops
infinet memeree
!e
print(-~0)
@terse oriole :white_check_mark: Your eval job has completed with return code 0.
1
Basically increments it so much that it reaches the ord value of the characters
This one doesnt seem to work mainly cause of snekbox
It somewhat works in terminal and works as intended in an IDLE shell
this is me tryna make my code more readable:
Readable is relative...
the lambda list is one of those "works for the wrong reason" things
@sly root :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | ModuleNotFoundError: No module named 'requests'
pog
@sly root ❌ Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | BotUsageError: Please use #bot-commands for non-esoteric bot commands.
i've tried to execute esoteric code(
the bot knows what's esoteric and what isn't ?
ik, full code is too big for discord
i tried to load it with request but module is not installed
today I learned that ... is an operator... that's pretty neat
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
Ellipsis
You can use it as expression like any other expression
!e ```py
print(....lt(...))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
NotImplemented
dumb idea to abstract away ANSI escape sequences
class _escape_sequence:
def __init__(self, item):
self._s='\x1b['+str(item).replace('(','').replace(')','').replace(',',';')
def __getattribute__(self, attr):
try:return super().__getattribute__(attr)
except:return self._s+attr
@type.__call__
class x1b:
def __getitem__(self, item):
return _escape_sequence(item)
print(\
x1b[32].m + "Green text." + \
x1b[0].m)
any escape sequence works
this is so, so true
!e
def argumentwrap(x):
args=[x.__annotations__['f'](i)for i in range(x.__annotations__['n'])]
argcount=len(args)
co_names=tuple(i for i in x.__code__.co_names if not i in args)
co_varnames=tuple(i for i in args)+tuple(i for i in x.__code__.co_varnames if i not in[*'nf'])
co_consts=tuple(i for i in x.__code__.co_consts if i!=x.__doc__)
co_code=''
for i in range(0,len(x.__code__.co_code),2):
if x.__code__.co_code[i]==124:
co_code+='|'+chr(co_varnames.index(x.__code__.co_varnames[x.__code__.co_code[i+1]]))
elif x.__code__.co_code[i]==116:
if x.__code__.co_names[x.__code__.co_code[i+1]] in args:
co_code+='|'+chr(co_varnames.index(x.__code__.co_names[x.__code__.co_code[i+1]]))
else:
co_code+='t'+chr(co_names.index(x.__code__.co_names[x.__code__.co_code[i+1]]))
elif x.__code__.co_code[i]==100:
co_code+='d'+chr(co_consts.index(x.__code__.co_consts[x.__code__.co_code[i+1]]))
elif x.__code__.co_code[i]==125:
co_code+='}'+chr(co_varnames.index(x.__code__.co_varnames[x.__code__.co_code[i+1]]))
elif x.__code__.co_code[i]==160:
co_code+='\xa0'+chr(co_names.index(x.__code__.co_names[x.__code__.co_code[i+1]]))
else:
co_code+=x.__code__.co_code[i:i+2].decode(x.__doc__)
co_code=co_code.encode(x.__doc__)
co_nlocals=len(co_varnames)
return type(lambda:0)(x.__code__.replace(co_argcount=argcount,co_names=co_names,co_varnames=co_varnames,co_consts=co_consts,co_code=co_code,co_nlocals=co_nlocals),globals())
@argumentwrap
def f(n:3,f:lambda i:chr(i+97)):
'iso-8859-1'
print(a,b,c)
f(1,'2',None)
@golden finch :white_check_mark: Your eval job has completed with return code 0.
1 2 None
anyone done something like this before?
uhhhh no?
!e
raise_ = lambda ack:(_ for _ in [1]).throw(Exception(ack))
try:
raise_('qu')
except Exception as e:
a = str(e)
b = ''.join(__import__('inspect').signature(raise_).parameters)
print(a+b)
@terse oriole :white_check_mark: Your eval job has completed with return code 0.
quack
anonymousdeveloper: writes some obscure bytecode hack
also anonymousdeveloper: "You should've done this before, anybody would do it"
why do I keep making print quack code...
how do I make this worse?
(()for()in()).throw
oh god
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | File "<string>", line 1, in <genexpr>
004 | Exception: XD
!e
raise_=lambda ack:(()for()in()).throw(Exception(ack))
try:
raise_('qu')
except Exception as e:
a=__builtins__.str(e)
b=''.join(__import__('inspect').signature(raise_).parameters)
print(a+b)
@terse oriole :white_check_mark: Your eval job has completed with return code 0.
quack
the bytecode hack is just my way of doing it - hell, you could do it with eval()
(lambda ack:(()for()in()).throw(Exception(ack)))('qu')
onelined
after the try:
yeah
try:(lambda ack:(()for()in()).throw(Exception(ack)))('qu')
I was doing some testing with throw
!e
(lambda _, __, ___: (lambda p, ____________________, ___: [print(__import__('this').d.get(____, ____), end='', file=p) for ____ in ___])(__.stdout, setattr(__, 'stdout', open(_.devnull, 'w')), ___))(__import__('os'), __import__('sys'), 'frperg zrffntr')
@terse oriole :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | File "<string>", line 1, in <lambda>
004 | FileNotFoundError: [Errno 2] No such file or directory: '/dev/null'
this doesnt work on the bot
but I have no other way to suppress prints?
I wanted to use contextlib.redirect_stdout
make a dummy file object
wow how does this catch the error?
uhh that isnt a try except
its a ROT 13 cipher using the dictionary in the this module
oh
isn't that just a ceasar cipher?
I thought it was just any shift
rot13 is special case of caesar
that's what I thought, wait why is it special?
so if I were to do this, what methods do I need to define in the class?
planning on onelining it with type
just all of the ones you use, except they do nothing except return the expected returns
uhh no the print function is using it...
class DevNull:
readable=writable=True
read=lambda s,n:'\0'*n
write=lambda s,stuff:len(stuff)
something like that
!e
a=type("devnull", (), {"readable":True,"writable":True,"read":lambda s,n:'\0'*n,"write":lambda s,something:""})()
print("asd",file=a)
@terse oriole :warning: Your eval job has completed with return code 0.
[No output]
oh
that worked?
!e
(lambda _, __, ___: (lambda p, ____________________, ___: [print(__import__('this').d.get(____, ____), end='', file=p) for ____ in ___])(__.stdout, setattr(__, 'stdout', type("devnull", (), {"readable":True,"writable":True,"read":lambda s,n:'\0'*n,"write":lambda s,something:""})(), ___))(__import__('os'), __import__('sys'), 'frperg zrffntr')
XD
whoops
!e
(lambda _, __, ___: (lambda p, ____________________, ___: [print(__import__('this').d.get(____, ____), end='', file=p) for ____ in ___])(__.stdout, setattr(__, 'stdout', type("devnull", (), {"readable":True,"writable":True,"read":lambda s,n:'\0'*n,"write":lambda s,something:""})()), ___))(__import__('os'), __import__('sys'), 'frperg zrffntr')
@terse oriole :x: Your eval job has completed with return code 120.
001 | secret messageException ignored in: <__main__.devnull object at 0x7fa01cc6bc10>
002 | AttributeError: 'devnull' object has no attribute 'flush'
need more stuff
yeah
and remove spaces after commas
!e
(lambda _,__,___:(lambda p, ____________________,___:[print(__import__('this').d.get(____,____),end='',file=p)for ____ in ___])(__.stdout, setattr(__,'stdout',type("devnull",(),{"readable":True,"writable":True,"read":lambda s,n:'\0'*n,"write":lambda s,something:"","flush":lambda a:None})()),___))(__import__('os'),__import__('sys'),'frperg zrffntr')
@terse oriole :white_check_mark: Your eval job has completed with return code 0.
secret message
perfect
!e
(lambda _,__,___:(lambda p, ____________________,___:[print(__import__('this').d.get(____,____),end='',file=p)for ____ in ___])(__.stdout, setattr(__,'stdout',type("devnull",(),{"readable":True,"writable":True,"read":lambda s,n:'\0'*n,"write":lambda s,something:"","flush":lambda a:None})()),___))(__import__('os'),__import__('sys'),'frperg zrffntr')
@terse oriole :white_check_mark: Your eval job has completed with return code 0.
secret message
I'm mostly learning esoteric python from this channel, still not that good at it though
I have a fun encryption method that takes an enormous amount of time to generate the key
hmm
the decrypter has a brainfuck interpreter built into it
about how enormous of a time?
on my nice beefy laptop, negligable.
on my older laptop, enough time to have a nap whilst generating the key
that is, with a 5 digit secret
oh
more digits, more thoncc
I can hear my pc fans spinning already
def generate(seed:int,key:int):return''.join([*map(lambda x:x**key,(*map(lambda x:int(x)<<1,str(seed)),))])
thoncc
returns a string, but the string can be interpreted as an abstractly large integer
encrypted message: an array of integers, each is usually under ten digits long.
decryption:
- for each number in array
-
- index the digit of the arbitrarily large integer at that position
-
- append to new digit array
- pass digit array as string to modified brainfuck interpreter
-
- 8 selected digits are translated to brainfuck characters
-
- the output from the equivalent of
.character in brainfuck is printed or piped.
- the output from the equivalent of
-
- optionally, allow usage of the equivalent of
,for an interactive encrypted io program.
- optionally, allow usage of the equivalent of
encryption:
- you have to write a brainfuck script, translate each character to matching digit, and randomly insert the unassigned digits.
- for each "intfuck" digit:
-
- choose a random position in the arbitrary integer
-
- while the digit doesn't match, change position.
-
- append index to array of encrypted data
it's overkill compared to ceasar shift
I-
!e but for simple message encryption I have this beautiful function
__annotations__=globals()
___:___ +'+-<>'=",.[]";
____:____//2 +1=(0x00for x in 100% yo_mamma is fat)
def code(
_0:(str,"The code, preferably UTF-8")="",
_1:(int,'architecture of target machine')=____
):
if not(_0):return''
if ord(max(_0))>1<<_1:raise RuntimeError(
"Cannot encode "+max(_0)+" into character size "+str(_1)
) ;-D
for _00 in['']:_01: (list, "mem::code")=[ord(_)for _ in str(_0)]
_02:(list, "bf::mul-values")=[
_ for _ in range((max(_01)+2)//10)if any([__//10==_ for __ in _01])
];_02+=(max(_01)//10 not in _02)*[max(_01)//10]
_00+='+'*10+'[>'+'>'.join([_*'+'for _ in _02])+'<'*len(_02)+'-]>'
_03:(int,"sys::pointer-shift state")=int()
_04:(list,'mem::turing-machine')=[0]*len(_02)
for _10 in _01:
_11:(tuple, ("chop off last digit","last digit"))=_10.__divmod__(10)
while _11[0]>_02[_03]:_03+=1;_00+='>';
while _11[0]<_02[_03]:_03-=1;_00+='<';
_12:(int,'cell_increment')= _11[1]-_04[_03]
_00+={1<0:'+',0<1:'-'}[_12<0]*abs(_12)+'.'
_04[_03]+=_12
_05:(str, 'conflict')=___[4:6],___[6:8]
for _2 in range(2):
while _05[_2]in _00:_00=_00 .replace(_05[_2],'')
while _05[_2][::-1]in _00:_00=_00.replace(_05[_2][::-1],'')
return _00
print(code("Quack!\n"))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
++++++++++[>+>+++>++++++++>+++++++++>++++++++++>+++++++++++<<<<<<-]>>>+.>>>+++++++.<<+++++++.++.>+++++++.<<<+++.<.
quack
winking face
!e ```py
def code(
_0:(str,"The message, preferably UTF-8")="",
_1:(int,'architecture of target machine')=8
):
___ = ''.join(map(str,range(1,9)))
if not(_0):return''
if ord(max(_0))>1<<_1:raise RuntimeError(
"Cannot encode "+max(_0)+" into character size "+str(_1)
) ;-D
for _00 in['']:01: (list, "mem::code")=[ord()for _ in str(_0)]
_02:(list, "bf::mul-values")=[
_ for _ in range((max(01)+2)//10)if any([__//10== for __ in _01])
];_02+=(max(_01)//10 not in _02)[max(_01)//10]
00+='1'*10+'74'+'4'.join(['1'for _ in _02])+'3'*len(_02)+'284'
_03:(int,"sys::pointer-shift state")=int()
_04:(list,'mem::turing-machine')=[0]*len(_02)
for _10 in _01:
_11:(tuple, ("chop off last digit","last digit"))=_10.divmod(10)
while _11[0]>_02[_03]:_03+=1;_00+='4';
while _11[0]<_02[_03]:_03-=1;_00+='3';
_12:(int,'cell_increment')= _11[1]-_04[_03]
_00+={1<0:'1',0<1:'2'}[12<0]*abs(12)+'5'
04[03]+=12
05:(str, 'conflict')=[4:6],[6:8]
for _2 in range(2):
while _05[_2]in _00:_00=_00 .replace(_05[_2],'')
while _05[_2][::-1]in _00:_00=_00.replace(_05[_2][::-1],'')
return _00
print(code("Roses are red, bananas are yellow, and my coffee is bitter, cold and black"))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
111111111174111411114111111114111111111411111111114111111111114111111111111333333328444115444151111531545333331154441111111544253533335444445352533311115354441525442222533544533544111115333335444544253153333544444415335111111155422251111111153333535444544222222222532222222253333544441111111115445333333544411544153222222255255333354444111154111153333354442545415532222542253333535444154422253111111152222222253333544422544253533335444154111111115325115425
so how do I insert random 0s and 9s into that?
!e ```py
from random import randint
def random_insertion(number:str):
a,b=number.iter(),[]
try:
while 1:b+=next(a)if randint(0,5)else str(9*randint(0,1))
except StopIteration:return''.join(b).lstrip('0')
print(random_insertion("111111111174111411114111111114111111111411111111114111111111114111111111111333333328444115444151111531545333331154441111111544253533335444445352533311115354441525442222533544533544111115333335444544253153333544444415335111111155422251111111153333535444544222222222532222222253333544441111111115445333333544411544153222222255255333354444111154111153333354442545415532222542253333535444154422253111111152222222253333544422544253533335444154111111115325115425"))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
11111110191917041114111141111111141111111119411019111119191411110110111199141111111111113393033303928444115440904151011153919954533339311544411111115044253533335440444535902530331111535444150254422225335944950335441111153333354445490425391533330540404944949153035111111155402022511110111153333535044454422222220022593220922022202053333549494411191111115445333393354441915441532922992222552553333540944491111541111593903393035444254954091595322220054225333353544415442292593911111101522222222533330054442254429535333354449154111911111532511594250
that actually worked
I think this might be hard to decrypt
unless you have the seed and pin
and it's so slow you need waitbars
def decrypt(filename,seed:int,key:int):
with open(filename)as file:data='array='+file.read()
with open('temp.py','w')as f:f.write(data)
from temp import array
__import__('os').remove('temp.py')
print("generating...")
abstract_integer = generate(seed,key)
print("decrypting...")
del key
numbers = [int(abstract_integer[int(this)])for this in array]
return[intfuck(numbers),print("decryption complete.")][0]
def encrypt(name:str,location:str,message:str,seed:int,key:int):
fn = location+__import__('os').sep+name+'.txt'
code = unfuck(message)
print('generating...')
abstract_integer = generate(seed,key)
limit = len(abstract_integer)-1
assert all([str(this)in abstract_integer for this in set(code)])
print("encrypting...")
del key
def ff(ie):
i,e=ie
pos = randint(0,limit)
while str(e)!=abstract_integer[pos]:pos-=1;pos%=limit
code[i]=pos
*map(ff,[*enumerate(code)]),
with open(fn,'w')as f:f.write(str(code))
print("encryption complete.")
!e for i in "etbj": print(chr(ord(i)+1))
@finite blaze :white_check_mark: Your eval job has completed with return code 0.
001 | f
002 | u
003 | c
004 | k
D:
now this
__try:__asm|[
format ( MZ ),
push ( cs ),
pop ( ds ),
mov ( ah| 9 ),
mov ( dx| hello ),
int ( 21 ),
mov ( ax| 0x4C00 ),
int ( 21 ),
hello| ( db| 'Hello world!' | 24 )
]
__except:(Exception)|[
nop
]
parses to
__try __asm | [format(MZ), push(cs), pop(ds), mov(ah | 9), mov(dx | hello), int(21), mov(ax | 19456), int(21), hello | (db | 'Hello world!' | 24)]
__except Exception | [nop]
doing something like inline asm from c++ (idk why when my main lang is c++ but why not)
__try {
__asm {
format MZ
push cs
pop ds
mov ah, 9
mov dx, hello
int 21h
mov ax, 4C00h
int 24h
hello db 'Hello world!', 24h
}
}
__except (...) {}
!e __try:__asm|[
format ( MZ ),
push ( cs ),
pop ( ds ),
mov ( ah| 9 ),
mov ( dx| hello ),
int ( 21 ),
mov ( ax| 0x4C00 ),
int ( 21 ),
hello| ( db| 'Hello world!' | 24 )
]
__except:(Exception)|[
nop
]
yes
here's the code that makes it work:
from __future__ import annotations
@lambda c:c()
class __annotations__:
def __setitem__(s,k,v):
match k:
case "__try":
s._k=k
s._v=v
case "__except":
print(s._k,s._v)
print(k,v)
case "__asm":std.__asm(k,v)
case "std":std.__getattr__(k)(v)
case "__for":
s.cond=v.split(",")[1].strip()
s.var=v.split(",")[0].strip("(")
globals().update({s.var:0})
case "_":
c=v.strip("{").strip("}").strip().split(", ")
cs="\n".join(st.strip("'")for st in code)
while eval(self.cond):
exec(cs);globals()[s.var]+=1
case _:pass
@type.__call__
class std:
def __asm(s,k,i):
_i=i.split("|")
t,_c=_i[0].strip(),[expr.strip()for expr in _i[-1].strip()[1:][:-1].split(",")]
print(t,_c)
class std:
def __init__(s,i):
_cs=i.split("|")
_fn=_cs[0].strip()
_arg="".join([arg.strip().replace("+endl","\n")for arg in _cs[1:]])
s.__getattribute__(_fn)(_arg)
def cout(s,i):print(i)
def __getattr__(s,a):
return s.__getattribute__(a.replace("_annotations__","_std"))
but still wip
!e ```py
from future import annotations
@lambda c:c()
class annotations:
def setitem(s,k,v):
match k:
case "__try":s._k,s._v=k,v
case "__except":print(s._k,s.v);print(k,v)
case "__asm":std.__asm(k,v)
case "std":std.getattr(k)(v)
case "__for":s.cond,s.var=v.split(",")[1].strip(),v.split(",")[0].strip("(");globals().update({s.var:0})
case "":
c=v.strip("{").strip("}").strip().split(", ");cs="\n".join(st.strip("'")for st in c)
while eval(self.cond):exec(cs);globals()[s.var]+=1
case _:pass
@type.call
class std:
def __asm(s,k,i):
_i=i.split("|")
t,_c=_i[0].strip(),[expr.strip()for expr in _i[-1].strip()[1:][:-1].split(",")]
print(t,_c)
class std:
def init(s,i):
_cs=i.split("|")
_fn=_cs[0].strip()
_arg="".join([arg.strip().replace("+endl","\n")for arg in _cs[1:]])
s.getattribute(_fn)(arg)
def cout(s,i):print(i)
def getattr(s,a):
return s.getattribute(a.replace("annotations","_std"))
__try:__asm|[
format ( MZ ),
push ( cs ),
pop ( ds ),
mov ( ah| 9 ),
mov ( dx| hello ),
int ( 21 ),
mov ( ax| 0x4C00 ),
int ( 21 ),
hello| ( db ( 'Hello world!' ) | 24 )
]
__except:(AssertionError)|[
nop
]
@sly root :white_check_mark: Your eval job has completed with return code 0.
001 | __try __asm | [format(MZ), push(cs), pop(ds), mov(ah | 9), mov(dx | hello), int(21), mov(ax | 19456), int(21), hello | (db('Hello world!') | 24)]
002 | __except AssertionError | [nop]
!e ```
from types import FunctionType
a = (x for x in [1])
list(FunctionType(a.gi_code, {})(0))
@outer surge :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
I wonder if you could do fun things with ctypes on the evaluator
I hope it's sandboxed
also implemented brainfuck with this syntax:
__brainfuck:(
movr| 3,
add| 48,
rprint,
fprint,
add| 12,
loop| 71 |[
movr| 1,
add| 3
],
)```
parses to [['movr', '3'], ['add', '48'], ['rprint', 'rprint'], ['fprint', 'fprint'], ['add', '12'], ['loop', '71'], ['movr', '1'], ['add', '3'],['end']]
"call stack"\™
0 ['movr', '3'] 1 ['add', '48'] 2 ['rprint', 'rprint'] 48 3 ['fprint', 'fprint'] 0 4 ['add', '12'] 5 ['loop', '71'] 6 ['movr', '1'] 7 ['add', '3'] 8 ['end'] unrecognised instruction end```
!e print(dircompile("a=1",'','exec')))
updated
0 ['movr', '3'] 1 ['add', '48'] 2 ['rpr', 'rpr'] 48 3 ['fpr', 'fpr'] 0 4 ['add', '12'] 5 ['loop', '71'] 6 ['movr', '1'] 7 ['add', '3'] 8 ['nop', 'nop'] 9 ['end']```
@split salmon :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'dircompile' is not defined. Did you mean: 'compile'?
!e print(dir(compile("a=1",'','exec')))
@split salmon :white_check_mark: Your eval job has completed with return code 0.
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'co_argcount', 'co_cellvars', 'co_code', 'co_consts', 'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars', 'co_kwonlyargcount', 'co_lines', 'co_linetable', 'co_lnotab', 'co_name', 'co_names', 'co_nlocals', 'co_posonlyargcount', 'co_stacksize', 'co_varnames', 'replace']
added argument type cast
0 ['movr', 3] 1 ['add', 48] 2 ['rpr', 'rpr'] 48 3 ['fpr', 'fpr'] 0 4 ['add', 12] 5 ['loop', 71] 6 ['movr', '1'] 7 ['add', '3'] 8 ['nop', 'nop'] 9 ['end', 'end']
now i need to update the interpreter to make it work with loops
Not python, but I just became aware of this and needed to share: https://github.com/carlini/printf-tac-toe
Yep printf programming is fun
__repr__
<structure human {
name: str
age: int
born: datetime
}>
I wanna make an esolang that compiles to brainfuck.
Just to make it easier to write brainfuck
I'm the interpreter, I would write brainfuck to end writing brainfuck
*compiler
that's what I want to make
but problem is the compiler itself
because its hard to parse something like this normally
so i was using .split
now I'm trying to migrate that code to sly/ply
its easy to parse something like this
__struct:human|(
name| str,
age| int,
born| datetime.datetime
)``` because there's only one thing (`|`) you can split that text with
and then just iterate over the list
but its not easy to parse this
__try:__brainfuck|(
movr| 3,
add| 112,
fpr,
add| 12,
loop| 71 |[
movr| 1,
add| 3,
loop| 4 |[
movl| 3,
mul| 77
]
],
)
__except:(Exception)|(
print| "Oopsie"
)```
lexed
LexToken(INSTR,'movr',1,0) LexToken(SPACE,' ',1,4) LexToken(ARG,'|',1,5) LexToken(SPACE,' ',1,6) LexToken(NUMBER,3,1,7) LexToken(COMMA,',',1,8) LexToken(SPACE,' ',1,9) LexToken(INSTR,'add',1,10) LexToken(SPACE,' ',1,13) LexToken(ARG,'|',1,14) LexToken(SPACE,' ',1,15) LexToken(NUMBER,112,1,16) LexToken(COMMA,',',1,19) LexToken(SPACE,' ',1,20) LexToken(INSTR,'fpr',1,21) LexToken(COMMA,',',1,24) LexToken(SPACE,' ',1,25) LexToken(INSTR,'add',1,26) LexToken(SPACE,' ',1,29) LexToken(ARG,'|',1,30) LexToken(SPACE,' ',1,31) LexToken(NUMBER,12,1,32) LexToken(COMMA,',',1,34) LexToken(SPACE,' ',1,35) LexToken(INSTR,'loop',1,36) LexToken(SPACE,' ',1,40) LexToken(ARG,'|',1,41) LexToken(SPACE,' ',1,42) LexToken(NUMBER,71,1,43) LexToken(SPACE,' ',1,45) LexToken(ARG,'|',1,46) LexToken(SPACE,' ',1,47) LexToken(LOOP_START,'(',1,48) LexToken(INSTR,'movr',1,49) LexToken(SPACE,' ',1,53) LexToken(ARG,'|',1,54) LexToken(SPACE,' ',1,55) ```
LexToken(NUMBER,1,1,56) LexToken(COMMA,',',1,57) LexToken(SPACE,' ',1,58) LexToken(INSTR,'add',1,59) LexToken(SPACE,' ',1,62) LexToken(ARG,'|',1,63) LexToken(SPACE,' ',1,64) LexToken(NUMBER,3,1,65) LexToken(COMMA,',',1,66) LexToken(SPACE,' ',1,67) LexToken(INSTR,'loop',1,68) LexToken(SPACE,' ',1,72) LexToken(ARG,'|',1,73) LexToken(SPACE,' ',1,74) LexToken(NUMBER,4,1,75) LexToken(SPACE,' ',1,76) LexToken(ARG,'|',1,77) LexToken(SPACE,' ',1,78) LexToken(LOOP_START,'(',1,79) LexToken(INSTR,'movl',1,80) LexToken(SPACE,' ',1,84) LexToken(ARG,'|',1,85) LexToken(SPACE,' ',1,86) LexToken(NUMBER,3,1,87) LexToken(COMMA,',',1,88) LexToken(SPACE,' ',1,89) LexToken(INSTR,'mul',1,90) LexToken(SPACE,' ',1,93) LexToken(ARG,'|',1,94) LexToken(SPACE,' ',1,95) LexToken(NUMBER,77,1,96) LexToken(LOOP_END,')',1,98) LexToken(LOOP_END,')',1,99)```
some progress
input:
__brainfuck:(
movl| 3,
loop| 30 |(
add| 7,
movr| 2
),
)
output:
LexToken(SHIFT_LEFT,'movl',2,1) LexToken(ARG,'|',2,5) LexToken(NUM,3,2,7) LexToken(COMMA,',',2,8) LexToken(LOOP,'loop',3,10) LexToken(ARG,'|',3,14) LexToken(NUM,30,3,16) LexToken(ARG,'|',3,19) LexToken(LPAREN,'(',3,20) LexToken(PLUS,'add',4,28) LexToken(ARG,'|',4,31) LexToken(NUM,7,4,33) LexToken(COMMA,',',4,34) LexToken(SHIFT_RIGHT,'movr',5,41) LexToken(ARG,'|',5,45) LexToken(NUM,2,5,47) LexToken(RPAREN,')',6,49)```
What this numbers mean?
movl 3 equal to <<< in bf?
move left by 3 cells
loop, iterate 30 times
- add 7 to current cell
- move right by 2 cells
lexer is done, i guess
now parser and so on
!e
import random,time
class Imposter:
def __init__(self,sus):
self.sus = sus
theimposter = Imposter(False)
r = 0
while not theimposter.sus:
if random.randint(0,10):
r+=1
time.sleep(0.1)
continue
theimposter.sus = True
print(f"The imposter was acting kinda sus and was thrown away on the {r} round.")
del theimposter # throw him outta here
@vale tangle :white_check_mark: Your eval job has completed with return code 0.
The imposter was acting kinda sus and was thrown away on the 38 round.
sus
!e
i = 0
while True:
i+=1
print(i)
@vale tangle :x: Your eval job has completed with return code 143 (SIGTERM).
001 | 1
002 | 2
003 | 3
004 | 4
005 | 5
006 | 6
007 | 7
008 | 8
009 | 9
010 | 10
011 | 11
... (truncated - too many lines)
Full output: too long to upload
hehe, i like the last line
!e
import random,time
class Imposter:
def __init__(self,sus):
self.sus = sus
theimposter = Imposter(False)
r = 0
while not theimposter.sus:
if random.randint(0,10):
r+=1
time.sleep(0.1)
continue
theimposter.sus = True
print(f"The imposter was acting kinda sus and was thrown away on the {r} round.")
del theimposter # throw him outta here
@vale tangle :white_check_mark: Your eval job has completed with return code 0.
The imposter was acting kinda sus and was thrown away on the 17 round.
!e
print(len(""))
@safe sinew :white_check_mark: Your eval job has completed with return code 0.
60
!e
hi
@safe sinew :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'hi' is not defined
@floral meteor can you teach me your cursed bf interpreters?
I love reading them but don't understand most
I've memorized one of them
!e Here's a version I don't think I've tried before
class brainfuck:
def __iadd__(s, n):
s.a[s.i] += n
s.a[s.i] %= 256
return s
def __str__(s):
return chr(s.a[s.i])
def __bool__(s):
return bool(s.a[s.i])
def __init__(s, c):
s.a=__import__("collections").defaultdict(int)
s.i=0
s.error=s.run(c)
def run(s, c):
s.t=p=0
while 0<=p<=len(c)-1:
if s.t:s.t+=(c[p]=='[')-(c[p]==']')
else:getattr(s,{
'+':'add', '-':'sub',
'<':'left','>':'rite',
'.':'dot', ',':'com',
'[':'loop',']':'endl'
}.get(c[p],'nop'))()
p+=1-2*(s.t<0)
return+bool(s.t)
memory=property(lambda s:[*(
lambda a:[s.a[_]for _ in range(min(a),max(a))]and s.a
)([*s.a.keys()]).values()],__iadd__)
def add(s):s += 1
def sub(s):s +=-1
def left(s):s.i -= 1
def rite(s):s.i += 1
def dot(s):print(end=str(s))
def com(s):s.a[s.i]=0;s+=ord(__import__('sys').stdout.read(1))
def loop(s):s.t+=not s
def endl(s):s.t-=bool(s)
def nop(*_):...
a = brainfuck("++++++++++[>+>+++>++++++++>+++++++++>++++++++++>+++++++++++<<<<<<-]>>>+.>>>+++++++.<<+++++++.++.>+++++++.<<<+++.<.")
print(a.memory)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | Quack!
002 | [0, 10, 33, 81, 99, 107, 117]
you just need a memory, three pointers, 8 instructions and a no-op.
The only differences are technically refactoring and extra implementation.
!e one liner with only one variable name. ```py
(lambda :(lambda :([0 for [6]['+']in[lambda:[([2],0)for [1][[2]]in[([1][[2]]+1)%256]][0]]for [6]['-']in[lambda:[([2],0)for [1][[2]]in[([1][[2]]-1)%256]][0]]for [6]['<']in[lambda:([2]-1,0)]for [6]['>']in[lambda:([2]+1,0)]for [6]['.']in[lambda:print(end=chr([1][[2]]))or([2],0)]for [6][',']in[lambda:[([2],0)for [1][[2]]in[ord(5)]][0]]for [6]['[']in[lambda:([2],not [1][[2]])]for [6][']']in[lambda:([2],-bool([1][[2]]))]],{[[[0 for [3]in[[3]+([0][[4]]=='[')-([0][[4]]==']')]]if [3]else[0 for [2:4]in[[6].get(([0]+'\0')[[4]],lambda:([2],0))()]]]for [4]in[1+[4]-2*([3]<0)]]and()for{}[0]in iter(lambda:0<=[4]<len([0]),False)}, not not [3] )[-1])([' '+,import('collections').defaultdict(int),0,0,0,import("sys").stdin.read,{}]))("++++++++++[>+>+++>++++++++>+++++++++>++++++++++>+++++++++++<<<<<<-]>>>+.>>>+++++++.<<+++++++.++.>+++++++.<<<+++.<.")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Quack!
Well guess you're making a lot of code that outputs quack now huh
Is this a brainfuck compiler?
did some more work on this monstrosity https://totally-not.a-sketchy.site/4XGVBSK.png
(cc @near gust )
i forgot about this. i have some more i was working on
that link name XD
just an interpreter.
I'm conceptualizing the compiler currently, before I start writing it.
at any rate, hello
how does this particular one work?
What does esoteric python mean
!e ```py
pointer=0;memory=[0 for i in range(21)]
def _(_0=(list,'instruction to interpet')):
B='memory';A='pointer';_1=_0[0];_2=_0[1]
match _1:
case'add':globals()[B][globals()[A]]+=_2
case'sub':globals()[B][globals()[A]]-=_2
case'mul':globals()[B][globals()[A]]*=_2
case'mmul':globals()[B][globals()[A]]@=_2
case'div':globals()[B][globals()[A]]/=_2
case'rdiv':globals()[B][globals()[A]]//=_2
case'pow':globals()[B][globals()[A]]^=_2
case'mod':globals()[B][globals()[A]]%=_2
case'movl':globals()[A]-=_2
case'movr':globals()[A]+=_2
case'rst':globals()[A]=0
case'ind':print(globals()[A])
case'ret':print(chr(globals()[B][globals()[A]]))
case'mret':print(''.join([chr(globals()[B][i])for i in range(_2)]))
case'dump':print(globals()[B])
case'loop':print('loops are not implemented')
case'endl':0
case'nop':0
case _:0
_(['movr', 2])
_(['ind', None])
_(['add', 113])
_(['ret', None])
_(['dump', None])
@sly root :white_check_mark: Your eval job has completed with return code 0.
001 | 2
002 | q
003 | [0, 0, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
!e ```py
from future import annotations
pointer=0;memory=[0 for i in range(21)]
def _(_0=(list,'instruction to interpet')):
B='memory';A='pointer';_1=_0[0];_2=_0[1]
match _1:
case'add':globals()[B][globals()[A]]+=_2
case'sub':globals()[B][globals()[A]]-=_2
case'mul':globals()[B][globals()[A]]*=_2
case'mmul':globals()[B][globals()[A]]@=_2
case'div':globals()[B][globals()[A]]/=_2
case'rdiv':globals()[B][globals()[A]]//=_2
case'pow':globals()[B][globals()[A]]^=_2
case'mod':globals()[B][globals()[A]]%=_2
case'movl':globals()[A]-=_2
case'movr':globals()[A]+=_2
case'rst':globals()[A]=0
case'ind':print(globals()[A])
case'ret':print(chr(globals()[B][globals()[A]]))
case'mret':print(''.join([chr(globals()[B][i])for i in range(_2)]))
case'dump':print(globals()[B])
case'loop':print('loops are not implemented')
case'endl':0
case'nop':0
case _:0
@lambda c:c()
class annotations:
def setitem(s,k,v):
if'__brainfuck'in k:
instructions=v[1:][:-1]
_0=instructions.replace('(','(,')
_1=_0.replace(')',',)')
_2=_1.split(_A)
_3=[instruction.strip()for instruction in _2]
_4=[instruction.replace(' ','')for instruction in _3]
_5='\n'.join(_4)
_6=[]
for instruction in _5.splitlines():
_7=instruction.split('|')
if len(_7)>1:
_6.append([_7[0],int(_7[1])if _7[1].isnumeric()else _7[1]])
elif not _7[0]=='':
_6.append([_7[0],None])
for _instr in _6:
_(_instr)
else:0
__brainfuck:(
add| 104, movr| 1,
add| 101, movr| 1,
add| 108, movr| 1,
add| 108, movr| 1,
add| 111, movr| 1,
add| 32, movr| 1,
add| 119, movr| 1,
add| 111, movr| 1,
add| 114, movr| 1,
add| 108, movr| 1,
add| 100,
aret| 11,
loop| 3 |(
movr| 26,
),
ind,
dump,
)
@sly root :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 46, in <module>
003 | File "<string>", line 32, in __setitem__
004 | NameError: name '_A' is not defined. Did you mean: '_0'?
Oh my god that is a lot of case
!e ```py
from future import annotations
pointer=0;memory=[0 for i in range(301)]
def _(_0=(list,'instruction to interpet')):
_1=_0[0];_2=_0[1]
match _1:
case'add':globals()['memory'][globals()['pointer']]+=_2
case'sub':globals()['memory'][globals()['pointer']]-=_2
case'mul':globals()['memory'][globals()['pointer']]*=_2
case'mmul':globals()['memory'][globals()['pointer']]@=_2
case'div':globals()['memory'][globals()['pointer']]/=_2
case'rdiv':globals()['memory'][globals()['pointer']]//=_2
case'pow':globals()['memory'][globals()['pointer']]^=_2
case'mod':globals()['memory'][globals()['pointer']]%=_2
case'movl':globals()['pointer']-=_2
case'movr':globals()['pointer']+=_2
case'rst':globals()['pointer']=0
case'ind':print(globals()['pointer'])
case'ret':print(chr(globals()['memory'][globals()['pointer']]))
case'mret':print(''.join([chr(globals()['memory'][i])for i in range(_2)]))
case'dump':print(globals()['memory'])
case'loop':print('loops are not implemented')
case'endl':0
case'nop':0
case _:0
@lambda c:c()
class annotations:
def setitem(s,k,v):
if'__brainfuck'in k:
instructions=v[1:][:-1]
_0=instructions.replace('(','(,')
_1=_0.replace(')',',)')
_2=_1.split(',')
_3=[instruction.strip()for instruction in _2]
_4=[instruction.replace(' ','')for instruction in _3]
_5='\n'.join(_4)
_6=[]
for instruction in _5.splitlines():
_7=instruction.split('|')
if len(_7)>1:
_6.append([_7[0],int(_7[1])if _7[1].isnumeric()else _7[1]])
elif not _7[0]=='':
_6.append([_7[0],None])
for _instr in 6:(_instr)
__brainfuck:(
add| 104, movr| 1,
add| 101, movr| 1,
add| 108, movr| 1,
add| 108, movr| 1,
add| 111, movr| 1,
add| 32, movr| 1,
add| 119, movr| 1,
add| 111, movr| 1,
add| 114, movr| 1,
add| 108, movr| 1,
add| 100,
mret| 11,
ind,
loop| 3 |(
movr| 26,
),
ind,
)```
@sly root :white_check_mark: Your eval job has completed with return code 0.
001 | hello world
002 | 10
003 | loops are not implemented
004 | 36
lol loops are not implemented. That's kinda essential
I wonder where you got this style from?
def _(_0=(list,'instruction to interpet')):
...
looks similar to this
def code(
_0:(str,"The message, preferably UTF-8")="",
_1:(int,'architecture of target machine')=8
):
XD
I like the annotations usage though
I just can't help but
for _1,_2 in _0:
match _1:
.
: