#esoteric-python
1 messages · Page 144 of 1
Now that's a good slogan
Actually thirteen if you count space and newline
Wait
!e
print(len("while1-=[]:\n "))
@cloud fossil :white_check_mark: Your eval job has completed with return code 0.
13
Is lambda calculus also turning complete?
according to https://en.wikipedia.org/wiki/Lambda_calculus#Explanation_and_applications it is
Now for the ultimate obstructification:
You could use exec and input every character of the original code like this:
exec(chr(1+1+1+1+1+...)+chr(1+1+1+...)+...)
!e ```py
x = set(list("exec(chr(1+1))"))
print(x)
print(len(x))
@lime bane :white_check_mark: Your eval job has completed with return code 0.
001 | {'c', 'e', 'r', ')', '+', '1', '(', 'x', 'h'}
002 | 9
This is borderline cheating but still valid python code. This way you could actually write any characters and execute them.
And also this is less fun
!e py exec(chr(1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+chr(1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+chr(1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+chr(1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+chr(1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+chr(1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+chr(1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+chr(1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+chr(1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+chr(1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+chr(1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1))
@lime bane :white_check_mark: Your eval job has completed with return code 0.
Hi
yes
i can use only 1 to construct all integers
for quick scripting i used 0-9, but it can be constructed with 1s
exchr()1+ - this is your set of chars, it is smaller than my
And it didn't mean to
!e py exec(chr(111+1)+chr(111+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+11)+chr(111+1+1+1+1+1)+chr(11+11+11+1+1+1+1+1+1+1)+chr(11+11+11+1)+chr(11+11+11+11+11+11+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+chr(111)+chr(11+11+1+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1)+chr(111)+chr(111+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1)+chr(11+11+11+1)+chr(11+11+11+1+1+1+1+1+1+1+1))
@lime bane :white_check_mark: Your eval job has completed with return code 0.
Hello World
I would say it is also quite fortunate that exec and chr together only have 5 different characters
!e ```py
def get_num2(n):
g_111 = n>=111
rest = n%111
whole_11s = rest//11
rest_rest = rest%11
p_111s = ['111'] * g_111
p_11s = ["11"]*whole_11s
p_1s = ["1"]*rest_rest
nums = []
nums += p_111s
nums += p_11s
nums += p_1s
#print(nums)
return "+".join(nums)
def obf(text):
numbers = [ord(x) for x in text]
chars = [f"chr({get_num2(n)})" for n in numbers]
txt = "+".join(chars)
result = f"exec({txt})"
return result
print(obf('print("Hello Discord")'))
@lime bane :white_check_mark: Your eval job has completed with return code 0.
exec(chr(111+1)+chr(111+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+11)+chr(111+1+1+1+1+1)+chr(11+11+11+1+1+1+1+1+1+1)+chr(11+11+11+1)+chr(11+11+11+11+11+11+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+chr(111)+chr(11+11+1+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1)+chr(111+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11)+chr(111)+chr(111+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1)+chr(11+11+11+1)+chr(11+11+11+1+1+1+1+1+1+1+1))
I'd like to introduce you to exchr(+1):
Python, but worse
Have you heard of exc("%)?
No
Hold on nevermind that doesn't necessarily work
Okay with =; it works
exchr(+1) and its sister language exc('%=;)
basically a bunch of assignments inside exec
how do you get numbers (other than 0 or 1)? (or do you not need them?)
e=''=='%';ee=e=='';exec('eee=%c%%c%%%c'%ee%e%ee)```
`eee` is now 101
aha
you can concat + modulo to get p much any number
then pass those to %c
then exec
I wonder actually
could you avoid having to use ;?
I was thinking something like exec("%c"%((""=="")+(""=="")+(""=="")+...))
Can you think of any way without =?
was thinking the same thing 😄, i'm not sure
This still has 9 characters, because you brought the + back
exec('%c%c'%(111, 111))
exec('%c'%(111+1)+'%c'%(11+11))
This has exc('%1,)
!e let me test:
s = set()
for i in range(1, 1000):
x = int("1"*i)
y = x % 1111
if y < 256:
s |={y}
print(len(s))
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
4
and this one has exc('%1+)
!e let me test:
s = set()
for i in range(1, 1000):
for j in range(i, 1000):
x = int("1"*i)
y = int("1"*j)
z = x % y
if z < 256:
s |={z}
print(len(s))
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
4
How exactly does this work?
Do you know what the exec function does?
Yeah
Ok
But the hello world output
!e py print(chr(111+1)+chr(111+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+11)+chr(111+1+1+1+1+1)+chr(11+11+11+1+1+1+1+1+1+1)+chr(11+11+11+1)+chr(11+11+11+11+11+11+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+chr(111)+chr(11+11+1+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1)+chr(111)+chr(111+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1)+chr(11+11+11+1)+chr(11+11+11+1+1+1+1+1+1+1+1))
@lime bane :white_check_mark: Your eval job has completed with return code 0.
print("Hello World")
!e let me test:
for q in range(1,10):
s = set()
for i in range(1, 1000):
for j in range(i, 1000):
x = int(str(q)*i)
y = int(str(q)*j)
z = x % y
if z < 256:
s |={z}
print(q, len(s))
@earnest wing :x: Your eval job timed out or ran out of memory.
001 | 1 4
002 | 2 4
This is, what the text evaluates to, when you don't execute it and then I just execute it
!e ```py
exec('print("Hello World")')
@lime bane :white_check_mark: Your eval job has completed with return code 0.
Hello World
So the thing in the parenthesis gets evaluated to code, that is then run
Do you understand now?
@earnest wing Do you have a link to a list with all the %format characters? Whenever I google it, it just says use f-strings instead
where you can find what each alphabet is represented by?
Do you know what ascii is?
not really but I've heard of it
!e ```py
n = ord("H")
print(n)
print(chr(60))
@lime bane :white_check_mark: Your eval job has completed with return code 0.
001 | 72
002 | <
ord(c)```
Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example, `ord('a')` returns the integer `97` and `ord('€')` (Euro sign) returns `8364`. This is the inverse of [`chr()`](https://docs.python.org/3/library/functions.html#chr "chr").
oh okay
so what's the relationship between the ones and this 72 in this case?
nevermind I think it's a different thing for "%" formatting
I think it's this https://docs.python.org/3/library/stdtypes.html#old-string-formatting
When I want to encode the letter "H", I need to do chr(72)
!e print(chr(72))
@icy frigate :white_check_mark: Your eval job has completed with return code 0.
H
But my goal is to use as few different characters as possible. That means I could do chr(1+1+1+1+1+....) until I get to 72
oh
Or I use this algorithm
That makes it shorter
how would you make it give what numbers to add up in a simpler method? That seems to be a bit complicated and can be shortnened
!e ```py
def get_num(n):
return "+".join(["1"]*n)
print(get_num(72))
@lime bane :white_check_mark: Your eval job has completed with return code 0.
1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1
This was the old, space inefficient way
oh that's way too long yeah
But when I wanted to print Hello word the 2000 character limit of discord hit, so I had to reduce the size
You have e, so in some cases you can do stuff like 1e11, right? :D
you mean 0x1e11
That's not a bad idea either
Well actually, it is a bad idea, because then I need the 0 character
anyways, I wanted to ask what's a complicated looking one liner someone can do
i like trying to understand what it does even though I know I can't
def conv(s):
return 'exec('+ '+'.join('"%c"%('+ '+'.join(['(""=="")']*ord(l)) +')' for l in s) +')'
exc('%1+) is probably the best character set
a more primitive converter than @lime bane's one
!e
def conv(s):
return 'exec('+ '+'.join('"%c"%('+ '+'.join(['(""=="")']*ord(l)) +')' for l in s) +')'
code = conv("print('Hello World!')")
print(exec(code))
print()
print(code)
@sudden osprey :white_check_mark: Your eval job has completed with return code 0.
001 | Hello World!
002 | None
003 |
004 | exec("%c"%((""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(
... (truncated - too long)
Full output: too long to upload
no, I mean 1e11, as in scientific notation. Although chr() likely doesn't like floats..
Also... 1e11 is way too large, 1e1 doesn't help :D
you might be on to something
it doesn't necessarily need to be 1, could use any digit
e.g.
!eval
print(3e33 % 33)
@sudden osprey :white_check_mark: Your eval job has completed with return code 0.
12.0
gives us a new number
!e
print(chr(12.0))
@restive void :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | TypeError: 'float' object cannot be interpreted as an integer
ah sad
what's 3e33 ?
3x10^33
oh I just realised that's only because of floating point imprecision lol, so the digit used doesn't really matter, more just the size.
!e ```py
def get_num(n):
whole_111s = n//111 # for ascii this is 1 or 0
rest = n%111
whole_11s = rest//11
rest_rest = rest%11
p_111s = ['111'] * whole_111s
p_11s = ["11"]*whole_11s
p_1s = ["1"]*rest_rest
nums = []
nums += p_111s
nums += p_11s
nums += p_1s
#print(nums)
return "+".join(nums)
def obf(text):
strings = []
for t in text:
if t in "exc(1+)":
strings += [f"'{t}'"]
elif t == "%":
strings += [f"'%'"]
else:
strings += [f"'%c'%({get_num(ord(t))})"]
string = "+".join(strings)
result = f"exec({string})"
return result
code = obf('print("Hello World")')
print(code)
exec(code)```
@lime bane :white_check_mark: Your eval job has completed with return code 0.
001 | exec('%c'%(111+1)+'%c'%(111+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+11)+'%c'%(111+1+1+1+1+1)+'('+'%c'%(11+11+11+1)+'%c'%(11+11+11+11+11+11+1+1+1+1+1+1)+'e'+'%c'%(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+'%c'%(111)+'%c'%(11+11+1+1+1+1+1+1+1+1+1+1)+'%c'%(11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1)+'%c'%(111)+'%c'%(111+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+1)+'%c'%(11+11+11+1)+')')
002 | Hello World
!e
assert __debug__
@fleet bridge :warning: Your eval job has completed with return code 0.
[No output]
Anybody got any good ideas for text based games? Preferably arcade style games, so not a text based rpg
text quest
!e
def f():
assert __debug__
def g():
pass
import dis
dis.dis(f)
print()
dis.dis(g)
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
001 | 2 0 LOAD_CONST 0 (None)
002 | 2 RETURN_VALUE
003 |
004 | 5 0 LOAD_CONST 0 (None)
005 | 2 RETURN_VALUE
Optimization
!e
print(__debug__)
@sudden osprey :white_check_mark: Your eval job has completed with return code 0.
True
IlIIIII = __import__("string", globals(), locals(), ["Template"]).Template(b"\x70\x65\x61\x63\x65".decode("utf-8")); IIIIIlI = __import__("string", globals(), locals(), ["Template"]).Template(b"\x69\x6e".decode("utf-8")); IIIIIIl = __import__("string", globals(), locals(), ["Template"]).Template(b"\x6f\x75\x72".decode("utf-8")); IIlIlIII = __import__("string", globals(), locals(), ["Template"]).Template(b"\x74\x69\x6d\x65".decode("utf-8")); lllllII = " ".join([ IlIIIII.substitute(), IIIIIlI.substitute(),IIIIIIl.substitute(), IIlIlIII.substitute(),] ); __import__("sys").stdout.write(lllllII + "\n")
my first obfuscation attempt
!e ```py
IlIIIII = import("string", globals(), locals(), ["Template"]).Template(b"\x70\x65\x61\x63\x65".decode("utf-8")); IIIIIlI = import("string", globals(), locals(), ["Template"]).Template(b"\x69\x6e".decode("utf-8")); IIIIIIl = import("string", globals(), locals(), ["Template"]).Template(b"\x6f\x75\x72".decode("utf-8")); IIlIlIII = import("string", globals(), locals(), ["Template"]).Template(b"\x74\x69\x6d\x65".decode("utf-8")); lllllII = " ".join([ IlIIIII.substitute(), IIIIIlI.substitute(),IIIIIIl.substitute(), IIlIlIII.substitute(),] ); import("sys").stdout.write(lllllII + "\n")
@sick hound :white_check_mark: Your eval job has completed with return code 0.
peace in our time
oh nice you used the Is and ls trick
What's the Is and ls trick? Just a way of making quite indistinguishable variable names?
yes
you can add 1s for further effect
just a command line interface, or something more like a text adventure?
what you could do is write a novel, but write every possibility for every decision the protagonist makes, and make the user decide what the protagonist does.
If you don't want the scrolling terminal effect, just print(end="\x1b[H\x1bc") at the start of every frame.
a sequence better known as CSIHESCc
anyone got any experience with programming in qiskit? if u do ping me pls
!e
b=lambda a: chr(int(('0'*(8-len(bin(ord(a))[2:]))+bin(ord(a))[2:])[4:]+('0'*(8-len(bin(ord(a))[2:]))+bin(ord(a))[2:])[::-1][4:][::-1],2));exec(''.join([b(z)for z in "\x07'\x96æG\x82r\x84VÆÆö\x12\x02ä\x966V\x02Gö\x02ÖVVG\x02\x97öWÂ\x02\x94ÅrÖ\x02ö&fW76\x16GVF\x12r\x92"]))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Hello! Nice to meet you, I'm obfuscated!
Lmao
!e
exec(''.join([chr(round(int(a,2)/10240)) for a in '_-__-__@-@__@-@__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__@-@__@-@__@-@__-__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__@-@__@-@__@-@__-__-__-__@-@__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__@-@__@-@__@-@__@-@__@-@__-__-__@-@__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__@-@__@-@__@-@__-__@-@__@-@__-__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__@-@__@-@__-__@-@__@-@__@-@__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__-__@-@__@-@__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__-__@-@__@-@__@-@__@-@__-__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__@-@__-__-__@-@__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__-__-__-__-__-__@-@__@-@__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__@-@__@-@__@-@__@-@__-__-__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__@-@__@-@__@-@__@-@__-__-__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__@-@__@-@__@-@__-__@-@__-__@-@__-__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__@-@__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__-__@-@__-__-__@-@__@-@__-__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__@-@__@-@__@-@__-__@-@__-__@-@__-__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__@-@__@-@__@-@__-__-__-__@-@__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__@-@__@-@__@-@__@-@__-__-__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__-__-__-__-__@-@__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__-__@-@__@-@__@'.replace('_-_', '1').replace('_@-@_', '0').split('_@~@_')]))```
@sick hound :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 <listcomp>
004 | ValueError: invalid literal for int() with base 2: '1100_@'
I think vids get filtered out by a bot in this server
plus even nitro has its upload limits and videos are chonky
?
!e
import __hello__, this
@errant crescent :white_check_mark: Your eval job has completed with return code 0.
001 | Hello world!
002 | The Zen of Python, by Tim Peters
003 |
004 | Beautiful is better than ugly.
005 | Explicit is better than implicit.
006 | Simple is better than complex.
007 | Complex is better than complicated.
008 | Flat is better than nested.
009 | Sparse is better than dense.
010 | Readability counts.
011 | Special cases aren't special enough to break the rules.
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ohifuperag.txt?noredirect

what
whats __hello__ and this? 
They're a part of python's builtin modules.
why does it print that when you import them?
the zen of python
@errant crescent :white_check_mark: Your eval job has completed with return code 0.
001 | The Zen of Python, by Tim Peters
002 |
003 | Beautiful is better than ugly.
004 | Explicit is better than implicit.
005 | Simple is better than complex.
006 | Complex is better than complicated.
007 | Flat is better than nested.
008 | Sparse is better than dense.
009 | Readability counts.
010 | Special cases aren't special enough to break the rules.
011 | Although practicality beats purity.
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ohipejaxef.txt?noredirect
!e
import __hello__
@errant crescent :white_check_mark: Your eval job has completed with return code 0.
Hello world!
i see
They're little easter eggs that were added by the devs iirc.
wrapping my brain around writing this felt like my brain was physically being wrapped around something
gameend=property(lambda self:not any([
not all([self[a]for a in self]), # is there blank squares?
any([a==b for(i,j,k,l),(w,x,y,z)in zip(self,filter(
lambda n:n in range(4),map(sum,product(self,filter(lambda x:sum(map(abs,x))==1,product(range(-1,2),repeat=4))))
)for a,b in map(int,[self[i,j,k,l],self[w,x,y,z]])) # are any adjacent cells equal?
]))
__setitem__=lambda self,item,value:(lambda i,j,k,l:self.matrix[l][k][j].__setitem__(i,[Cell,BaseCell][not value](*item,*[[value],()][not value])if type(value)==int else value))(*item)
a visual snippet of code from the 4D 2048 game
two more interface methods left and I'm done.
one is the output visualisation of the 4D board, the other is the event loop.
ok that's the event loop done ```py
def run(self):
self.eng and print('\x1b[H\x11b[c')
while not self.eng.gameend:c=self.input.kbhit()and self.input.getch().decode('ANSI')or'\1';self.next_frame({c in'wasd':lambda:self.eng.swipe(str.maketrans('wasd','\0\3\1\2')[ord(c)]),c=='\xe0':lambda:(lambda _c:self.eng.swipe(str.maketrans('KHMP','\7\4\6\5'))if chr(_c)in'KHMP'else self.quit())(ord(self.input.getch().decode('ANSI'))),c=='\x1b':self.quit}.get(1>0,lambda:'')())
makes async look so easy, doesn't it?
I think the frame display could be fit in one line if I soft code it enough. here is the untested complete soft coded board:
def next_frame(s,message=''):print(f"""\x1b[H\x1bc\x1b[0m{message}\x1b[90m^{"^=^".join(['^~^'.join(['^'.join(['@'.join(['|'.join([f"{self.eng[i,j,k,l]:{m}}"for i in range(4)])for k in range(4)])for m in map(str,range(3))])for j in range()])for l in range(4)])}\x1b[m\x1b[A""".replace('~','@'.join(['+'.join(4*['-'*7])]*4)).replace('=','@'*127).replace('@','\x1b[100m \x1b[49m').replace('^','\n'))
I left out the outermost borders to shave off a few characters of board size
and I made it under my goal of 44 lines
how long have you been programming using python? just curious
!e
print(lambda: "esoteric python")()
@sick hound :x: Your eval job has completed with return code 1.
001 | <function <lambda> at 0x7fc17a7dfd90>
002 | Traceback (most recent call last):
003 | File "<string>", line 1, in <module>
004 | TypeError: 'NoneType' object is not callable
wrap ur func in tuple then call it inside the print statement
!e
print((lambda: "esoteric python")())
@knotty delta :white_check_mark: Your eval job has completed with return code 0.
esoteric python
yes.
alright, at 50 lines, the abomination is now at least playable.
you see the two 32s on the left?
you press s that would make them 64;
you then press the down arrow, and it combines with another 64 to make 128
s
then down arrow
thats not a tuple
whups
What's that trick you can use with == to mutate the content of an immutable mappingproxy?
(And furthermore, is it cpython specific?)
yeah, it is cpython bug
!e
from types import MappingProxyType
orig = {1: 2}
proxy = MappingProxyType(orig)
class X:
def __eq__(self, other):
other[1] = 3
assert proxy[1] == 2
proxy == X()
assert proxy[1] == 3
assert orig[1] == 3
@fleet bridge :warning: Your eval job has completed with return code 0.
[No output]
Thank you
wow that's looking great
great work! what IDE are you using?
and do you program 'readably' before you scramble it?
how do people not apply decorators in source files when running tests? i'm currently patching google.cloud.firestore.transactional before importing my source files to no avail
Hi guys 🙂
I made UDLs in Python 
(also supports decorator syntax)
(unregistering literals + context managers soontm)
@earnest wing that's really cool!
Thank you! I'm making it a challenge to make this as "production-friendly" as possible within the silly premise (monkeypatching dynamic attributes to builtins lol) lol
what's that?
i hate this with a passion
User-defined literals, so basically custom suffixes for literals
Based on the c++ model
yes, and I'm planning on pushing it to pypi soon lmao, thank you!

sometimes even i don't understand what i'm talking about
mood
explain to me like im 5 what on earth that is
in C++, you can use templates (basically macros) to define custom code that runs when you write e.g. 100_kg in code, by registering kg as a "literal suffix" for integers.
this is that system using pure Python, which wouldn't usually be possible (since you can't add attributes to builtin types) but thanks to some cpython implementation details is doable!
The syntax is a little different, of course ("blah".x vs "blah"_x), but otherwise it's the same idea
i think all this is way beyond my skillset because i dont understand anything you're explaining 😂 ty for the explanation tho
i only know python and I'm still like kinda intermediate at it
what theme is this? i like the colors a lot :)
That's Ayu Mirage Bordered for vsc 😄
how can I
def foo(ref_x):
ref_x += 1
a = 1
foo(a)
print(a)
```desired output```>>> 2```
where X is immutable
ping on reply pls
or dm :D
hi
just add a = ref_x to the foo func
!e ```py
def foo(ref_x):
ref_x += 1
a = ref_x
a = 1
foo(a)
print(a)```
hmm
inchesting
!e
def foo(ref_x):
a = ref_x + 1
a = 1
foo(a)
print(a)
maybe if we make a var global?
!e ```py
def foo(ref_x):
global a
a = ref_x + 1
a = 1
foo(a)
print(a)```
@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.
2
ah
@fair quartz could probably be cleaner but ye ^
wait
let me see
!e ```py
def foo(ref_x):
global a
a = ref_x + 1
a = 1
foo(a)
foo(a)
print(a)```
@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.
3
you can't do that.
not the way you did it at least 🙂
x is immutable hmm
they want foo(a) to mean that a is incremented, and presumably that foo(b) would increment b.
so thats not possible then
no, because the function gets the value of the variable, not a reference to the variable.
you can possibly just guess which one it is from the last frames locals, wouldn't work if multiple variables have the same value though
yeah, ick
or check the last frame's code 
i know it's kind of the point of this channel to do crazy things, so I guess go ahead.
I'm prob gonna write a proof of concept that'll examine the calling co_code to get a name and then loop up frames to find it and replace it
Looks awesome!
For more dynamic printing perhaps allow for the passing to take upon the length of the longest element + an offset, to prevent small lists being too far apart.
e.g. if an entire column contains only 2 elements per list, there would be no need to justify it with 20 spaces; more like 12 spaces.
Although, thats just a quality of life feature, and may be unnecessary for your current use.
!e ```py
from ctypes import *
def foo(ref_x):
res = ref_x + 1
if eval(f"ref_x is (_ := {ref_x})"):
print(f"warning: {ref_x} will be turned into {res}")
POINTER(c_uint).from_address(id(ref_x)+int.basicsize).contents = POINTER(c_uint).from_address(id(res)+int.basicsize).contents
c_ssize_t.from_address(id(ref_x)+int.basicsize - sizeof(c_void_p)).value = c_ssize_t.from_address(id(res)+int.basicsize - sizeof(c_void_p)).value
a = 1233
foo(a)
print(a)
b = 2
foo(b)
print(b)
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | 1234
002 | warning: 2 will be turned into 3
003 | 3
that's assigning by id
notepad++, and no.
If I need to debug a line, I "expand" it temporarily.
imma just casually play 2048 in 4 dimensions
is 16 spawns per swipe too much? I feel like it's a bit chaotic.
also aesthetics, should I make the vertical hyperborders thicker?
Actually I have to they're currently the same width as the subborders
Sort of
Cell separation width is the same
ofc i can't, i wanna tho
ok what ifi
do this:
!e
def foo(x):
a = globals()[x.__name__]
a += 1
globals()[x.__name__] = a
a = 10
print(a)
foo(a)
print(a)
@fair quartz :x: Your eval job has completed with return code 1.
001 | 10
002 | Traceback (most recent call last):
003 | File "<string>", line 8, in <module>
004 | File "<string>", line 2, in foo
005 | AttributeError: 'int' object has no attribute '__name__'. Did you mean: '__ne__'?
!e a = 4; print(*globals())
@fair quartz :white_check_mark: Your eval job has completed with return code 0.
__name__ __doc__ __package__ __loader__ __spec__ __annotations__ __builtins__ a
!e a = 5; print(*dir(a))
@fair quartz :white_check_mark: Your eval job has completed with return code 0.
__abs__ __add__ __and__ __bool__ __ceil__ __class__ __delattr__ __dir__ __divmod__ __doc__ __eq__ __float__ __floor__ __floordiv__ __format__ __ge__ __getattribute__ __getnewargs__ __gt__ __hash__ __index__ __init__ __init_subclass__ __int__ __invert__ __le__ __lshift__ __lt__ __mod__ __mul__ __ne__ __neg__ __new__ __or__ __pos__ __pow__ __radd__ __rand__ __rdivmod__ __reduce__ __reduce_ex__ __repr__ __rfloordiv__ __rlshift__ __rmod__ __rmul__ __ror__ __round__ __rpow__ __rrshift__ __rshift__ __rsub__ __rtruediv__ __rxor__ __setattr__ __sizeof__ __str__ __sub__ __subclasshook__ __truediv__ __trunc__ __xor__ as_integer_ratio bit_count bit_length conjugate denominator from_bytes imag numerator real to_bytes
ok then
@fair quartz
!e
def foo(x):
xid = id(x)
xname = None
for glob in globals():
if id(glob) == xid:
a = globals()[glob]
xname = glob
a += 1
globals()[xname] = a
a = 10
print(a)
foo(a)
print(a)
@fair quartz :x: Your eval job has completed with return code 1.
001 | 10
002 | Traceback (most recent call last):
003 | File "<string>", line 14, in <module>
004 | File "<string>", line 9, in foo
005 | UnboundLocalError: local variable 'a' referenced before assignment
lemme look at that
warning: any number in range(-5, 257) will be overwritten with itself plus one
tooo we can do that?
so like i still have to make something that's better than what i just did
yeah could you tell me how to get a var with ctypes if we know the id?
@quartz wave sorry for the ping
so do we just do
ctypes.POINTER(ctypes.c_uint).from_address() ?
and im guessing .contents is a property which supports getting and setting (and delling) but im wondering why need all this whacky stuff to change ints? can't we reassign it to the value of res?
to the last question in this message, no
def foo(ref_x):
res = ref_x + 1 # the result
if eval(f"ref_x is (_ := {ref_x})"): # if the integer is cached...
print(f"warning: {ref_x} will be turned into {res}") # warning, there's no turning back from converting a cached integer
pointer(POINTER(c_uint).from_address(id(ref_x)+int.__basicsize__)).contents = pointer(POINTER(c_uint).from_address(id(res)+int.__basicsize__)).contents
# ^ pointer to the digits of ref_x ^ pointer to the digits of res
# so it basically changes the digits array of ref_x, and may leak the old one
c_ssize_t.from_address(id(ref_x)+int.__basicsize__ - sizeof(c_void_p)).value = c_ssize_t.from_address(id(res)+int.__basicsize__ - sizeof(c_void_p)).value
# ^ size of ref_x ^ size of res
# so then it changes the internal size of ref_x
no
it's just impossible to know what variable has the exact value as ref_x
because there are cached integers
in this range
so is won't work
equivalent code in C: ```c
#define PY_SSIZE_T_CLEAN
#include "Python.h"
int foo(PyLongObject *ref_x) {
PyLongObject *res;
PyObject *string;
Py_ssize_t ref_x_size;
digit *new_ob_digit;
int status;
res = PyNumber_InPlaceAdd(ref_x, _PyLong_GetOne());
if (res == NULL) {
return -1;
}
ref_x_size = Py_SIZE(ref_x);
if (((size_t)ref_x_size) + 1U < 3U) {
if (ref_x_size) {
digit first_digit = ref_x->ob_digit[0] * ref_x_size;
if (first_digit + _PY_N_SMALLNEGINTS < 0 || first_digit >= _PY_N_SMALLPOSINTS) {
goto change;
}
}
string = PyUnicode_FromFormat("warning: %u will be turned into %U", first_digit, res);
if (string == NULL) {
goto error;
}
status = PyObject_Print(string, stdout, Py_PRINT_RAW);
Py_DECREF(string);
if (status < 0) {
goto error;
}
}
change:
// it's just hard to not have a memory leak here
ref_x->ob_digit = res->ob_digit;
Py_SET_SIZE(ref_x, Py_SIZE(res));
return 0;
error:
Py_DECREF(res);
return -1;
}
That's just the command line interface level.
It's around the same width as the "graphical" user interface. I put graphical in quotation marks because it does not use a gui
this is in the terminal
only ascii characters are printed.
and that does the entire display.
that's how games were coded in the early days of computers, but they only used 8 colours
how the code looks in vscode. the document outline on the right is rather pointless.
!e ```py
@type.call
class foo:
def getattribute(self, name):
if type(globals()[name])is int:
globals()[name]+=1;return globals()[name]
else:return super().getattribute(name)
a = 2 + 2
foo. a
print(a)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
5
isnt that same as foo.a
yeah, but the space puts emphasis on its relation to the global name a
esoteric code is an artform
upload to a github repo xD
!e
class PythonPrivateClass:
def __getattribute__(self, name):
raise ValueError("this class is private")
priv_class = PythonPrivateClass()
priv_class.a```
@jovial monolith :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 5, in <module>
003 | File "<string>", line 3, in __getattribute__
004 | ValueError: this class is private
!e
class PythonPrivateClass:
def __getattribute__(self, name):
raise ValueError("this class is private")
priv_class = PythonPrivateClass()
priv_class.super().a```
@jovial monolith :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 5, in <module>
003 | File "<string>", line 3, in __getattribute__
004 | ValueError: this class is private
!e
@type.__call__
class Ugh:
def __getattribute__(self, name):
globals()[name] = "ughh"
Ugh.a
print(a)
@fair quartz :white_check_mark: Your eval job has completed with return code 0.
ughh
lol
use Cells
>>> from types import CellType as C
>>> def f(ref):
... ref.cell_contents += 1
...
>>> a = 1
>>> c = C(a)
>>> f(c)
>>> a = c.cell_contents
>>> a
2
!e
from types import CellType as C
def f(ref):
ref.cell_contents += 1
a = 1
c = C(a)
f(c)
a = c.cell_contents
print(a)
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
2
also you can use one-element list
!e
def f(ref):
ref[0] += 1
return ref
a = 1
ref = [a]
f(ref)
a = ref[0]
print(a)
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
2
jump_hurdle()
what do i do if my class method is wrapped by another class and thus is called with the wrong self?
!e
import pickle as rick
# lovin this joke haha
@vale tangle :warning: Your eval job has completed with return code 0.
[No output]
very esoteric
!e
print(*(''.join(chr(34+len((z:=0j)or[(z:=z*z+x/64*2.67-2.1+y/32*2.5j-1.25j)for _ in[0]*61if abs(z)<=2]))for x in range(64))+'\n'for y in range(32)),sep='')
@severe canyon :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/katoqexibu.txt?noredirect
ah man :(
!e
print(*(''.join(chr(34+len((z:=0j)or[(z:=z*z+x/64*2.67-2.1+y/32*2.5j-1.25j)for _ in[0]*61if abs(z)<=2]))for x in range(64))+'\n'for y in range(32)),sep='')
@severe canyon :white_check_mark: Your eval job has completed with return code 0.
001 | #############$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%$$$$$$$$$$$$$
002 | ############$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%&&&&&%%%%%%%$$$$$$$$
003 | ###########$$$$$$$%%%%%%%%%%%%%%%%%%%%&&&&&&')-)''&&&&%%%%%$$$$$
004 | ##########$$$$$$%%%%%%%%%%%%%%%%%%%&&&&&&&'''(-8*)-'&&&&&%%%%%$$
005 | ########$$$$$%%%%%%%%%%%%%%%%%%%&&&&&&&&&'''()*-3,)(''&&&&&%%%%%
006 | ########$$$%%%%%%%%%%%%%%%%%%%&&&&&&&&&'''().04T_0-;('''&&&&%%%%
007 | #######$$$%%%%%%%%%%%%%%%%%%&&&&&&&&''(((()*5A____L,)((''''&&&%%
008 | ######$$%%%%%%%%%%%%%%%%%%&&&&&&&''()*+***+,.E____2,+*)((()*'&&%
009 | #####$$%%%%%%%%%%%%%%%%&&&&&&''''(()4LPF.__N________<_7,,2,]+'&&
010 | #####$%%%%%%%%%%%%%%%&&&'''''''((()*,:_____________________.*('&
011 | ####$%%%%%%%%%%%%&&&'''''''''((()*453_____________________0+)('&
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/haqaqukosa.txt?noredirect
made my mandlebrot golf into ascii output ¯_(ツ)_/¯
that is beautiful!
can I has an ANSI Sequence version?
yesterday I was discussing in #python-discussion why mathematics is essential to programming.
you said golf?
r=range;print(*(''.join(chr(34+len((z:=0j)or[(z:=z*z+x/64*2.67-2.1+y/32*2.5j-1.25j)for _ in[0]*61if abs(z)<=2]))for x in r(64))+'\n'for y in r(32)),sep='')
actually it might be the same size
range vs r=;rr
5170 characters, 45 lines, and it is harder to lose than win;
4-dimensional 2048 is now complete and fully debugged.
that took me 4 days.
The previous file output version was golfed
This is just a conversion
No golfing there
Replace 34 with 31, and 61 with 64, then it looks better
But python bot wouldn't let me :(
why not?
lmao
.
it must've outputted `
Indeed it did
optemisashun
a=[a()for _ in range(16)];{[a[n+_].move(*r())for n in range(16-_)]and()or()for _ in iter(lambda:len({*a}),16)}
a is the list of coordinates for the 16 cells the game starts on.
I just realised I could use random.choice instead
It took soooooo long, but I finally played far enough to test a feature: numbers more than 7 digits long
the android version I've been playing stops when you get to 7 digits. :(
I'm smarter than the android devs
Mine goes up to 21 digits
after that, it will keep going, but the board will be distorted
Right, these people could just lower the font size, but no?
So clarify, yours is 4d?
yes
Nice
there is up, down, left, right, in, out, forwards and backwards
if you play with just wasd, it's like playing 16 games of 2d 2048 at once
Also, terminal based, which is based in its own dimension.
can you elaborate
whats the original code
and what properties do you want in the modified code
well
here
while True:
print("yes")
print("no")
print("nah")
i wanna split 2 print out of the While statesment
anyway to do that?
can you use proper grammar, cant really understand sry
this specifically
easily explain
i'll take print("no") and print("nah") out of while statesment
but how
it's for one line code
take it out
o0f while statesment
in 1 line
please understand i don't know how to explain it out
they mean take it out in a one-line statement
while True: print("yes") #HELP ME SPLIT THEM BOTH OUT
yes!
like you can't do this ```py
while True: print("yes"); "have beyond outside of the while loop"; print("no"); print("nah")
yeah we can't just do that
it will stay in while statesment
giving it a tuple caused syntax error
well i dont believe it's possible, it expects a newline to delimit the "block". another option is to use a comprehension over an infinite iterable
it's possible
how do you know
well
you just want one-liner while loop?
with basic while its not possible
anyway to do?
you can do this:
[some_function for(_)in map(sum,enumerate(iter(int,1)))];another_function_here```
there must be a way to delimit the while. that way is the newline. with your constraint, it's not possible.
map(sum,enumerate(iter(int,1))) is an alternative to while True
^
while cond: thing
[thing for _ in iter(lambda:not cond,1)]
alr thanks for help
nah just saying that ( and [ was not closed is the worst thing happens without even realizing it
@bronze merlin Так ты русский?
da
впервые вижу тут русского лол
i don't have my keyboard layout rn i couldn't write
!e
b=lambda a: chr(int(('0'(8-len(bin(ord(a))[2:]))+bin(ord(a))[2:])[4:]+('0'(8-len(bin(ord(a))[2:]))+bin(ord(a))[2:])[::-1][4:][::-1],2));exec(''.join([b(z)for z in "\x07'\x96æG\x82r\x84VÆÆö\x12\x02ä\x966V\x02Gö\x02ÖVVG\x02\x97öWÂ\x02\x94ÅrÖ\x02ö&fW76\x16GVF\x12r\x92"]))
@split salmon :white_check_mark: Your eval job has completed with return code 0.
Hello! Nice to meet you, I'm obfuscated!
fr?
yes
obfuscasted is in it's name
yow static cast char
I coded it myself
can you explain this part
?
map(sum,enumerate(iter(int,1)))
basically you're iterating over int infinite times
map(sum,..) isn't even needed here but it works anyway
what it basically does
iterating over a type
with iter(int,1) you're just making a iterator object, and enumerating it using enumerate(...)
full list of magic methods?
!e print(dir(object))
@knotty delta :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__']
!e print("hello world")
@azure meteor :white_check_mark: Your eval job has completed with return code 0.
hello world
@azure meteor :white_check_mark: Your eval job has completed with return code 0.
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}
#bot-commands
@azure meteor ❌ Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | WrongChannelError: please use #bot-commands
@floral meteor do you implemented the functions and classes in bf snippet?
if not, i think it will be better with this design:
FUNCTION(NAME)[
function body or lambda
]
or
NAME: FN(..argument list..)[function body]```
pow returns a float meaning it has limited precision
- as olivia said,
powreturns a float which has only about 15 digits of precision - totally not the right channel to ask for help, see #❓|how-to-get-help
https://github.com/chilaxan/pysnippets/blob/main/byref.py i ended up writing a conclusive implementation
@fleet bridge ^ you might find this interesting
@burnt pasture I ended up writing an implementation, its awful
i thought you were saying that I ended up writing an implementation 🙂
Python/ceval.c lines 2869 to 2878
TARGET(STORE_GLOBAL) {
PyObject *name = GETITEM(names, oparg);
PyObject *v = POP();
int err;
err = PyDict_SetItem(GLOBALS(), name, v);
Py_DECREF(v);
if (err != 0)
goto error;
DISPATCH();
}```
it uses PyDict_SetItem which assumes GLOBALS() is a dict (not a subclass)
but you can set GLOBALS() to a dict subclass by passing a dict subclass into the function constructor
LOAD_GLOBAL has checks (and uses the less specialized path for dict subclasses)
yea theres a lot needed for it to even start to cover all the edge cases
and i prob missed many
im proud of this function py def find_segments(co_code, idx, end_size): # take in set of opcodes and final stack size # determine segments of code for each final stack item stack_size = 0 isjump = [*dis.hasjabs, *dis.hasjrel].__contains__ segments = [] seg = bytearray() seg_marker = 0 while isjump(co_code[idx]) or stack_size != end_size: opcode = co_code[idx] oparg = co_code[idx + 1] seg[:] = bytes([opcode, oparg]) + seg jump = False if isjump(opcode) else None change = dis.stack_effect(opcode, oparg if opcode >= dis.HAVE_ARGUMENT else None, jump=jump) stack_size += change seg_marker += change idx -= 2 if seg_marker == 1 and not isjump(co_code[idx]): segments.append(seg) seg = bytearray() seg_marker = 0 return list(reversed(segments)) which i use to split the arguments of a function call into sets of opcodes
lets me look for direct variable loads in the function call at runtime (to find the names in the upper frame)
doesnt even include the asm_hook and f_locals libs that are on that repo as well
so i have a simpler solution that involves a snippet you posted in #esoteric-python some time ago
!e ```py
def getframe(level=0):
try:raise
except Exception as e:
frame = e.traceback.tb_frame.f_back
for () in [()] * level:
frame = frame.f_back
return frame
def foo(val, frame=0):
frame = getframe(frame + 1)
name = frame.f_code.co_code[frame.f_lasti - 1]
load_inst = frame.f_code.co_code[frame.f_lasti - 2]
if load_inst in {101, 116}:
frame.f_locals[frame.f_code.co_names[name]] += 1
elif load_inst in {124, 135, 136, 148}:
frame.f_locals[(frame.f_code.co_varnames + frame.f_code.co_cellvars + frame.f_code.co_freevars)[name]] += 1
else:
raise Exception("passed value is a constant")
a = 5
foo(a)
print(a)
b = 1233
foo(b)
print(b)
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | 6
002 | 1234
it's only now i realized i could've just used frame.f_locals instead of complex opcode replacing stuff
Yea that works but mine is more generalized so it works in almost any situation
And thru a decorator so you can wrap arbitrary functions
like ```py
a = "a"
@byref
def foo(b: byref):
b *= 2
foo(a)
print(a)
``` would output aa?
yup
that works. I've noticed a few edge cases surrounding kwargs and how they are done with CALL_FUNCTION_EX and CALL_FUNCTION_KW that ill try to fix tomorrow, but as of now most calling conventions work (or are explicitly forbidden)
i had to forbid stuff like foo(*a, ref_var, *b) because it wasn't possible to know how a would expand
i could also theoretically hook into function construction to make the decorator apply itself automatically but ill do that once i have those edge cases fixed
if you want to mess with it, i wrote it specifically for 3.10 (no idea if it works on other versions) and you can just clone it from the github link
would be nice if it wasn't just limited to globals
but damn there's gonna be a lot of complexity
it definitely won't work in 3.11
there they changed a lot of stuff
lol
well it's not windows-compatible so i can't improve it or something
3.11 sounds like a nightmare already
yes
new opcodes
3.10 was already a bummer.
match case where instead of otherwise or default it's case _ which makes it confusing if I wanna use _ as a variable
>>> dis("a(b)")
0 RESUME 0
1 2 LOAD_NAME 0 (a)
4 LOAD_NAME 1 (b)
6 PRECALL_FUNCTION 1
8 CALL 0
10 RETURN_VALUE
``` 3.11 `a(b)`
!e ```py
from dis import dis
dis("a(b)")
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_NAME 0 (a)
002 | 2 LOAD_NAME 1 (b)
003 | 4 CALL_FUNCTION 1
004 | 6 RETURN_VALUE
3.10 a(b)
and I already have {a:lambda...,b:lambda:...}.get(value, d)() for switching
so I'm gonna stay in 3.9
maybe 3.9.7, although I'm still on 3.9.2 cos Im lazy
speaking of lazy I made an autosolver for 4D 2048, and it's reached the quarter-billion tile already
top left black cell
the autosolver is really lazy
at least you made one
!e 3.10 keyword call ```py
from dis import dis
dis("a(b=3)")
def run(interface):
print('\x1bc');from random import randint as r
while not interface.eng.gameend:
interface.next_frame(interface.eng.swipe(r(0,7)))
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_NAME 0 (a)
002 | 2 LOAD_CONST 0 (3)
003 | 4 LOAD_CONST 1 (('b',))
004 | 6 CALL_FUNCTION_KW 1
005 | 8 RETURN_VALUE
then 3.11 keyword call ```py
dis("a(b=3)")
0 RESUME 0
1 2 LOAD_NAME 0 (a)
4 LOAD_CONST 0 (3)
6 PRECALL_FUNCTION 1
8 KW_NAMES 1
10 CALL 1
12 RETURN_VALUE
precall function whaaaaat
TARGET(KW_NAMES) {
assert(oparg < PyTuple_GET_SIZE(consts));
call_shape.kwnames = GETITEM(consts, oparg);
DISPATCH();
}
TARGET(LOAD_CONST) {
PREDICTED(LOAD_CONST);
PyObject *value = GETITEM(consts, oparg);
Py_INCREF(value);
PUSH(value);
DISPATCH();
}
like the only difference between these two is that the latter pushes to stack
TARGET(PRECALL_FUNCTION) {
/* Move ownership of reference from stack to call_shape */
call_shape.callable = PEEK(oparg + 1);
call_shape.postcall_shrink = 1;
call_shape.total_args = oparg;
assert(call_shape.kwnames == NULL);
#ifdef Py_STATS
extern int _PySpecialization_ClassifyCallable(PyObject *);
SpecializationStats *stats =
&_py_stats.opcode_stats[PRECALL_FUNCTION].specialization;
stats->failure++;
int kind = _PySpecialization_ClassifyCallable(call_shape.callable);
stats->failure_kinds[kind]++;
#endif
DISPATCH();
}
PRECALL_FUNCTION
>>> dis("a + 3")
0 RESUME 0
1 2 LOAD_NAME 0 (a)
4 LOAD_CONST 0 (3)
6 BINARY_OP 0 (+)
8 RETURN_VALUE
``` also `BINARY_ADD` is now `BINARY_OP 0`
I've been calling this an AI all day just because it looks like one and it's doing better at 4D 2048 then me.
nice
I managed to screenshot it in the middle of printing.
and there's the evidence that this is in the terminal.
this is smarter than me. D:
and it does that single purpose better than me
although it's been running for about 36 hours
to get the quarter-billion tile
The rationale behind the new opcodes is here:
https://github.com/faster-cpython/ideas/issues/267#issuecomment-1042928991
By breaking up call into two opcodes, you can have 1 that deals with the type of callable (Python, method, builtin, c function, etc), and then one that deals with the sort of arguments passed (positional, positional+keyword, complex unpacking). Each of those can then be swapped to specialised opcodes independently.
code golf challenge: print all of the lyrics to Never Gonna Give You Up by Rick Astley in the least amount of characters without using web requests or files
someone's gonna think up of some crazy formula to generate the text.
most people will just apply lossless compression to the string
I'm not gonna participate cos there's a massive spider in my bathroom
I made eye contact with it
well, two of its 8 eyes
You can do both at the same time :)
it's looking at me funny
you can use compression and weird magic
mathematical magic
So far my record in my own programming language is 57,370ish characters
I got 4 dimensional 2048 in 5000 characters exactly
because I used a python program to generate it
Not even math can save you here https://esolangs.org/wiki/Brainfuckn't
and the last few characters were a comment that said #5000 chars
Hello, World! with a trailing newline in 104 characters is the best I could do with this crappy language
++++++~>~>>~>~<<<<.@^>^>>^<<<.@>>>>^..<<<<@|.-@>>>>>.[>]<.+^<.@.[>]<^<<<.>>^<<<<<.>>&<<.[>-]~++~++<.--@.
It's hard to do math magic when you don't have arithmetic
To add 2 8-bit numbers, I believe it took me around 300ish characters
"bit fuckery"
"bit fuckery"
basically, standard formulas for generating output don't work here
and don't look at my shitty C++ code that I used to implement the language
I'm working on a rewrite in Rust and maybe I could do a second rewrite in C++
however, it uses 8x more memory to work on bytes instead of bits to allow vectorization of certain operations
rn, a single ^ is like 110 assembly instructions, but there's a bunch of vectorization
try to codegolf this lexer
tried my best
def lex(_0,_1,_2=0,_3=[]):
while _2<len(_0):
_4=None
for(_5)in _1:
if(_4:=re.compile(_5[0]).match(_0,_2)):
_3+=([],[(_4.group(0),_5[1])])[len(_5)>1and _5[1]is not None];break
if not _4:sys.stderr.write('Illegal character: %s on line %d'%(_0[_2],_2))
else:_2=_4.end(0)
return _3```
input:
const x: str = "hello";```
output:
('const', 'RESERVED') ('x', 'ID') (':', 'RESERVED') ('str', 'ID') ('=', 'RESERVED') ('"hello"', 'STR') (';', 'RESERVED')```
tokens:
RESERVED = 'RESERVED'
INT = 'INT'
STR = 'STR'
ID = 'ID'
tokens = [
(r'[ \n\t]+', None),
(r'#[^\n]*', None),
(r'\=', RESERVED),
(r'\:\=', RESERVED),
(r'\(', RESERVED),
(r'\)', RESERVED),
(r'\{', RESERVED),
(r'\}', RESERVED),
(r'\[', RESERVED),
(r'\]', RESERVED),
(r'\:', RESERVED),
(r'\;', RESERVED),
(r'\+', RESERVED),
(r'\-', RESERVED),
(r'\*', RESERVED),
(r'\/', RESERVED),
(r'\<\=', RESERVED),
(r'\<\=\=', RESERVED),
(r'\<', RESERVED),
(r'\<\<', RESERVED),
(r'\>\=', RESERVED),
(r'\>\=\=', RESERVED),
(r'\>', RESERVED),
(r'\>\>', RESERVED),
(r'\=\=', RESERVED),
(r'\=\=\=', RESERVED),
(r'\!\=', RESERVED),
(r'\!\=\=', RESERVED),
(r'and', RESERVED),
(r'or', RESERVED),
(r'not', RESERVED),
(r'if', RESERVED),
(r'elif', RESERVED),
(r'else', RESERVED),
(r'while', RESERVED),
(r'let', RESERVED),
(r'const', RESERVED),
(r'[0-9]+', INT),
(r'\".*\"', STR),
(r'[A-Za-z][A-Za-z0-9_]*', ID),
]```
_0 is input text and _1 is token list
I was the one who wrote the page and the language :)
the documentation is pretty bad lmao
it doesn't exactly say how to put a character into the tape (like are the most significant bits placed first or ???)
I'm also going to try to brute force a shorter hello world
but for that, I need to make a safe version of the interpreter that can take a file as an argument
and also doesn't segfault
and I need to figure out how to make sure I generate a program that halts
segfault go brrrrrrr
seems like an alternative of brainfuck
>+++++++++[<++++++++>-]<.>+++++++[<++++>-]<+.+++++++..+++.[-].>+++++++++[<++++++++++>-]<---.>++++[<++++++>-]<.+++.------.--------.[-]>+++[<+++++++++++>-]<.
Hello World! in bf, pretty similar
not really similar at all in how it works. They look similar because brainfuckn't IS a superset of a brainfuck with binary cells
and I decided to use similar notation
Hmm, alright.
the + increases the pointer size, not the pointer value
Any ideas for a concurrent/parallel version of Brainfuck?
I had an idea like this: extend the language with a single ! character. This character sets the current I/O port to the value on the cursor.
By default the I/O port is 0, which means standard input & standard output.
But if you set it to something other than 0, it reads to/writes from a different "thread" with the given port number
what I don't know is to how to spawn these threads from within the language.
Maybe there could be another pair of brackets, like { and }, which sets the program on the thread with the current port?
There is systemf which allows syscalls
you could implement time sharing using brainfuck code itself
I guess, it is Turing complete after all
I was wondering about this in the context of making an HTTP client in brainfuck
it is easier if you make it async, instead of context-switching at any point, like threads do
I think I can make it work by only context switching on . and ,
or even only on ,
Also, I imagined that each thread would have an entirely isolated memory. So it shouldn't matter when they context-switch, right?
!e
def bftopy(bf):
lines = ["async def _bf_fun(io):", " p,x,m=0,0,{}"]
indent = 1
addline = lambda line: lines.append(" " * indent * 4 + line)
for char in bf:
if char == "+":
addline("m[p]=m.get(p,0)+1")
elif char == "+":
addline("m[p]=m.get(p,0)-1")
elif char == ">":
addline("p+=1")
elif char == "<":
addline("p-=1")
elif char == "[":
addline("while m.get(p):")
indent += 1
elif char == "]":
indent -= 1
elif char == "!":
addline("x=m.get(p,0)")
elif char == ".":
addline("await io.write(x,m.get(p,0))")
elif char == ",":
addline("m[p]=await io.read(x)")
return "\n".join(lines)
print(bftopy(", >+!< .>>.<< >+!< .>>.<<"))
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 | async def _bf_fun(io):
002 | p,x,m=0,0,{}
003 | m[p]=await io.read(x)
004 | p+=1
005 | m[p]=m.get(p,0)+1
006 | x=m.get(p,0)
007 | p-=1
008 | await io.write(x,m.get(p,0))
009 | p+=1
010 | p+=1
011 | await io.write(x,m.get(p,0))
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/zuwajuvewo.txt?noredirect
@jagged osprey something like this^
the point of what 🤔
the idea is that they can communicate with messages, using . and ,
!e
import asyncio
def bftopy(bf):
lines, indent = ["async def _bf_fun(io):", " p,x,m=0,0,{}"], 1
addline = lambda line: lines.append(" " * indent * 4 + line)
for char in bf:
if char == "+": addline("m[p]=m.get(p,0)+1")
elif char == "+": addline("m[p]=m.get(p,0)-1")
elif char == ">": addline("p+=1")
elif char == "<": addline("p-=1")
elif char == "[": addline((indent := indent + 1) or "while m.get(p):")
elif char == "]": indent -= 1
elif char == "!": addline("x=m.get(p,0)")
elif char == ".": addline("await io.write(x,m.get(p,0))")
elif char == ",": addline("m[p]=await io.read(x)")
exec("\n".join(lines), (g := {}))
return g["_bf_fun"]
class DummyIO:
def __init__(self, inputs):
self._inputs = list(reversed(inputs))
async def read(self, _port):
if not self._inputs:
await asyncio.Future()
return self._inputs.pop()
async def write(self, port, data):
print(f"{data} on port {port}")
fn = bftopy(", >+!< .>>.<< >+!< .>>.<<")
asyncio.run(fn(DummyIO([5, 6])))
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 | 5 on port 1
002 | 0 on port 1
003 | 5 on port 2
004 | 0 on port 2
lexer update
#[some_decorator]
trait SomeTrait {
field: type;
another_field: int;
some_field: Some<Generic, Expression>;
}
to
('#[some_decorator]', 'DecoratorExpression', (1, (0, 17))) ('trait', 'ReservedKeyword', (2, (0, 5))) ('SomeTrait', 'Identifier', (2, (6, 15))) ('{', 'ReservedLiteral', (2, (16, 17))) ('field', 'Identifier', (3, (2, 7))) (':', 'ReservedLiteral', (3, (7, 8))) ('type', 'Identifier', (3, (9, 13))) ('another_field', 'Identifier', (4, (2, 15))) (':', 'ReservedLiteral', (4, (15, 16))) ('int', 'Identifier', (4, (17, 20))) ('some_field', 'Identifier', (5, (2, 12))) (':', 'ReservedLiteral', (5, (12, 13))) ('Some<Generic, Expression>', 'GenericExpression', (5, (14, 39))) ('}', 'ReservedLiteral', (6, (0, 1)))```
lexer error handling
some_field: Some<Generic, Expression>; ————————————————∆ ---- illegal character (<, 5:18)```
!e ```py
def _(q):
for l in range(3):
y=q[l:]
while not y[0]and any(y[1:]):q+=[q.pop(l)];y+=[y.pop(0)]
for l in range(3):
if not[*{*q[l:l+2]}][1:]:q[l]+=q.pop(l+1);q+=[0]
___=[0,0,0,1],[0,1,1,1],[1,1,1,1],[2,1,2,2]
[_(__)for __ in ]
print()
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
([1, 0, 0, 0], [2, 1, 0, 0], [2, 2, 0, 0], [2, 1, 4, 0])
what even is this field of mathematics called, that I can do these things to these arrays?
dis negrozma is writing to a py file 💀
dont think its mathematics at this point
r,p=range,print
l=x=0
h=9
k=[[0for i in r(10)]for j in r(10)]
for v in r(5):
for i in r(l,h+1):k[v][i]=x;x+=1
for i in r(l+1,h+1):k[i][h]=x;x+=1
for i in r(h-1,l-1,-1):k[h][i]=x;x+=1
for i in r(h-1,l,-1):k[i][l]=x;x+=1
l+=1;h-=1
for i in r(10):
for j in r(10):k[0][j]=" "+str(k[0][j]);p(k[i][j],end=" ")
p()```
how could I golf this
k[0][j]=" "+str(k[0][j])
I think this part can definitely be reworked
!e print(help)
@upbeat sonnet :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 'help' is not defined
i mean
!e py from pydocs import help print(help)
ok?
!e py from pydoc import help print(help)
!e py from pydoc import help print(help)
@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.
<pydoc.Helper instance>
@upbeat sonnet :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | AttributeError: module 'pydoc' has no attribute '__getattr__'
@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.
<method-wrapper '__init__' of module object at 0x7fd133c8bd30>
!e
print("yes") if 1 == 1; print("no") elif 0 == 0;
@bronze merlin :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | print("yes") if 1 == 1; print("no") elif 0 == 0;
003 | ^^^^^^^^^^^^^^^^^^^^^^^
004 | SyntaxError: expected 'else' after 'if' expression
@bronze merlin :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | print("yes") if 1 == 1; print("no") if 0 == 0; else None;
003 | ^^^^^^^^^^^^^^^^^^^^^^^
004 | SyntaxError: expected 'else' after 'if' expression
what are you trying to do
testing some syntax
thanks to you i'm just about to make that syntax possible except for the else part
@bronze merlin :white_check_mark: Your eval job has completed with return code 0.
001 | yes
002 | no
there we go
never thought I would be legitimately doing this, but here we go
tuple
wtf
pointers in python 🤯
!e ```py
#ifndef __cplusplus
#include <stdio.h>
#define and ?
#define or :
#define def int
#define main() main() { a
#define None 0; }
#define print(x) puts(x);
#/*
"""#"/
int
#/
"""#"*/
C = 0;
def main():
print(++C and "C" or "python")
return None
#if 0
main ()
#endif
#else
#include <iostream>
#/*
"""#"/
int main() {
puts("C++");
}
#/
"""#"*/
#endif
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
python
prints C in C, C++ in C++, and python in python
woah how does this work?
not sure how to explain
making a randomizer for a specific pokemon romhack because the universal randomizer doesn't work
rom
uses C preprocessor directives and takes advantage of the fact that python uses # as the starting symbol of a comment
yeah i can tell, but ++C, is that valid python syntax
yes
two unary adds
which do absolutely nothing in python
ah
!e ```py
a = int(pow(2, 31, 2**31-1))
b = 1
print(a is b, a, b)
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
False 1 1
non-cached integers
wat does da third argyument do 
ooh
probably will be fixed in python 3.11
!e
custom_block = ">:)"
def test() -> lambda:\
customblock:
print("hi")
test()
@knotty delta :white_check_mark: Your eval job has completed with return code 0.
hi
custom_block is a part of the lambda i think, and it does nothing
then the : is just the def's
That's amazing
you know code is good when it confuses even people who have studied python grammar for months
lmfao
!e ```py
from fishhook import hook
@hook(type(lambda: 0))
def rrshift(self, other):
return self(other)
@hook(type(print))
def rrshift(self, other):
return self(other)
@hook(type)
def rrshift(self, other):
return self(other)
(
123
>> (lambda x: x*2)
>> str
>> (lambda x: x[::-1])
>> print
)
@languid hare :white_check_mark: Your eval job has completed with return code 0.
642
did you ever figure out a _ replacement
the math operators are easy enough to deal with _, but function calls die
ah never mind i had cursed method chaining, not piping
#bot-commands message

oh wait i could get the original ast with inspect, change it, compile the ast to get its bytecode and rewrite the bytecode to that
so rewrite the function call nodes which have an argument named _ to be lambda _: f(_) instead
https://numba.pydata.org/numba-doc/latest/user/5minguide.html#how-does-numba-work
Numba reads the Python bytecode for a decorated function
seems about right, so we just gotta read the ast, edit, compile a new function
hm
If you could find a way to intercept function calls from the object being passed as argument... I wonder whether audit events or GC hooks could be useful
@languid hare https://paste.pythondiscord.com/edosisaser
probably not foolproof since it'll change it if there's any _ at all
might be some way to break it with sthn like for x, _ in ...
!e this could be used instead of modulus for modulus operations! ```py
a = 34
print(pow(a,1,5))
print(34%5)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 4
002 | 4
obfuscation 100
i can't believe i didn't spot this bug when i added long_mod to Objects/longobject.c
wow
im so confused 😭 i started python not long ago and i wanted to see if i could earn anything in this server but everything is so complicaated
probably because you're in this channel?
is this a bad channel?
for beginners yes
you should stay away from this channel if you don't wanna be confused
this confusing is channel
this channel is more for doing over the top things with python. dont worry too much.
did I make a new mathematics?
It... tastes... like discrete mathematics, but the only field I recognised here is set theory where I used it to obfuscate determining equality of q[l] == q[l+1]
me just casually making this code windows-compatible using a modified cpython
it works
noice
hey what if i made a pull request for this
whats the non confusing channel?
and any tips for where i can learn more python
they all look confusing
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
oh thx!
any tips where I can learn more #esoteric-python
probably not
you can look at IFcoltransG's guide but he's kinda missing for 2 months right now and may not have updated his esoteric python guide
🙆♀️
today i just learned that you can use iterator.__setstate__ to reset an iterator
not all iterators support __setstate__ its part of how pickle is implemented
!e py i = iter(range(2000)) for _ in range(1000): next(i) print(i.__reduce__())
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
(<built-in function iter>, (range(0, 2000),), 1000)
!e ```py
i = iter(range(0, 2000))
i.setstate(1000)
print(next(i))
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
1000
is this the old advanced python channel?
someone's probably already done this but
why not make a brainfuck compiler by simply running it's compiler for c in python
OT but your MAL is amazing
ty

does anyone have experience with this error? SystemError: no locals when loading <NULL>
here's the code i was playing around with when i encountered this error:
def print_members(obj):
for attr in dir(obj):
if attr[:2] == '__':
continue
val = getattr(obj, attr)
print(f'{attr}: {val}')
class abc:
def __init__(self):
pass
print_members(abc.__init__.__code__)
a = abc()
src = 'self.x = 123\nself.stu = "hola"'
code_obj = compile(src, __file__, 'exec')
code_obj = code_obj.replace(
co_argcount = 1,
co_posonlyargcount = code_obj.co_posonlyargcount,
co_kwonlyargcount = code_obj.co_kwonlyargcount,
co_nlocals = code_obj.co_nlocals,
co_stacksize = code_obj.co_stacksize,
co_flags = 0x43,
co_firstlineno = code_obj.co_firstlineno,
co_code = code_obj.co_code,
co_consts = code_obj.co_consts,
co_names = ('x', 'stu'),
co_varnames = ('self',),
co_freevars = code_obj.co_freevars,
co_cellvars = code_obj.co_cellvars,
co_filename = code_obj.co_filename,
co_name = '__init__',
co_lnotab = code_obj.co_lnotab
)
print()
print_members(code_obj)
abc.__init__.__code__ = code_obj
b = abc()
print(dir(a))
print(dir(b))
the full traceback:
Traceback (most recent call last):
File "/home/anthy/Work/py/dex-tools/pydex/test.py", line 53, in <module>
b = abc()
File "/home/anthy/Work/py/dex-tools/pydex/test.py", line 1, in __init__
def print_members(obj):
SystemError: no locals when loading 'x'
found the error:
co_namesdoesn't have 3 elements (you need to add some sort of padding, or replace someLOAD_NAMEopargs with the correct numbers)co_nlocals,co_argcount, andco_posonlyargcountmust be 1- the code still thinks
selfis inco_names, so you have to dopy co_code = code_obj.co_code.replace(bytes((LOAD_NAME, 0)), bytes((LOAD_FAST, 0))),where ```py
LOAD_FAST = import('dis').opmap['LOAD_FAST']
LOAD_NAME = import('dis').opmap['LOAD_NAME']
4. this is not so much of an error but more like a tip: if you're just gonna do ```py
co_X = code_obj.co_X,
``` then just don't do it at all, the code will still be the same since you're doing `code_obj.replace`
!e ```py
class abc:
def init(self):
pass
a = abc()
src = 'self.x = 123\nself.stu = "hola"'
code_obj = compile(src, 'main.py', 'exec')
LOAD_FAST = import('dis').opmap['LOAD_FAST']
LOAD_NAME = import('dis').opmap['LOAD_NAME']
code_obj = code_obj.replace(
co_argcount = 1,
co_posonlyargcount = 1,
co_nlocals = 1,
co_flags = 0x43,
co_code = code_obj.co_code.replace(bytes((LOAD_NAME, 0)), bytes((LOAD_FAST, 0))),
co_names = ('NAME FOR PADDING ONLY', 'x', 'stu'),
co_varnames = ('self',),
co_name = 'init',
)
abc.init.code = code_obj
b = abc()
print(dir(a))
print(dir(b))
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
002 | ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'stu', 'x']
so it seems to work now
noice, i might have some questions still but let me read through and analyze this
why does co_posonlyargcount have to be 1? in the class function __init__, it's set to 0. does this work differently for class functions than regular functions?
Hey @steady perch!
It looks like you tried to attach file type(s) that we do not allow (.zip). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.
Feel free to ask in #community-meta if you think this is a mistake.
it's because the self argument is positional-only i think
No, that's #internals-and-peps
We swallowed most of their subtopics and left them with only internals and peps to talk about
lmao
!e ```py
class A:
def init(self):
self.b = 15
self.c = self.b, 8
print((A.init.code.co_stacksize))
@lime bane :white_check_mark: Your eval job has completed with return code 0.
2
remember I made 4 dimensional 2048?
well it's now functional as a command line interface
The engine can load a game from a 4x4x4x4 array, which can be generated from eval(str(engine))
with all this implemented, I still gotta make it a nice round number by adding a comment at the end # this source code for 4D 2048 is exactly 5000 characters, even with this extremely lengthy comment at the end of the file.
!e python locals().update({f"vector{i}d": tuple[(float,)*i] for i in range(2, 10)}) print(vector2d) print(vector4d)
@sleek flume :white_check_mark: Your eval job has completed with return code 0.
001 | tuple[float, float]
002 | tuple[float, float, float, float]
@craggy bear :warning: Your eval job has completed with return code 0.
[No output]
@craggy bear :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | print(u fuck)
003 | ^^^^^^
004 | SyntaxError: invalid syntax. Perhaps you forgot a comma?
!e
print('"u fuck"')
@craggy bear :white_check_mark: Your eval job has completed with return code 0.
"u fuck"
Can someone help me i want to translate python to lua but python has functions that lua does not have
like inits and import and classes how would i even use these in lua?
aight so i got a spicy one, anyone know why my code runs faster when i introduce an artificial delay into it? when its commented out im running ~40fps and with it in the code i get ~60. Programs intended purpose is live video analysis
!e
def sqrt(n):
if n < 0: return 0
fn = len(str(n)) * 100
fp = 0
while fn != fp:
fp = fn
fn = 0.5 * (fp + n / fn)
return fn
print(sqrt(634))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
25.179356624028344
!e
def sqrt(n):
if n < 0: return 0
fn = len(str(n)) * 100
fp = 0
while fn != fp:
fp = fn
fn = 0.5 * (fp + n / fn)
return fn
print(sqrt(625))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
25.0
god it works 🙌
Does simulating an Operating System in Python (Terminal) counts as esoteric?
any python weirdness counts as esoteric
like modifying bytecode, obfuscation, code gore, python vm languages, golfing, etc.
Hey, if anyone like me is looking for small golfing challanges, maybe you could try making roman numerals to decimal converter
Good Luck
!e
v={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
f=lambda n:(s:=0)or[(s:=s+(a:=v[n[i]])-(a>(b:=v[n[i-1]])and s)*2*b)for i in range(len(n))][-1]
print(f('MMMM'))
print(f('MMXXII'))
print(f('IV'))
@severe canyon :white_check_mark: Your eval job has completed with return code 0.
001 | 4000
002 | 2022
003 | 4
v={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
f=lambda n:(s:=0)or[(s:=s+v[c]-(v[c]>(a:=v[n[i-1]])and s)*2*a)for i,c in enumerate(n)][-1]
shorter
Slightly shorter
v=dict(zip("IVXLCDM",[1,5,10,50,100,500,1000]))
f=lambda n,s=0:[(s:=s+v[c]-(v[c]>(a:=v[n[i-1]])and s)*2*a)for i,c in enumerate(n)][-1]
nice
is this a roman numeral to integer golf 👀
oh nvm my golf was int to roman numeral
e.e
oo ok
@ruby prawn ❌ Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | WrongChannelError: unable to get help from this channel. See how-to-get-help for more information
!e ```py
import importlib
def _0imp(_0,_1=None,_2=None,_3=(),_4=0):
try:_5=_1['name']if _1 else'main'
except KeyError:_5='main'
if'os'==_0:
if any((_xx:=_x)in['remove','rmdir','unlink']for(_x)in _3 or[]):raise ImportError(f"'{_xx}' is restricted.")
elif'sys'==_0:
if any((_xx:=_x)in['exit']for(_x)in _3 or[]):raise ImportError(f"'{_xx}' is restricted.")
elif'importlib'==_0:raise ImportError(f"module '{_0}' is restricted.")
return importlib.import(_0,_1,_2,_3,_4)
builtins.dict['import']=_0imp
from os import rmdir
@sly root :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 13, in <module>
003 | File "<string>", line 6, in _0imp
004 | ImportError: 'rmdir' is restricted.
noice
anyone wanna add anything to cpython
!e ```py
import importlib,types,dis,sys
def _0hook(_0,_1):
if'exec'==_0 and _1:
if _1 and isinstance(_1[0],types.CodeType):
_2,_3=_1[0],None;_4=[dis.opname[_x]for(_x)in _2.co_code]
for(_i,_n)in enumerate(_4):
if'STORE_NAME'==_n:_3=_2.co_code[_i+1];break
if'LOAD_NAME'==_n:return
if _2 is not None and _3 is not None:
if(_5:=_2.co_names[_3])in['_0hook','_0imp']:
raise Exception("cannot re-assign variable")
def _0imp(_0,_1=None,_2=None,_3=(),_4=0):
try:_5=_1['name']if _1 else'main'
except KeyError:_5='main'
if'os'==_0 and any((_xx:=_x)in['remove','rmdir','unlink']for(_x)in _3 or[]):raise ImportError(f"'{_xx}' is restricted.")
elif'sys'==_0 and any((_xx:=_x)in['exit']for(_x)in _3 or[]):raise ImportError(f"'{_xx}' is restricted.")
elif'importlib'==_0:raise ImportError(f"module '{_0}' is restricted.")
return importlib.import(_0,_1,_2,_3,_4)
builtins.dict['import']=_0imp
import('sys').addaudithook(_0hook)
from os import rmdir
_0imp=None
@sly root :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 24, in <module>
003 | File "<string>", line 16, in _0imp
004 | ImportError: 'rmdir' is restricted.
what? it should give an error
>>> _0imp=None Traceback (most recent call last): File "restrict.py", line 13, in _0hook try:_5=_1['__name__']if _1 else'__main__' Exception: cannot re-assign variable
>>>```
Realised you can shorten the first line by doing v=dict(I=1,V=5,X=…)
!e ```py
import importlib,types,dis,sys
def _0hook(_0,_1):
if'exec'==_0 and _1:
if isinstance(_1[0],types.CodeType):
_2,_3=_1[0],None;_4=[dis.opname[_x]for(_x)in _2.co_code]
for(_i,_n)in enumerate(_4):
if'STORE'in _n:_3=_2.co_code[_i+1];break
if _2 is not None and _3 is not None:
if(_5:=_2.co_names[_3])in['builtins','_0hook','_0imp']:
raise Exception("Cannot re-assign variable")
def _0imp(_0,_1=None,_2=None,_3=(),_4=0):
try:_5=_1['name']if _1 else'main'
except KeyError:_5='main'
if'os'==_0 and any((_xx:=_x)in['remove','rmdir','unlink']for(_x)in _3 or[]):raise ImportError(f"'{_xx}' is restricted.")
elif'sys'==_0 and any((_xx:=_x)in['exit']for(_x)in _3 or[]):raise ImportError(f"'{_xx}' is restricted.")
elif'importlib'==_0:raise ImportError(f"module '{_0}' is restricted.")
return importlib.import(_0,_1,_2,_3,_4)
builtins.dict['import']=_0imp
import('sys').addaudithook(_0hook)
from os import rmdir # this should give an error that will day that this function is restricted
_0imp = None # gives error while executing normally or in repl
builtins.dict['import'] = None # should give an error too```
@sly root :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 21, in <module>
003 | File "<string>", line 14, in _0imp
004 | ImportError: 'rmdir' is restricted.
anyways, it works outside of snekbox:
>>> __builtins__.__dict__['__import__']=8 Traceback (most recent call last): File "restrict.py", line 10, in _0hook raise Exception("Cannot re-assign variable") Exception: Cannot re-assign variable >>> _0imp=8 Traceback (most recent call last): File "restrict.py", line 10, in _0hook raise Exception("Cannot re-assign variable") Exception: Cannot re-assign variable >>> ```
i am here to tell you that you can still bypass this hook
thank you for listening and have a good time
how?
have a good time too
like this?
>>> __builtins__ = {'__import__': 3} Traceback (most recent call last): File "restrict.py", line 10, in _0hook raise Exception("Cannot re-assign variable") Exception: Cannot re-assign variable```
no not like that
like this globals()['_0imp']=None
oh
sec
added ```
print(_2.co_names[_3])
globals()['_0imp']=None globals >>>```
i think there's a way to handle that
code is really messed up on pc
print(_2.co_names[_3],"\n",
[(_x.opname, _x.argval)for(_x)in dis.Bytecode(_2)]
)
>>> globals()['_0imp']=None globals [('LOAD_CONST', None), ('LOAD_NAME', 'globals'), ('CALL_FUNCTION', 0), ('LOAD_CONST', '_0imp'), ('STORE_SUBSCR', None), ('LOAD_CONST', None), ('RETURN_VALUE', None)] >>>```
so the only thing is needed is to check names
!e def cat(): try: eeee except: cat() cat()
@sick hound :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in cat
003 | NameError: name 'eeee' is not defined
004 |
005 | During handling of the above exception, another exception occurred:
006 |
007 | Traceback (most recent call last):
008 | File "<string>", line 3, in cat
009 | NameError: name 'eeee' is not defined
010 |
011 | During handling of the above exception, another exception occurred:
... (truncated - too many lines)
Full output: too long to upload
@quartz wave
if(_5:=_2.co_names[_3])in(_z:=['__builtins__','_0hook','_0imp']):
raise Exception("Cannot re-assign variable")
elif'globals'==_5:
if any(_xx in _z for(_xx)in[_x.argval for(_x)in dis.Bytecode(_2)]):
raise Exception("Cannot re-assign variable")
>>> globals()['_0imp']=None Traceback (most recent call last): File "restrict.py", line 16, in _0hook raise Exception("Cannot re-assign variable") Exception: Cannot re-assign variable >>>```
cool
how would one mess up so badly that errors begin occuring during the process of handling the error
if(_5:=_2.co_names[_3])in(_z:=['globals','__builtins__','_0hook','_0imp']):
if'globals'==_5:if any(_xx in _z[1:]for(_xx)in[_x.argval for(_x)in dis.Bytecode(_2)]):raise _e
else:raise _e```
what does this do
!e
class String:
def __init__(s,chars):
s.string = chars;
def __pow__(s,a):
if isinstance(a,int):
if a == 2:
ords = [*map(ord,s.string)]
return '\n'.join(''.join(chr(a*b)for b in ords)for a in ords)
else:
raise ValueError("not squared :(")
else:
raise ValueError("not an integer")
a = String("abc")
print(a**2)
@severe canyon :white_check_mark: Your eval job has completed with return code 0.
001 | Ⓛ┢▃
002 | ┢▄◦
003 | ▃◦♉

!e
from fishhook import hook
@hook(str)
def __pow__(s,a):
if isinstance(a,int):
if a == 2:
ords = [*map(ord,s)]
return '\n'.join(''.join(chr(a*b)for b in ords)for a in ords)
else:
raise ValueError("not squared :(")
else:
raise ValueError("not an integer")
print("abc"**2)
@languid hare :white_check_mark: Your eval job has completed with return code 0.
001 | Ⓛ┢▃
002 | ┢▄◦
003 | ▃◦♉
finally i can do this locally with my modified cpython
i love it
"Hello World!"**2
baseball 门
!e ```py
from fishhook import hook;from functools import reduce;from itertools import product
@hook(str)
def pow(s,a):
if isinstance(a,int):
o=*map(ord,s),
return''.join(chr(reduce(int.mul,b))for b in product(o,repeat=a))
else:raise TypeError(str(type(a)))
print("abc"**2, "abc"**3)
print("Hello World!"**2)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | Ⓛ┢▃┢▄◦▃◦♉
002 | ᑀᱨṠṠἸऀᡸἸ‐Ṡᰠैᱨ⟙⪜⪜⯋ಠ≓⯋⳺⪜❴അṠ⪜ⶐⶐ⻔⒴⻔〘ⶐ⨰෬Ṡ⪜ⶐⶐ⻔⒴⻔〘ⶐ⨰෬Ἰ⯋⻔⻔〡▹〡ㅮ⻔⭜๏ऀಠЀૠเಀРᡸ≓⒴⒴▹ૠᶑ▹⚾⒴⇼ଷἸ⯋⻔⻔〡▹〡ㅮ⻔⭜๏‐⳺〘〘ㅮเ⚾ㅮ㋄〘ⲈາṠ⪜ⶐⶐ⻔⒴⻔〘ⶐ⨰෬ᰠ❴⨰⨰⭜ಀ⇼⭜Ⲉ⨰✐ैഅ෬෬๏Рଷ๏າ෬с
now I see why only squared is implemented
tf
:)
i thought of the others... never came that far for reasons
btw, the str * str operation, should yield an appropriate matrix
someone implement that
but should it really be newline separated?
that's just regularly inserting the character ascii value 10, which makes it a different string to the one acheived from multiplying: data is added from somewhere
where are you getting these chr(10)s from?
what's the shortest factorial program you guys can think of
f=lambda n:n*f(n-1)if n else 1``` this is a decent one
you could prob make smaller
f=lambda n:n<2or n*f(n-1)
yeah this is the smallest i can think of
reduce is a dead end and not even in builtins anymore :p
hmm does this count? it returns a bool for n=1 but true is technically 1
yes
alright
you posed the question anyway
f=lambda n:1>>n or n*f(n-1)
(not shorter but the true makes me uncomfortable)
f=__import__("math").factorial
oh nvm probably longer
but
if your criterion is "f: int -> int" then yes it is valid
!e
@lambda _:_()
class _:
def __format__(self, spec):
def test(_):
header=spec.split("(")[1].split(")")[0].split(";");header[0]=header[0].split("let ")[1];body="\n".join(x.strip() for x in spec.split("[")[1].strip().split("]")[0].strip().split("\n"));globals()[header[0]]=0
while eval(header[1]):exec(body);globals()[header[0]] += 1
self.__class__._ = property(test)
return ""
def function() -> f'''
{_:
for (let i; i < 2; i++)[
print(i)
print("Hello world")
]
}
''':_._
function()
@gritty mesa :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | Hello world
003 | 1
004 | Hello world
Yeah the syntax highlighter had fun with that one
i prefer 0**n instead of 1>>n :P
interesting, i wonder how is there no syntax error at all
half is due to the annotation, half due to the format
ohh
poor syntax highlighter couldn't figure it out though
!e
def a(arg=[]):
arg.append(1)
print(arg)
a()
a()
a.__defaults__[0].clear()
a()
a()
@alpine peak :white_check_mark: Your eval job has completed with return code 0.
001 | [1]
002 | [1, 1]
003 | [1]
004 | [1, 1]
!e
class X:
def __iпit__(self):
print('init called')
self.x = 123
x = X()
print(x.x)
@fleet bridge :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 7, in <module>
003 | AttributeError: 'X' object has no attribute 'x'
python with the cyrillic characters again
init not called confirmed
__in1t__
__innit_bruv__
You are not allowed to use that command here. Please use the #bot-commands channel instead.
ok
"ipenit"?
"ipit"
Foiled lol
It rool mysterious, innit?
Hey, whats the shortest way to import libs?
from a,b,c,d import *
trying to do something like this
ironically i use this method
globals().update({i: __import__(i) for i in ["random", "string", "math"]})
__import__() isn't really intended for user use, you should probably use importlib.import_module() which has a more sane API.
Most of the shiny things we play with here aren't intended for user use
lambda*a:exec("from %s import*;"*len(a)%a)
just pass strings and it should work, I haven't tested though
Import goes inside a function (closure), so imported stuff is not in global scope.
simple fix ```py
lambdaa:exec("from %s import;"*len(a)%a,globals())
Yep, now it works.
lambda*a,scope=globals():{scope.update({k:v for k,v in __import__(m).__dict__.items() if not k.startswith('_')}) for m in a}
Is there a more elegant way to do this in one line?
f=lambda w:len([None for i in range(len(w)) for j in range(i + 1, len(w)) if w[i]+w[j] in w])
I'm being forced to take an intro to python class so I'm trying to do all functions in one line. I'm currently using the length of an array as a sort of counter and using a list constructor to fill it. Feels stupid and runs slower than another 6-line solution I came up with
Be prepared to fight; some instructors will not like you trying to outsmart them and give you a bad grade for this kind of thing.
Yeah, I've put the functions in comments above my more standard looking solutions
My instructor seems chill tho hopefully
def count_weights(w):
count = 0
for i in range(len(w)): # sets up the 2D iteration space, which includes all values of i and only the values of j greater than i. This is because all of the previous indexes become restircted sequentially, so I don't need to check the uniqueness manually.
for j in range(i+1, len(w)):
if w[i]+w[j] in w: # add one to the count if the sum in in the list
count += 1
return count
``` the full solution if it helps to see it laid out
I did something similar in highschool, when we had to submit a website with links to different parts and pictures and everything and I handed in a single file (images via base64-URIs, links via hashes and javascripty hiding of irrelevant parts)
I like the idea of esoteric coding so I've been trying to dip my toes into one-liners
What are some of the best features that aid compact code?
Constructing a set would make this massively faster
!e
f=lambda w:(s:=set(w),sum(1 for i in range(len(w)) for j in range(i + 1, len(w)) if w[i]+w[j] in s))[1]
import random, time
random.seed(420)
l=[random.randint(0,1000) for _ in range(500)]
t=time.time()
print(f(l))
print(time.time()-t)
```this takes 0.95 on your original solution
@dark wharf :white_check_mark: Your eval job has completed with return code 0.
001 | 24429
002 | 0.024204730987548828
ah, I see
Also changed the len to sum of a generator for a little extra speed
Yeah
No need to make a massive list
yeah, summing the 1s is smart
Was debating on swapping out your w[i] thing for an enumerate but idk if it'll speed things up much if at all
!e
f=lambda w:(s:=set(w),l:=len(w),sum(1 for i,v in enumerate(w) for j in range(i + 1, l) if v+w[j] in s))[-1]
import random, time
random.seed(420)
l=[random.randint(0,1000) for _ in range(500)]
t=time.time()
print(f(l))
print(time.time()-t)
```here's a potentially faster one but I'm on mobile and not bothered to run proper tests
@dark wharf :white_check_mark: Your eval job has completed with return code 0.
001 | 24429
002 | 0.016857147216796875
This uses enumerate and avoids calling len a bunch of times though that's a very marginal gain

)



