#esoteric-python
1 messages · Page 56 of 1
Write as short as possible code that solves a given task
Most often counted in bytes
thank you
how to make email automation generator.
anyone got any ideas to golf this more?
import sys
z=sys.argv[1].replace(*" .")
exec('z=[[v," "][v=="."*(sum(y in"# "for y in z[x-52:x:51]+z[x+52:x:-51])>2)]for x,v in enumerate(z)];'*650)
print(*z,sep="")```
skipping the first replace and swapping the space and dot characters in the later part of the code?
would also free up the argv[1] to leave to an unpacking assignment
i dont think i can do that without making it longer
if i dont replace at the start i have to use a placeholder so i can then change the to . and then placeholder to afterwards
i think
thats what i did before
are there other dots?
at the end i need dots remaining
i see
sample input output
#S# E# #S# ....E#
# ### ##### #.###.#####
# # # → #...#.....#
### ##### # ###.#####.#
# # # .......#
########### ###########```
youd need to change the slicing in my code to work on that sample though
after the first replace i check every square and change it back to a space if its a dead end
i think that equal-multiply-gt can be turned into a chain comparison
can it?
i cant see any way to get it shorter cause i need the v=="." to check if its a . and then the rest is to count the surrounding tiles
the * used to be an and
6 chars saved
import sys
z=sys.argv[1].replace(*" .")
exec('z=[[v," "][2<sum(y<"$"<v<"/"for y in z[x-52:x:51]+z[x+52:x:-51])]for x,v in enumerate(z)];'*650)
print(*z,sep="")```
the v==s*(...>2) thingy can be made into v==s!=...>2 which saves a character
but this one's better
I can't get any shorter with this I think I might need a different algorithm to get shorter
@wicked dagger a spoiler for the actual "102 bytes" part
```py
i=lambda**k:lambda f:type(f)(f.code,type('',(dict,),{'missing':f.globals.getitem})(k))
!e py print("".join([(0.5.__class__.__name__[0]), (9).__class__.__name__[0], "".join([dir(str)[-1][0] for x in range(2)])]) + "".join([True.__class__.__name__[0].upper() + ().__class__.__name__[1], "".join([dir(str)[-1][0] for x in range(2)])]))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
fizzBuzz
lmao
best code in my life
!e
a=lambda o,i:o.__class__.__name__[i];b=[dir('str')[-1][0]for _ in'ab'];print(a(1.,0),a(1,0),*b,a(True,0),a((),1),*b,sep='')
:white_check_mark: Your 3.14 eval job has completed with return code 0.
fizzbuzz
542431903886606399
!e ```py
print('%x'%542431903886606399)
:white_check_mark: Your 3.14 eval job has completed with return code 0.
7871af15200003f
dunno how to interpret that
looks like a discord id
meow
hello i want to make openclaw work but every tim he sai permission denied
i try many thing nothing work plese help
lol
hello
almost everything i write seems to be unreadable to anyone except me so here's a dictionary that gives items a timelimit
Click here to see this code in our pastebin.
Given that you have access to a mutable class object in python, is the only way to use to call a function without using parentheses setting __class_getitem__?
# given
class a: ...
# is this the only dunder we can trigger?
a.__class_getitem__ = exec
a['...']
context is restricted source challenges
You can call some functions parenless via decorators on a class statement
restricted source challenge: using only printable characters (string.printable) but none of ('(', '.', 'c') in your source code, is it possible to print "Hello, World!" to stdout and nothing else?
!e print(import("string").printable)
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
002 |
003 |
004 |
The
import __hello__
Works up to and including python 3.10
Close, punctuation a bit off though (:
including the quotes?
if you really want to, my solution works either way
curious
They removed __hello__ in 3.11?
No, but it no longer prints the Hello, World! on import
You need to call __hello__.main()
ohhhhhhh, that makes more sense
Noo, you are right 🙁
!e ||```py
getattr=path=print
all=["Hello, World!"]
from main import*
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | Hello, World!
002 | Hello, World!
no idea
!e ```py
getattr=path=exit
all=["Hello, World!"]
from main import*
:x: Your 3.14 eval job has completed with return code 1.
Hello, World!
!e ```py
getattr=path=print
all=["Hello, World!"]
from main import*
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | Hello, World!
002 | Hello, World!
import this
>>> this
<module 'this' from '/usr/lib/python3.12/this.py'>
>>> love = this
>>> love
<module 'this' from '/usr/lib/python3.12/this.py'>
>>> this is love
True
>>> love is True
False
>>> love is False
False
>>> love is not True or False
True
>>> love is not True or False; love is love
True
True
why is __path__ involved?
!e
__import__("fishhook").hook(bool)
def __str__(self): return "em truh t'nod ybab"[::-1]
love = 1 <3
what = all([1])
print(what is love)
:white_check_mark: Your 3.13 eval job has completed with return code 0.
True
i think you're missing a @ for the decorator
!e Right.
@__import__("fishhook").hook(bool)
def __str__(self): return "em truh t'nod ybab"[::-1]
love = 1 <3
what = all([1])
print(what is love)
:white_check_mark: Your 3.13 eval job has completed with return code 0.
baby don't hurt me
!e ```py
getattr=print
all=["Hello, World!"]
from main import*
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | __path__
002 | Hello, World!
003 | Hello, World!
it's kind of needed for the star import, i guess?
oh, it wouldn't normally have a __path__ because it wasn't imported to begin with; the import logic looks for it; and the __getattr__ hook triggers
yeah exactly, import machinery is wild when you start messing with hooks
isn't fishhook third-party?
yes
by @rugged sparrow
But there's a few libraries we install in the environment the bot is running code in.
ooh
!e e
:x: Your 3.14 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File [35m"/home/main.py"[0m, line [35m1[0m, in [35m<module>[0m
003 | e
004 | [1;35mNameError[0m: [35mname 'e' is not defined[0m
!e ls
:x: Your 3.14 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File [35m"/home/main.py"[0m, line [35m1[0m, in [35m<module>[0m
003 | ls
004 | [1;35mNameError[0m: [35mname 'ls' is not defined[0m
Please use #bot-commands for experimenting with the bot
!e I guess this should work?
__path__ = None
__getattr__=print
__all__=["Hello, World!",0]
from __main__ import*
:x: Your 3.14 eval job has completed with return code 1.
001 | Hello, World!
002 | Traceback (most recent call last):
003 | File [35m"/home/main.py"[0m, line [35m4[0m, in [35m<module>[0m
004 | from __main__ import*
005 | File [35m"<frozen importlib._bootstrap>"[0m, line [35m1421[0m, in [35m_handle_fromlist[0m
006 | File [35m"<frozen importlib._bootstrap>"[0m, line [35m1417[0m, in [35m_handle_fromlist[0m
007 | [1;35mTypeError[0m: [35mItem in __main__.__all__ must be str, not int[0m
i mean sure
if stderr doesn't matter
This is genius
!e print(chr(sum(range(ord(min(str(not())))))))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
ඞ
lets goo i still remember it
:white_check_mark: Your 3.14 eval job has completed with return code 0.
ඞ
Step by step its
True->'True'->'T'->84->3486->ඞ
ahhhh got it
i also figured it out
the not() kinda freaked me out
but it was actually not ()
and since () is falsey
not () returns True, the bool
is it possible to avoid assigning n?
"string"[n:='><+-.['.find(i)];a+=n//5
by duplicating the code
@long fulcrum Could you also do this instead?
n=((n-1)//2)*(n%2)or ((n+1)*3)*(n%2==0)
n=[(n+1)*3,(n-1)//2][n%2]
nvm codegolf made a better one
:p
this is my full thing
for n in range(1000):
s=0
while n:n=[-~n*3,~-n//2][n%2];s+=1
print(s)```
oh I can do n>>1
C++ is better yell
this image feels like its missing something without the other panels
the above panel is the message above the image and the bottom panel is the even more above messages
yay
.bm
i think they were trying to say C++ is better yellow
is there a shorter version of
i=0
_,g=sys.argv```
or the whole thing actually
import sys
i=0
_,g=sys.argv
while i<1055:m=i%33==31;print(".#"[2<sum(g[i-67+x:][:3].count("#")for x in b"!Bc")<4+(g[i]<"$")],end="\n"*m);i+=1+m```
:3
:3
code golfed anything belongs here
heck yeah
I made Tetris in 25 lines, I've seen people do one liners but I don't know how to do that
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Is code golf even a concept in any other language other than python
yes, people have even made golfing languages
it is certainly not a Python-specific thing
Nice
This python code converts roman numerals into decimals
roman=lambda _,__=lambda ___:[
[ 1,
5, 10,
50, 100,
500, 1000
][ "IVXLCDM"
.index( _
) ]
for (
_ )
in (
___ )
]:sum( [
[ _i,
-_i ][
_i <
__i ]
for (
_i, __i
) in
( zip(
[ 0
] +
__( _
), __(
_ )
+ [
0 ]
) )
] )
print(roman("MMMCCCLXXXVIII"))
Should make it in the shape of a roman numeral (maybe "V"?)
awesome
g
!e
p = lambda x,c=lambda n:[1,5,10,50,100,500,1000]["IVXLCDM".index(n)]:sum([c(i)*(-1 if c((x+"I")[y+1])>c(i)else 1)for y,i in enumerate(x)])
print(p("MCDLXXIV"))
Can anyone come up with any shorter code than this?
:white_check_mark: Your 3.14 eval job has completed with return code 0.
1474
!e
p=lambda x,c=lambda n:[1,5,10,50,100,500,1000]["IVXLCDM".index(n)]:sum([c(i)*(1-2*(c((x+"I")[y+1])>c(i)))for(y,i)in enumerate(x)])
print(p("MCDLXXIV"))
130 characters
:white_check_mark: Your 3.14 eval job has completed with return code 0.
1474
!e
p=lambda x,c=lambda n:[1,5,10,50,100,500,1000]["IVXLCD".find(n)]:sum(c(i)*(c(f"{x}I"[y+1])<=c(i)or-1)for y,i in enumerate(x))
print(p("MCDLXXIV"))
forgot to remove end
ouch
:white_check_mark: Your 3.14 eval job has completed with return code 0.
1474
!e
def f(i):
t=0
for r in i:n=10**(205558%ord(r)%7)%1999;t+=n-2*t%n
return t
print(f("MCDLXXIV"))```
:white_check_mark: Your 3.14 eval job has completed with return code 0.
1474
explain pls
idk it's just some code I have saved, I imagine it's from stack overflow
could we make it inline lambda?
the magic section looks to be found via pysearch?
yeah I couldn't find it on stack overflow so probably
is anyone able to figure how to get this code running like the first part
# import sys;e=enumerate
# for m in sys.argv[1:]:
# m=m.split()
# for y,j in e(m):
# for x,i in e(j):
# s=[]
# for g in[(y,x)for y,j in e(m)for x,i in e(j)if i=="0"]:
# q=[(y,x)];d={(y,x):0}
# while q:
# v,*q=q;b,a=v
# if v==g:s+=d[v],
# if m[y][x]=="#":break
# for B,A in(b-1,a),(b,a-1),(b,a+1),(b+1,a):
# if -1<B<9>A>-1and m[B][A]!="#"and(B,A)not in d:d[(B,A)]=d[v]+1;q+=(B,A),
# print(end=([chr(x)for x in range(150)if chr(x).isalnum()][min(s)]if s else m[y][x]))
# print()
# print()
import sys
for m in sys.argv[1:]:
for x,i in enumerate(m):
s=[]
for g in[y for y,j in enumerate(m) if j=="0"]:
q=[x];d={x:0}
while q:
v,*q=q
if v==g:s+=d[v],
if m[x]=="#"or m[x]=="\n":break
n=[]
if v>9:n+=v-10,
if v<72:n+=v+10,
if v%10>0:n+=v-1,
if v%10<8:n+=v+1,
for w in n:
if (m[w]=="-"or m[w]=="0")and w not in d:
d[w]=d[v]+1;q+=(w),
print(end=([chr(x)for x in range(150)if chr(x).isalnum()][min(s)]if s else m[x]))
print("\n")```
first code uses a 2d list but im trying to get it working with just the string that gets passed
input output
-#------- -#6543212
-#-----0- -#5432101
-#------- -#6543212
-#------- -#7654323
-#------- -#8765434
-######## -########
-#------- -#-------
-#------- -#-------```
the new code fails on this input
---------
---------
---------
---###---
---#-#---
---###---
---------
---------
--------0```

that 72 should have been a 79
Why not? There's locals(), vars(), globals() and sys._getframe()...
I mean, it would be worse that way, but still...
!e ```py
f=lambda i:(t:=0)or[t:=t+n-2*t%n for n in[10**(205558%ord(r)%7)%1999 for r in i]]and t
print(f("MCDLXXIV"))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
1474
!e ```py
f=lambda i,t=0:[(n:=10**(205558%ord(r)%7)%1999)+(t:=t+n-2*t%n)for r in i]and t
print(f("MCDLXXIV"))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
1474
that's what i was thinking
kind of communicated it wrongly though :p
!e ```py
f=lambda i,t=0:[t:=t+(n:=10**(205558%ord(r)%7)%1999)-2*t%n for r in i]and t
print(f("MCDLXXIV"))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
1474
i don't know if that's shorter than the def version with one-space indents
I was counting with one space indents
!e ```py
f=lambda i,t=0:[t:=t+(n:=10**(205558%ord(r)%7)%1999)-2*t%n for r in i][-1]
print(f("MCDLXXIV"))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
1474
Another char down
It's finally shorter than original!
!e ```py
f=lambda i,t=0:max(t:=t+(n:=10**(205558%ord(r)%7)%1999)-2*t%n for r in i)
print(f("MCDLXXIV"))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
1474
I was unsure whether I could do this, but it works out, so -1 byte
I think that shorter solutions would need to switch to a different algorithm altogether (if that's possible).
I really don't see where it could be improved
this python program recognizes it's own sha256 hash and describes itself without any file reads. <redacted due to windows line endings making it finnicky>
Doesn't work for me, is there anything about the line endings I have to take care of?
Are you getting 5b80b6f58d7062d48307e1dea85f35c31e94baca19642fa9c12d4727b3cf609e as the hash of the source code?
No, b059e490d17cb61e4794aefad78a652b2b973e0b9dd6fba1cc85094a3e82504f
Hexdump: https://paste.pythondiscord.com/YYGQ
i tried a few combinations, none seem to work:
% sha256sum *
c981fa78ac1134b4caa8af7d6a4e7c2defe2190c57b20df36fc6f156bfc48651 GO4Q.txt
8513992ed9910ddc8cecd457274268958a4f635c71c6ec8f0bba8b617ca73c68 crlf_notrailing_nl_utf16.py
52695766fb61bed089b113ff13ea221938434d1248a665b2532e2ab662488895 crlf_notrailing_nl_utf8.py
2f626dfd858786a8269b86597631f3d42ffe618f523216b2b5cf0ecc0d9cb772 crlf_trailing_nl_utf16.py
d7873b97d6076571d3e8f2666d92023d5e0c9ae7ce852efbd91276a063430884 crlf_trailing_nl_utf8.py
4e830932e951220cab02f128f603b6963dd4b5bad099d5ff9427c07c0a632178 lf_notrailing_nl_utf16.py
92969b687732b9bf43655b1fae55d8d9107b67b46f933990c6183a42e2d9fe6e lf_notrailing_nl_utf8.py
cf232524fb77f4e2ba8e15751826863c9a32d56041541bc269ec65a967333313 lf_trailing_nl_utf16.py
1819a93a06815a4b1be23c653b405f2a5d6d16f5a3e746e435b9e2c3da7277b0 lf_trailing_nl_utf8.py
Do you happen to be on Windows?
Yes
Oh. And not on WSL I'm guessing.
Oh, yeah thats the problem, when I go into wsl I'm getting the c981 hash you guys are getting
I converted it to DOS line endings, but now I'm getting f275268ba73ba946ddd0246bf796f3b05135cee467dd592a29b3734a5564045f...
Okay, and if I remove the trailing line ending but keep DOS line endings I'm getting c981...
Where did you get this Python file from?
I made it
Well, it works for me (with a normal file on a non-weird OS) when I replace the string in the file with e5a4cda988c87e09681ce41b9ff30d82b7b8830138e1e23eeb1a969377f23e4f
How did you even cook that up
sed -i 's/\r//' spooky.py should fix the line endings* if you've got the c981 version!
That's just dos2unix
i thought it's supposed to be fe45fb1678176053679ede6188ed19e301214aeb22783f0acd6f480689910845
No, 5b80b is what it should be
the fe45 is a magic constant
oh, i just realized my editor auto formated the file on save. without it, i get 5b80b
$ sha256sum lf_notrailing_nl_utf8.py
5b80b6f58d7062d48307e1dea85f35c31e94baca19642fa9c12d4727b3cf609e lf_notrailing_nl_utf8.py
the fe45 constant is important because if you set it to anything else, the "english checksum" breaks, plus the hash of the file changes
well really they are all important and triply constrain each other
... is sha256 really so weak that putting together something like this is feasible? spooky indeed
thanks asm and l3viathan for helping me realize what was causing problems and why it was careless to finalize this with windows line endings. not very good for copypasting from discord! i went back and redid everything to (hopefully) fix that issue. LF only line endings. was not easy to make everything line up again lol
this python program detects it's own sha256 hash while simultaneously describing it's own character composition. everything depends on everything else. change one character, break everything!
import hashlib
def x(hex_string):
r = 1
for c in hex_string:
r += int(hashlib.sha256(c.encode()).hexdigest(), 16)
return hashlib.sha256(str(r).encode()).hexdigest()
if __name__ == "__main__":
if len(sys.argv) != 2:
print("usage: python3 spooky.py <sha256 hex digest>")
print("the program detects if you give it its own sha256 hash.")
sys.exit(1)
input = sys.argv[1]
if x(input) != "d694dd1b4a8c7b658240b201d313f933968f9b750dbb69d5bfbbe09018107b7c":
print("That's not the hash of the source code. Verify you got everything: the full source file has exactly two j's, twenty six f's, fourteen b's, sixteen d's, fifty four i's, thirty two o's, fifteen c's, ninety one e's, thirteen p's, seventeen g's, twelve l's, two k's, six m's, thirty seven h's, twenty three a's, fifty one n's, one q, thirty four r's, eighty six s's, seventy t's, sixteen u's, sixteen v's, nine w's, seventeen x's, twenty four y's, one z, seven 0's, eleven 1's, eight 2's, eight 3's, four 4's, eight 5's, ten 6's, six 7's, five 8's and seven 9's. Not case sensitive.")
else:
print("Success!")```
The hash of the file should be 234d5dce0e9c5f785481a6711a65b0db962f794ef462cbfa82b00d8313ac73e9
Mind sharing how did you do it?
it is meant to be confounding 😉 its like a ship in a bottle
I mean the x function is definitely lenient and any order of the letters in the hash would work as the input and this could be brute-forced, but the self-describing message is self dependent and I'm not sure how to calculate that.
you're definitely on the right track, that is one of the tricks
You could improve brute force time by changing the order of the letters listed instead of changing the compared hash. There's a clear distribution of the number of letters and they don't seem to vary a lot between the two of the files.
I can somewhat imagine how it could be done, but nonetheless the self-describing part looks hard.
I'd try creating it by:
- Generate hash of a file without the comparison hash and file description
- Generate the comparison (of old version) and description (of old version).
Repeat a few times (maybe once is enough) to get rough expected letter count.
Lock in the comparison hash (after all it's just equivalent of the file description, but disregarding the order of the letters).
Then just permutate the order of how the letters are listed and check if the resulted hash of the file has the required count of each letter (based on comparison hash) until it's a match.
Considering that from n up, the letters + numbers are ordered and before theme there are 15 "randomly" arranged letters, I can estimate that it took ~10^12 tries. Definitely doable within one day time-frame using some fast implementation in paralel.
How close am I?
The comparison hash is indeed locked in before the permutation search begins - even before the self-describing bit is built - and yes it takes about 10^12 tries! But the way I derived the "comparison hash" is different, and it was derived for a specific reason to make the bruteforce search as fast as possible. You're extremely close.
How long did it take to calculate?
The self-describing bit (the autogram) takes <60 seconds, the comparison hash itself I can do instantly because it encodes a specific property of the program hash, and the final permutation search is the long one, generally a few hours
six 7's
any ideas to make this shorter?
import sys
e=enumerate
for m in sys.argv[1:]:
o=[*m]
for k,c in e(A:=[*filter(str.isalnum,map(chr,range(150)))]):[[-1<i+w<89and o[i+w]=="-"and o.__setitem__(i+w,A[k+1])for w in[-10,10,-1,1]]for i,x in e(o)if x==c]
print(*o,"\n",sep="")```
the filter is to convert the distance to base62
!e ```py
from string import*;print(printable[:62])
:white_check_mark: Your 3.14 eval job has completed with return code 0.
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
well
is o only 89 characters in length?
yeah
this
so first i think you can import string and do string.printable[:62].swapcase() instead
I also changed the o[i+w]=="-" around to save a space
import sys,string
e=enumerate
for m in sys.argv[1:]:
o=[*m]
for k,c in e(A:=string.printable[:62].swapcase()):[[-1<i+w<89and"-"==o[i+w]and o.__setitem__(i+w,A[k+1])for w in[-10,10,-1,1]]for i,x in e(o)if x==c]
print(*o,"\n",sep="")```
also instead of py for m in sys.argv[1:]: o=[*m] you can do ```py
for*o,in sys.argv[1:]:
oh what I always thought you couldn't do anything to the variable in a for loop
for loop targets are like any assignment targets
you can collapse this into a single line now btw
oh yeah
just put the for k,c in e(A) in the listcomp and assign to A before it
and also instead of print(*o,"\n",sep="") use "".join
there's another optimization that can be done with [-10,10,-1,1] but i might be away for a while
basically you can shorten it by doing enumerate(o,<some constant>) and making that constant list into a bytestring
can this be shorter than what I have?
I tried this with bytestring but it ended up the same length
import sys,string
e=enumerate
A=string.printable[:62].swapcase()
for*o,in sys.argv[1:]:[[[-1<(j:=i+w-50)<89and"-"==o[j]and o.__setitem__(j,A[k+1])for w in b'(<13']for i,x in e(o)if x==c]for k,c in e(A)];print("".join(o)+"\n")```
oh wait you needed the extra newline
okay
print("".join(o)+"\n")
print(*o,"\n",sep="")
oh yeah this is shorter I just forgot to change the print back
put the -50 as the second argument in e(o)
also -1<...==o[j] can be simplified
okay wait
it ends up the same length
i see
I tried 89>i+w>=0<("-"==o[i+w]) which is the same length
221
import sys,string
e=enumerate
A=string.printable[:62].swapcase()
for*o,in sys.argv[1:]:[-1<i+w<89and"-"==o[i+w]and o.__setitem__(i+w,A[k+1])for k,c in e(A)for i,x in e(o,-50)if x==c for w in b'(<13'];print(*o,"\n",sep="")```
I can change the last and to ==
218
import sys,string
e=enumerate
A=string.printable[:62].swapcase()
for*o,in sys.argv[1:]:[x!=c or-1<i+w<89and"-"==o[i+w]==o.__setitem__(i+w,A[k+1])for k,c in e(A)for i,x in e(o,-50)for w in b'(<13'];print(*o,"\n",sep="")```
untested
import sys,string
e=enumerate
A=sorted(string.printable[:62])
for*o,in sys.argv[1:]:
for j in[i+w-50for k,c in e(A)for i,x in e(o)for w in b'(<13'if x==c]:
if-1<j<89!="-"==o[j]:o[j]=A[k+1]
print(*o,"\n",sep="")
k is undefined
oh right
212 untested ```py
import sys,string
e=enumerate
A=sorted(string.printable[:62])
for*o,in sys.argv[1:]:[o.setitem(j,A[k+1])for k,c in e(A)for i,x in e(o)for w in b'(<13'if-1<(j:=i+w-50)<89!=x==c>"-"==o[j]];print(*o,"\n",sep="")
yep it works
191 untested ```py
import sys
A="123456789ABCDEFG"
for*o,in sys.argv[1:]:[o.setitem(j,d)for c,d in zip("0"+A,A)for i in range(89)for w in b'(<13'if-1<(j:=i+w-50)<89!=o[i]==c>"-"==o[j]];print(*o,"\n",sep="")
I love coming into this channel time to time just to see the... whatever this is lmao
So funky
basically turns the input on the left into the output on the right
-#------- -#6543212
-#-----0- -#5432101
-#------- -#6543212
-#------- -#7654323
-#------- -#8765434
-######## -########
-#------- -#-------
-#------- -#-------```
the basic idea is an ascending character value search that uses a 1D grid interpretation with hardcoded indexes to replace the orthogonal neighbors with the next character value if they're empty (-)
doesnt work, the zeroes start spreading
A needs to run up to q
oh wait i did it wrong
it messes up the newlines and doesn't do any of the distances
I think I'm still doing it wrong actually
it works but it's one longer using string.printable for A and joining
this ends up the same length
import sys,string
A="".join(sorted(string.printable[:62]))
for*o,in sys.argv[1:]:[o.__setitem__(j,d)for c,d in zip(A,A[1:])for i in range(89)for w in b'(<13'if-1<(j:=i+w-50)<89!=o[i]==c>"-"==o[j]];print(*o,"\n",sep="")```
it's longer actually i was comparing to an older one
might not need the "".join for A=
oh yeah
was finally able to get this shorter using this
w=[1]
exec("print(*w);*w,=map(sum,zip(w+[0],[0]+w));"*20)```
Python: loop unrolling
.l import sys
Z=sys.argv[1].replace(*" .")
Exec('z=[[v," "][2<sum(y<"$"<v<"/"for y in z[x-52❌51]+z[x+52❌-51])]for x,v in enumerate(z)];'*650)
Print(*z,sep="")
.l ```import sys
z=sys.argv[1].replace(*" .")
exec('z=[[v," "][2<sum(y<"$"<v<"/"for y in z[x-52:x:51]+z[x+52:x:-51])]for x,v in enumerate(z)];'*650)
print(*z,sep="")
!e import sys z=sys.argv[1].replace(*" .") exec('z=[[v," "][2<sum(y<"$"<v<"/"for y in z[x-52:x:51]+z[x+52:x:-51])]for x,v in enumerate(z)];'*650) print(*z,sep="")
:x: Your 3.14 free threaded eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File [35m"/home/main.py"[0m, line [35m2[0m, in [35m<module>[0m
003 | z=[31msys.argv[0m[1;31m[1][0m.replace(*" .")
004 | [31m~~~~~~~~[0m[1;31m^^^[0m
005 | [1;35mIndexError[0m: [35mlist index out of range[0m
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Hi I'm new to esoteric python
!e
f=lambda x:(-1046017.47468*x**10)+(2623063.85928*x**9)+(-439870.30489*x**8)+(-3989739.38765*x**7)+(3407989.77792*x**6)+(721271.24084*x**5)+(-1991793.21887*x**4)+(722163.21951*x**3)+(58786.17727*x**2)+(-76753.93198*x)+(11021.04325)
d=lambda i,c:chr(round(f((i*2+ord(c)-86)/44))-i*2)
print("".join([d(i,c) for i, c in enumerate("Hello World")]))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
I hate fish
finding polynomials that pass through given points is cute
finally managed it shorter
import sys
z=sys.argv[1].replace(*" .")
exec('z=[[v," "][2<sum(y<v=="."for y in z[x-52:x:51]+z[x+52:x:-51])]for x,v in enumerate(z)];'*650)
print(*z,sep="")```
What does this do?
fih
I'm late, but I just realised that you could partially pre-compute hash for the first part of the file as it doesn't change.
solves a maze
you can run it with an input like this
the way it works is it fills the maze in with . which is used to mark the path to the finish. and then it just loops through the maze and if the . is a dead end it then it's changed to a . then I just do that 650 times until all the dead end paths are gone
wait did you put everything in a string and multiply it by 650 just to avoid a for loop??
well python doesn't have a loop 650: statement and it's shorter than both kinds of existing loops
such is the nature of codegolf
dang
where can I learn common codegolf techniques?
read golfed code
golf code yourself
i dont really care for stack exchange personally but codegolf.stackexchange.com is a decent repository of golfed code in a bunch of languages if you want to look at it
i dont really care for stack exchange personally
may I introduce you to https://codegolf.codidact.com/
for(i)in' '*650:f()
exec('f();'*650)
for()in[()]*650:f() is also unfortunately the same length as the former
ty bro
hello
hi
TIL that () = [] is a valid statement
I was just thinking about maybe doing some python code golf but i just saw the posts here and i think im good...
we all started from a place of comfort, didn't stop some of us :D
LOL
Did u guys start this because u already wrote noodle-code or because u wrote clean code that even my Grandma could understand? or something inbetween?
esoteric python is something you do to reeeeally have fun with the python language once you understand it. kinda like how artists need to intimately know the rules to break them
i was interested in the python language's features and codegolf allowed me to discover most of it
plus other forms of esoteric python
it's basically knowing the language better than it knows itself
!e
() = []
:warning: Your 3.14 eval job has completed with return code 0.
[No output]
me too
!e
def foo(_:(x:="bar")=0):
print(x)
foo()
:white_check_mark: Your 3.13 eval job has completed with return code 0.
bar
does anyone know if it is ever useful to put expressions inside of type hints?
well all typehints are valid expressions, for one
but for nonstandard use of typehints there's probably not much accepted use
besides putting strings in, though that was largely outphased by 3.14's lazily evaluated annotations
for unconventional uses it could be used to communicate another outside value while keeping the value hidden within the function object
similar to default values
use them as an alternative to globals 👍
day 77 of putting code in the weirdest places ever
behold, typehints
it can be actually useful for Annotated types
Annotated[TypeForm, *Metadatas]
on the right side you just give something potentially useful at runtime. pydantic uses it to smuggle runtime objects representing validators and other things
by TypeForm i mean type form as defined in the i-love-that-it's-final pep https://peps.python.org/pep-0747/
oh man it's so great typeforms are there
i wish we had it earlier
I'm trying to tightly integrate 3.14 GIL-less Python with Godot Engine. To eliminate the need for marshaling and make (Godot) Object zero copy passable via GE-Python boundary. The problem is that Object is virtual so it will have vtable at the start and PyObject_Head only after that (if Object will inherit from PyObject). Static casting down to PyObject* should give Python correct pointer (PyObjectType must mind that offset). The issue is with allocation - GIL-less requires to allocate Python Object using mimalloc. Correct allocation size seems trivial but that offset to PyObject_HEAD is problematic; C++ side frees Object by calling memfree on them and this is hijacked to instead participate in Refcounting.
codegolf: try defining a function(lambda doesn't count) that takes in a list of arbitrary integer values randomly shuffled and outputs the largest one in binary
output type must be int or string
def x(i):print(f"{max(i):b}")
!e def x(i):print(f"{max(i):b}")
._. Well i thought youd get it quit quickly but wow... i didnt event know:b was a thing
"lambda doesn't count" python code golf generally allows lambdas as full solutions
they are the exact same as functions after all, just different syntax and no name
if the 0b prefix is acceptable then bin is 2 chars shorter
f"{x:b}"
bin(x)##
I feel sorry for myself to open this chat
!e
Click here to see this code in our pastebin.
tictactoe
b,t=[0,0],1
while not any((b[p]&m==m)and not print("XO"[p]+"wins!")for m in(7,56,448,73,146,292,84,273)for p in(0,1))and sum(b)<511:
if (u:=int(input("> "))) not in range(9)or 1<<u&sum(b):break
t^=1;b[t]|=1<<u
for i in range(9): print("X "*(b[0]>>i&1)+"O "*(b[1]>>i&1)or ". ",end="\n"*(i%3==2))
expanded code if anyone wants to actually read it https://paste.pythondiscord.com/V7HA
I decided to put all of it inside of a type hint
_:(b:=[0,0],t:=1,[exit() if any((b[p]&m==m)and not print("XO"[p]+" wins!")for m in(7,56,448,73,146,292,84,273)for p in(0,1))or sum(b)==511 else (exit() if (u:=int(input("> "))) not in range(9)or 1<<u&sum(b) else ((b:=[b[0],b[1]|1<<u]) if t else (b:=[b[0]|1<<u,b[1]]),t:=t^1,[print("X "*(b[0]>>i&1)+"O "*(b[1]>>i&1)or ". ",end="\n"*(i%3==2)) for i in range(9)])) for _ in[0]*9])=0
SyntaxError: named expression cannot be used within an annotation
You can't use := insidie an annotation
Looks like this is only an error in 3.14 and 3.15
check out my obfuscator https://github.com/lyric0x10/Oblivion
give me some feed back : )
view some obfuscated code https://paste.pythondiscord.com/VRFA
well it doesn't seem like a vm
which is a good thing
yea i meant the code u postedthat was obfuscated
prolly i'm just braindead
pretty cool
would be interesting to see the deobfuscation of the example automated
yea, but I dont think anybody in this server can. I'd like to see someone attempt it.
<outdated>
interesting project if i manage to keep this motivation until i can code again
yall wanna calculate pi with 0 error in finite time
from __hello__ import TestFrozenUtf8_2 as __cod__;22/7.; print("\
" ""+
__cod__.__doc__
)
!e
from __hello__ import TestFrozenUtf8_2 as __cod__;22/7.; print("\
" ""+
__cod__.__doc__
)
:white_check_mark: Your 3.14 eval job has completed with return code 0.
π
.topic
Suggest more topics here!
%magic```
Print information about the magic function system.
Supported formats: -latex, -brief, -rest
doesn't seem to exist
It's badly formatted, it's supposed to be __magic__, which still doesn't literally exist.
What's meant is "magic methods" aka dunders aka special methods.
oh yes dunders
is there an option to keep names that need to be exported while obfuscating the code? or is that handled already
python_minifier also doesn't seem like an internal module
Your right it isnt an internal module. the github specifically says "No external pip packages required for core obfuscation". minifying your code isn't an obfuscation feature.
no, there isn't. i'll add that to the todos list
it's needed to run main.py for some reason though
Why do you not want to install it?
i mean it's an external pip package which probably should be mentioned but i can just do that i guess
yea i updated the readme to mention it. honestly i created the readme using ai and didnt read it before posting. it's my fault
explain?
I just copied the message above me which hadn't been !e'd. But it looks like ||the 22/7 is just a distraction, it just reads a docstring in the __hello__ module||.
I just realized why that docstring contains pi, its because its for testing utf8
I didn't think that
though I do know thay 22/7. is a distraction
what about "\" "
which isn't also printed
It's not "\" ", but "\" "", where the \ is the line continuation backslash. So it's just "" "" (implicit concatenation) plus the pi.
couldn't see it properly on mobile
@noble jasper didn't you have another discord account earlier?
do you remember this?
i did but it got hacked and deleted
that was my V1 obfuscator
its my attempt at golfing tictactoe
You have to enter values from 0 to 8* to play moves
with the board formatted like this
0 1 2
3 4 5
6 7 8
>>> def d(n):
... print(n)
... return n
...
>>> a = [15,10,2]
>>> a[-1]-=d(a.pop())
2
>>> a
[15,0] # expected outcome: [15,8]
i know that's some edge case i'm hitting and in general i should not do this, but... what? (i just joined this place and became too confused due to amount of channels, so im gonna ask here)
the console i ran this on is 3.14.0a1, but this seems to do the same in 3.12.4.
a[-1] is evaluated first
that's how -= and all other augmented assignments get their first value
LHS eval, RHS eval, BINOP done, LHS store
yeah, but i was confused because a[-2] gives an error with a=[10,2]
that error is on the store part
ohh okay thanks
so it reevaluates the index on load and store?
it reevaluates the subscript
the index itself used for the subscript is copied
a[i] -= x
is equivalent to ```py
_idx = i
a[_idx] = a[_idx] - x
#^^^^^^ ^^^^^^
different operations
okay i get it now, big thanks
i kinda imagined there was an optimisation there because the metamethods are separate 😆
but wait, what does _isub_ do then?
__isub__ defaults to regular __sub__ when unimplemented :p
oh 😐
for methods that implement it, could be used to modify inplace
that's for the object that's getting subtracted from though
storing into an index is a different operation that's done to the list and not the element getting subtracted from
Give me some esoteric python code as a beginner
As a beginner to esoteric python, not to programming in python
!e ```
print(False == False in [True])
:white_check_mark: Your 3.14 eval job has completed with return code 0.
False
I have downloaded the whole precedence in my brain
Level 2
Or level 1, if we consider this as level 0
Wait
Is that not about preceding
what to hell
!e ```
a = {}
b = a
a[0] = a = {}
print(a, b)
:white_check_mark: Your 3.14 eval job has completed with return code 0.
{} {0: {}}
i mean..
what precedence do you think would make sense here :p
!e ```
print((False == False) in [True])
print(False == (False in [True]))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | True
002 | True

Surely this isn't about == and is difference?
well, there's only == and in here
:warning: Your 3.14 eval job has completed with return code 0.
[No output]
!e print(False in [True])
:white_check_mark: Your 3.14 eval job has completed with return code 0.
False
😭
in fact this feature is widely known for being pythonic
hint: it can be used to check if something is between two values
This thing makes no sense 😭 i have used walrus but this thing is beyond science

Is this going algebra or something
(this specific case is very esoteric, however)
regular python feature. like beginners can use it too, most people just don't use it this way (or even know it can be used this way)
saying from my memory
I don't think i ever did it
😭 chat am i that bad in python
have you ever done something like m <= x < n?
start inclusive range
math yes
Isn't that like our builtin range
which excludes end
which in other languages needs to be done as m <= x and x < n
is it that hard for them to implement
I give up chat
😔
Tell me the secret
not sure, but most have had chain comparisons unimplemented since their birth
in is the same precedence as other comparison operators
I don't get it if so
and since comparison operators are chained in python..
in basically is == with iteration right
mhm, but that's not the focus here
i see
Is that how it is translated internally?
yup
But why
I would expect either of this to happen
in is in the same category as comparison operators in the parser

why? idk :p
but it makes for a fun feature
but that goes against how i see it
it should be a separate check
Iterate over iterable for each item, target._eq_(item).
Isn't it?
Against*
yes, most implementations follow that
it's a python-only feature so i'd argue it's very pythonic ^^
this doesn't happen in practical things and works as we usually expect, right?
Or i will have anxiety next time i use un parenthesized expression which contains in
nobody usually uses the in as a chain
and you only need to parenthesize when you're using comparison operators with it and you don't intend to chain it
Now this
I think i saw something like this a few days ago in python discussion channel
I see. Very tricky bug that can go un noticed and horrible
a[0] ??????

Ok wait i thought it was a set
Nvm
Because of right to left (reverse) assignment, such that a = {}, a[0] = {}, b contains the original dict which a used to reference?
Was that it?
Wait
Wth
Why would that be assigned to b
i mean that would mean a would be assigned then a[0] would be assigned..
it's a very simple idea though
Why is that all happening to b than a
because i assigned b to a before it?
Then it should happen to a too print shows its empty
😭
Okay wait
Don't tell answer until i say i give up
Hints are welcome
- a[0] = {}
then reassigned a
Oh i didn't have to think right to left assignment
a[0] = {} # b also gets that
a = {} # becomes empty
Okay that was easy, shouldn't have thought it is tricky
yup!
That was honestly what i initially would i have thought had i not been biased and thought that probably its tricky so it could be right to left than usual left to right
Next please
It was fun.
with the exception of the rightmost expression which is evaluated first, python assignments are evaluated left to right
okay
() = ()
I see
Thanks for your explanation
I wonder why "explain" contains "i" but not "explanation"
English can't stay predictive
I hate Inconsistency
simplification, probably
it's like how "comfortable" doesn't pronounce "for," or how "pronunciation" doesn't have the "o" in "pronounce"
!e this btw ```py
[] = []
() = ()
:warning: Your 3.14 eval job has completed with return code 0.
[No output]
What is there
That i will read () at left side as a tuple assignment?
both sides are thought of as expressions than tuple, even though they're empty to be literal'ed as tuple
Not sure why it does that but makes sense if it contains expressions
So there's nothing to carry the empty tuple so it just does not get assigned
Hence it gets just... Forgetten
Is that all
there's no assignment being done, that's true
right side is always evaluated and left side is always a target in an assignment though
!e even though it looks like nothing... ```py
() = 1
:x: Your 3.14 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File [35m"/home/main.py"[0m, line [35m1[0m, in [35m<module>[0m
003 | [1;31m()[0m = 1
004 | [1;31m^^[0m
005 | [1;35mTypeError[0m: [35mcannot unpack non-iterable int object[0m
Lol
Next
Gotta binge it
Why does it allow for [] = []
Tuple is understandable
Its not even a subscription
it's practically the same thing
it looks like a list literal, but it's the same as a tuple literal in the LHS
!e [a, b] = [1, 2]
print(a, b)
:white_check_mark: Your 3.14 eval job has completed with return code 0.
1 2
Yo you're rigjt
Right
Why tho, shouldn't it only group by tuple for expressions than list literals
!e {} = {}
:x: Your 3.14 eval job has completed with return code 1.
001 | File [35m"/home/main.py"[0m, line [35m1[0m
002 | [1;31m{}[0m = {}
003 | [1;31m^^[0m
004 | [1;35mSyntaxError[0m: [35mcannot assign to dict literal here. Maybe you meant '==' instead of '='?[0m
a list is also sequence, so
ok wtf
Valid crashout
this scares me
@undone thicket see rhis
i will not sleep tonight
😈😈
HUH?!?
why cant u do it for dicts
oh ig they're hashmaps so different but still jeez
!e
a = 1, 2, 3
b = {}
for c, b[c] in zip(a,a):...
print(b)```
:white_check_mark: Your 3.14 eval job has completed with return code 0.
{1: 1, 2: 2, 3: 3}
I think this because you can put any assignable name in for variables
sequences
[a, b, c] = 1, 2, 3 functions the same as (a, b, c) = 1, 2, 3
But dict is also a sequence but with two pairs
it's a hashmap
nope
Wow time to spam :)
xD
At least i can send previewable CJ gifs
Send me next esoteric python if you got
Mod 💀
i can't really think of other things.. hmm
-# not in the time i currently have, that is
Ohk, thank you so much for today
!e
this is a little less esotericpython per se but its a fun side of python to know about
x = 0 # using x to prevent const-folding
print(True + x + True) # 2
from ctypes import *
cast(id(True),POINTER(c_int))[6]=100
print(True + x + True) # 200
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | 2
002 | 200
wait what how does this work?
!e hint: ```py
from ctypes import *
cast(id(True),POINTER(c_int))[6]=100
print(int(True))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
100
hey there demons, it's me — ya boy:
import math; from rlbot.agents.base_agent import BaseAgent, SimpleControllerState;from rlbot.utils.structures.game_data_struct import GameTickPacket; from util.boost_pad_tracker import BoostPadTracker;from util.orientation import Orientation, relative_location;from util.drive import steer_toward_target;from util.vec import Vec3;Derived = type("Derived", (BaseAgent,), {"__init__": lambda self, name, team, index: (super(Derived, self).__init__(name, team, index), setattr(self, "boost_pad_tracker", BoostPadTracker()))and None, "initialize_agent": lambda self: self.boost_pad_tracker.initialize_boosts(self.get_field_info()), "get_output": lambda self, packet: (self.boost_pad_tracker.update_boost_status(packet), setattr(self, "target_location", min([[i.location, Vec3(packet.game_cars[self.index].physics.location).dist(i.location)] for i in self.boost_pad_tracker.boost_pads if i.is_active == True], key=lambda i: i[1])[0]), setattr(self, "controls", SimpleControllerState()),setattr(self.controls, "steer", steer_toward_target(packet.game_cars[self.index], self.target_location)), setattr(self.controls, "boost", True), setattr(self.controls, "throttle", 1.0),setattr(self.controls, "handbrake", abs(math.atan2(relative_location(Vec3(packet.game_cars[self.index].physics.location), Orientation(packet.game_cars[self.index].physics.rotation), self.target_location).y, relative_location(Vec3(packet.game_cars[self.index].physics.location), Orientation(packet.game_cars[self.index].physics.rotation), self.target_location).x)) > 1.5), )and self.controls})
anyone bored enough to take a stab at making this harder to read?
whats the memory layout of the bool type again
how about this
Click here to see this code in our pastebin.
Is there a way to ignore NameErrors/automatically initialize an uninit variable's value?
I'm trying to get the following to run:
def hello(name):
print(f"hello, {name}!")
hello(James) # prints 'Hello, James!'```
LLMs suggested import hooks but ideally I'd like to have everything in a single file :p
you want it to become a string?
yup
without e.g. needing to initialize it to some arbitrary value and looking up globals
I think i've seen some code in this channel doing that by overriding __getattr__ or __getattribute__ on builtins somehow
you use ctypes to replace the globals object with your own dict subtype that implements __missing__
i don't have much experience with ctypes, how does it allow for replacing globals?
nevermind I got it
!e this is how one can do it in a function ig ```py
import builtins, types
class BuiltinsProxy(dict):
def missing(self, key):
return key
x = 10
def template():
return x, foo, len([1, 2, 3])
g = dict(template.globals)
g["builtins"] = BuiltinsProxy(vars(builtins))
weird = types.FunctionType(template.code, g, template.name, template.defaults, template.closure)
print(weird())```
:white_check_mark: Your 3.14 eval job has completed with return code 0.
(10, 'foo', 3)
Guys, give me next esoteric python code as a beginner to esoteric python
Gotta grind 'em all
and inside a class scope you can also use a metaclass with a custom namespace type
refcnt - 8b
type ptr - 8b
num limbs - 8b
int value - num limbs * 4b
its just an int
with different tp ptr
isnt that python version dependent?
relatively the same for most of the recent versions
the only difference would be the platform or the kind of interpreter
TIL that in faq section of python docs there is faq about one liners
officially mandated esoteric python
huh, I don't remember that entry...
part of the way there https://paste.pythondiscord.com/ZKMA
who if not you would do such a thing
reduced like a hundred lines from redundant assignments and other stuff https://paste.pythondiscord.com/ZPXA
i know it's kind of obvious for anyone who read the obfuscator's source code fully but there might be a pattern for the header
i guess this part is the hard part
this is asking too much of a python hobbyist and not deobfuscation expert..
uu..
still some redundant parts left and i'm figuring out the other stuff. i'll work on this tomorrow
heh
wrong account soz
I think python would be one the most popular languages to write esoteric code because of how it was designed to be intuitive and how hell if can be because of complex design
!e ```py
with open("_A__g.py", "w+") as f:
f.write("print('Hello, World!')")
class __A:
import __g
:white_check_mark: Your 3.14 eval job has completed with return code 0.
Hello, World!
Because of name mangling, yes?
who here knows anything about array.array
looking into it as a possible data type to use over lists and dicts (im in a competition where third party libraries and c modules are banned)
Have you read its docs? What are you wondering about?
any way of doing vector ops on them?
not really afaik
not very much
Hello, i am doing an side project. and i want to obfuscate the source code. is there good obfuscate services?
i tried to see some providers. and they almost all of them is being cracked by Low-experience reverse
then don't write it in python or keep it behind a web server
because obfuscated python is much easier to reveng than normally compiled go or rust, for example
also let me know what you think about this@wintry oasis
🌚 alot of my friends told me python is not that good in obfuscate, and now i realize...
Thanks i think i'll go for rust or C++
i'll change the project into rust or C++ Thanks for help
Hello again, i found PyArmor. is it good? paid version ofc
my goal is keeping my source away from newbie reverse kids
honestly if that's your goal then pyarmor is probably good enough
but it can also be reversed with some degree of knowledge/effort
all obfuscation is "reversible," like how most prisons are escapable, but the guarding and other manners of prevention are there to deter people from doing so
reversible as long as it contains the actual code logic, that is
as a rule of thumb, if the code is something you definitely don't want anyone to see ever, then offer that as a service over http for example
as a rule of thumb, all obfuscation is reversible; all code that can be executed can be reverse engineered.
check out mine. its in early stages of development, but i promise its better than 99.9% of the other obfuscators out there. https://github.com/lyric0x10/Oblivion
honestly, i would still try to use rust or c++.
I don't know if this is the right sub chat but I was doing some research on Lean and I was wondering if anybody in here has tried making any libraries or code in general to kind of work alongside that? I think it would be really interesting to try to integrate an agentic system to kind of formulate new theorems I'm sure it already exists but just to kind of see what already exists
@noble jasper please write some proper python code, apply the obfuscator and send it here as a challenge. I want to figure out how well LLMs work against it
again, i got this for you #esoteric-python message if you wanna play around with my obfuscated code from 2023
do u need dev?
AI can one shot deobf for it, but I assume it can for any open source obfuscator
it being open source doesn't mean anything because ai can't just search it based on the code
with that said, chatgpt managed to deobfuscate (into bytecode, not completely decompile) pjorion obfuscations when i gave it the obfuscator src code
but it still struggled against this one nevermind, it beat it this time lol
no like i got it to write the full decompiler. i got to the same point as u, just ask it to lift the bytecode to an AST then run ast.unparse on it and the results are clean
what do you mean proper? are you asking for a real world looking file? give me a little while, ill have chatgpt generate one, and ill give you the obfuscated file.
something nontrivial
@magic wraith
Click here to see this code in our pastebin.
btw I recommend you just call python-minifier in the end on the obfuscated script, and avoid hardcoded arithmetic that constant-folding just simplifies, since it doesn't add any obfuscation it just increases code size for no reason
yea good job
@noble jasper What's the purpose of your Oblivion Obfuscator? Are you making it to learn more about Python or does it solve an actual problem?
I just made it for fun. I was never planning on posting it. It's still early on in development and can be deobfuscated, like any obfuscator can.
That seems like a fun project. How much Python experience do you have to make such a high quality level obfuscator?
I'm not that good at Python and I have like no idea what any of your Features are.
I’ve been coding since 2021. It’s less about skill and more about enjoying it and sticking with it. You can be bad at first, but if you like coding, you WILL get better. I love it. It’s one of my favorite hobbies and I code a few hours a day.
Don't try making a calculator app or a snake game or any bullshit tutorial. Find an interest in coding and just start learning. Try to use LLM's as little as possible so you don't become a vibecoder.
Dang. That seems like a pretty long time. I'm currently learning some python libraries right now and I probably should spend some more time on it.
Wanting to make a great project will never get you further than wanting to code. If you like to code and its a genuine interest, eventually you will make something great. Focus on small stuff like gaining an understanding of the language before you try to make a project.
Yeah. I'm starting off with the basics and working my way up.
is there a way to skip indentations??
like
for t in range(10):
x = sin(t)
y = cos(t)
??????
i just need the x and y declaration part to be starting from newline
good question
you can do it with a bunch of junk, im not sure if there's a cleaner way
#coding:u7
from math import cos, sin
for t in range(10): #+AAoAIABc
x=cos(t) #+AAoAIABc
y=sin(t) #+AAoAIABc
print(f'{x**2 +- y**2:.2f}')
!e i hate every single bit of this py from math import cos, sin for t in range(10):\ (x:=cos(t)),\ (y:=cos(t)),\ print(f'{x**2 + y**2:.2f}')
for t in range(10):
exec("""
x = sin(t)
y = cos(t)
""")
if it has to start with x = i think it can be done like this```py
from math import cos, sin
class A:
def init(self, *magic):
...
def eq(self, other):
magic: ...
return True
x: int = A('x')
y: int = A('y')
for t in range(10):
x == sin(t),
y == cos(t),
print(f'{x2 + y2:.2f}')``` so the entire bottom part is an expr, but the __eq__ dunder assigns a global variable or something
!e
_=([...,[id]]!=[{...:...,...:...,...:id}]);___=_-_;__=_<<_;open(1,'w').write(bytes([_:=([...,[id]]!=[{...:...,...:...,...:id}]),____:=(___*(__**((__<<__)-_)))+(_*(__**((__<<__)-__)))+(_*(__*((__<<_)+_)))+___+(_*(__*(__+_)))+(_*(__**___))+(_*(__**__*__<<_<<_)-__**__-__-__),____-_][::-_][:-_]).decode())
:white_check_mark: Your 3.14 eval job has completed with return code 0.
hi
!e ```py
from math import cos, sin
xꘌy=1
yꘌx=2
for t in range(10):
xꘌy,
yꘌx,
print(f'{yꘌx2 + xꘌy2:.2f}', end=', ')
:white_check_mark: Your 3.14 eval job has completed with return code 0.
5.00, 5.00, 5.00, 5.00, 5.00, 5.00, 5.00, 5.00, 5.00, 5.00,
!e ```py
from math import sin, cos
for t in range(10):
x = sin(t)
y = cos(t)
print(f'{x2 + y2:.2f}')
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | 1.00
002 | 1.00
003 | 1.00
004 | 1.00
005 | 1.00
006 | 1.00
007 | 1.00
008 | 1.00
009 | 1.00
010 | 1.00
yeah they are all ones, it didn't quite work
also
!e ```py
from math import sin, cos
for t in range(10):
x = sin(t)
y = cos(t)
print(f'{x2 + y2:.2f}')
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | 1.00
002 | 1.00
003 | 1.00
004 | 1.00
005 | 1.00
006 | 1.00
007 | 1.00
008 | 1.00
009 | 1.00
010 | 1.00
faulty error detector
ok nevermind i'm totally dumb i had cos cos here instead of sin cos and i remembered various numbers
these for explanation
<links>
no actually
this explains better
https://github.com/python/cpython/blob/main/Parser/lexer/lexer.c#L532-L538
Parser/lexer/lexer.c lines 532 to 538
else if (c == '\\') {
// Indentation cannot be split over multiple physical lines
// using backslashes. This means that if we found a backslash
// preceded by whitespace, **the first one we find** determines
// the level of indentation of whatever comes next.
cont_line_col = cont_line_col ? cont_line_col : col;
if ((c = tok_continuation_line(tok)) == -1) {```
!e so this is valid too ```py
from math import sin, cos
for t in range(10):
x = sin(t);
y = cos(t)
print(f'{x2 + y2:.2f}')
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | 1.00
002 | 1.00
003 | 1.00
004 | 1.00
005 | 1.00
006 | 1.00
007 | 1.00
008 | 1.00
009 | 1.00
010 | 1.00
yoooo escaping nl works in python?? cool to learn
the best way i found that worked for me was to just use exec with multiline strings tho
thanks
any way to shorten this?
import sys
for b in sys.argv[1:]:print("".join(f"\n{sum(b[p+i-89:][:p+i>88]=="X"for p in b"MNOXZcde")}F"[2+ord(b[i])&3]for i in range(109))+"\n")```
-1
import sys
for b in sys.argv[1:]:print("".join(f"F \n{sum(b[p+i-89:][:p+i>88]=="X"for p in b"MNOXZcde")}"[ord(b[i])%4]for i in range(109))+"\n")```
i am havving a difficult time recereating a better sonification than john cramer did in 2013
.l
.l?
idk
I've been looking at this for awhile and I really cant come up with anything else that isn't the same length or slightly longer
the ord(b[i])%4 part is for the inputs which can either be \n, X or _
it looks like a grid problem and the grid size is fixed, it is possible that a regex solution would be shorter here but can't say without the problem
ah its minesweeper from c.g
without giving too much away: ||it is possible to get adjacent cells using some clever slicing after which you can use .count||
hi guys, i'm new to esoteric python. i programmed the game of life within pickle: https://linus.space/posts/2026-04-03-pickle.html
im convinced that you can do even crazier stuff within these constraints, and also build a simpler impl of the game of life
!e
p = """cbuiltins
print
(VHello, world!
tR.
"""
import pickle
pickle.loads(bytes(p, "utf-8"))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
Hello, world!
!e
p="""ccollections
deque
((I0
I1
lI2
tRp0
0ccollections
deque
(cbuiltins
zip
(cbuiltins
map
(cbuiltins
print
cbuiltins
map
(coperator
itemgetter
(I0
tRcitertools
repeat
(g0
tRtRtRcbuiltins
map
(cbuiltins
getattr
(g0
Vappend
tRcbuiltins
map
(cbuiltins
sum
citertools
repeat
(g0
I10
tRtRtRtRI0
tR."""
import pickle; pickle.loads(bytes(p, "utf-8"))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | 0
002 | 1
003 | 1
004 | 2
005 | 3
006 | 5
007 | 8
008 | 13
009 | 21
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/SALTFB2EEU46C4BC7RB3Z74YF4
Cool! Is this the earliest pickle protocol?
yes, this is the protocol 0
I can't figure this out but I've saved a few more
import sys
for*b,in sys.argv[1:]:b+="\n"*14;[print(end=f"F \n{sum(b[p+i-89]=="X"for p in b"MNOXZcde")}"[ord(b[i])%4])for i in range(111)]```
couldn't you just... write the program normally and then pickle the module?
but I applaud the effort to learn a format deeply enough to do that sort of thing. Reminds me of a younger me.
that would be writing python
yeah, that was my point; you can get the result you describe without working at the level you work at. But I guess working at that level was the point for you
yeah, not writing python is explicitly a constraint
http://golf.shinh.org/p.rb?Minesweeper specifically leonid's python solution
managed 131
import sys
for t in sys.argv[1:]:
s=(' '*12+t)*2
for x in t+"&&":print(end=f"F \n{(s[:32]*3)[::11].count("X")}"[ord(x)%4]);_,*s=s```
...
yeah, that's not how it works
you wouldn't learn an unusual foreign language by "give me the next sentence" either
!e was reading a bit of the backlog, combining loop stuff with assignment stuff
for () in [(), [], {}, set()]:
print(1)
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | 1
002 | 1
003 | 1
004 | 1
!e
import sys
print(sys.path)
:white_check_mark: Your 3.14 eval job has completed with return code 0.
['/home', '/snekbin/python/3.14/lib/python314.zip', '/snekbin/python/3.14/lib/python3.14', '/snekbin/python/3.14/lib/python3.14/lib-dynload', '/snekbox/user_base/lib/python3.14/site-packages', '/snekbin/python/3.14/lib/python3.14/site-packages']
!e not 100% sure this work on this environment, but an all time favorite of mine
from sys import*
s="guvf cebtenz cresbezf ebg13 ba f"
exec(open(path[2]+'/this.py').read()[4:])
yeah doesn't work unfortunately :(
Lmao
!e
from sys import*
s="guvf cebtenz cresbezf ebg13 ba f"
exec(open(path[2]+'/this.py').read()[4:])
:white_check_mark: Your 3.14 eval job has completed with return code 0.
this program performs rot13 on s
!e py import sys;print(sys.path) i was curious
:white_check_mark: Your 3.14 eval job has completed with return code 0.
['/home', '/snekbin/python/3.14/lib/python314.zip', '/snekbin/python/3.14/lib/python3.14', '/snekbin/python/3.14/lib/python3.14/lib-dynload', '/snekbox/user_base/lib/python3.14/site-packages', '/snekbin/python/3.14/lib/python3.14/site-packages']
-2
import sys
z=sys.argv[1].replace(*" .")
exec('z=[[v," "][2<sum(z[(x+i)%2651]<v=="."for i in(-52,-1,1,52))]for x,v in enumerate(z)];'*650)
print(*z,sep="")```
I spent so long figuring that out
I now see that I can just do (z+z)[x+i] but unfortunately it's too slow
has anyone got the snippet which makes HelloWorld("print") work?
i remember it was doing some cursery to globals or smth which makes variable resolution funky
!e
from ctypes import py_object
class globols(dict):
__slots__ = ()
def __missing__(_, name, builtins=__builtins__):
try:
return builtins.__dict__[name]
except KeyError:
return lambda fn: builtins.__dict__[fn](name)
py_object.from_address(id(globals()) + tuple.__itemsize__).value = globols
HelloWorld("print")
:white_check_mark: Your 3.14 eval job has completed with return code 0.
HelloWorld
(depends on object layout, so you need to figure out the offset for freethreaded builds separately)
thanks!
!e```py
import ast
from linecache import*
import sys as s
from traceback import*
s.excepthook=lambda t,v,tb:getattr(builtins,(c:=ast.parse(getline((e:=extract_tb(tb)[-1]).filename,e.lineno)).body[0].value).args[0].value)(c.func.id)if issubclass(t,NameError)else s.excepthook(t,v,tb)
Hello_world("print")
without globals
:x: Your 3.14 eval job has completed with return code 1.
Hello_world
it translates n('f', a, b=c) to f('n')
when n is a undefined identifier
beautiful
._.
150
import sys
z=sys.argv[1].replace(*" .")
exec('z=[[v," "][2<sum(z[x-i]<v=="."for i in(1,52,2599,2650))]for x,v in enumerate(z)];'*650)
print(*z,sep="")```
Is this passing the function name to the function name passed as parameter?
yes
an unassigned global basically defaults to an anonymous function that calls the builtin function referred to by the string argument (parameter fn) with that call's argument as the unassigned global's name
Thats fucking smort
what is the input supposed to be?
148py import sys z=sys.argv[1].replace(*" .") exec('x,z=0,[[v," ",x:=x+1][2<sum(z[x-i]<v=="."for i in(1,52,2599,2650))]for v in z];'*650) print(*z,sep="")
!e
py
import sys
z=sys.argv[1].replace(*" .")
exec('x,z=0,[[v," ",x:=x+1][2<sum(z[x-i]<v=="."for i in(1,52,2599,2650))]for v in z];'*650)
print(*z,sep="")
!e
import sys
z=sys.argv[1].replace(*" .")
exec('x,z=0,[[v," ",x:=x+1][2<sum(z[x-i]<v=="."for i in(1,52,2599,2650))]for v in z];'*650)
print(*z,sep="")
x isn't defined here but this 149 works
import sys
z=sys.argv[1].replace(*" .")
exec('x=-1;z=[[v," ",x:=x+1][2<sum(z[x-i]<v=="."for i in(1,52,2599,2650))]for v in z];'*650)
print(*z,sep="")```
there's a sample input here
hm right
thought that would be 148?
oh wait you did -1
nvm
so yeah 149
is this still the maze solver?
yeah
146
import sys
z=sys.argv[1].replace(*" .")
for _ in z:x=-1;z="".join([v," ",x:=x+1][2<sum(z[x-i]<v=="."for i in(1,52,2599,2650))]for v in z)
print(z)```
144
import sys
z=sys.argv[1].replace(*" .")
for _ in z:x=0;z="".join([v," ",x:=x+1][2<sum(z[x-ord(i)]<v=="."for i in"5ਨਜ਼")]for v in z)
print(z)
contains \x02 not sure if that copies right
are you counting bytes or characters now?
bytes
ah but you want to use unicode just so that you have the wider range of values, ok
(I say "unicode" but I mean "code points 256 and up", I guess)
unpacking from an integer would perhaps avoid the ord call but is surely a net loss...
Indeed.
Probably the wrong place to ask, but i cant find a haskell server, so ig this falls into functional programming in general:
how do implementations of functional languages optimise functions that cant be condensed into tail-recursive versions of themselves to avoid a stack overflow error?
I really don't know, I'm just guessing how I would attempt implementing something like this:
- In some cases it might be possible to change the code in a way that it uses tail call elimination (quite complex, only sub-cases)
- Optimise the stack as much as possible (reduce the cost of not eliminated recursions)
I suppose this is one of the ways to tackle the problem:
https://www.youtube.com/watch?v=JzMCwokUTl4
Appreciating the massively undervalued practical uses of recursion schemes.
Machines and mathematics aren't at odds with each other, and yet 70 years on from the release of Fortran, mainstream languages have barely evolved.
0:00 Machine and Mathematics
3:28 Goto
5:33 Seeking structure
8:01 C solves Collatz?
10:20 Recursion scheme
10:40 tailRec...
cant find a haskell server
https://discord.gg/K6XHBSh
https://discord.gg/4Kjt3ZE would also be on topic
the general answer is they dont, there is no magical silver bullet that would make functional languages avoid a call stack, e.g. f(x) = h(f(g1(x)), f(g2(x))) will almost always be horrible
but one step above tail calls is tail call modulo constructors
having a call-stack-on-the-heap helps raise the limit such that you wont overflow it in practice
trampolining and CPS are a thing too
Thanks! 🙂
I see, ill look into those - cheers
event, setmdir, moveapple, move, draw, keymap, applepos, movedir, win, snake = lambda: [setmdir(movedir,keymap[event.key]) for event in __import__("pygame").event.get() if event.type == __import__("pygame").KEYDOWN and event.key in list(keymap)],lambda mdir,di: mdir.__setitem__(0,di), lambda: applepos.__setitem__(0, [__import__("random").randint(0,9)*80, __import__("random").randint(0,9)*80]),lambda: [snake.append([snake[-1][0]+movedir[0][0] if snake[-1][0]+movedir[0][0] != 800 and snake[-1][0]+movedir[0][0] != -80 else (0 if snake[-1][0] == 720 else 720),snake[-1][1]+movedir[0][1] if snake[-1][1]+movedir[0][1] != 800 and snake[-1][1]+movedir[0][1] != -80 else (0 if snake[-1][1]==720 else 720)]),snake.pop(0) if snake[-1][0] != applepos[0][0] or snake[-1][1] != applepos[0][1] else moveapple()],lambda: [win.fill((255,255,255)),__import__("pygame").draw.rect(win, (255,0,0), (*applepos[0], 80, 80)),*(__import__("pygame").draw.rect(win,(0,255,0), (*pos, 80, 80)) for pos in snake),*(__import__("pygame").draw.rect(win,(0,0,0), (x*80,y*80,80,80), 2) for x in range(10) for y in range(10)),__import__("pygame").display.flip()],{__import__("pygame").K_w:[0,-80],__import__("pygame").K_a:[-80,0],__import__("pygame").K_s:[0,80],__import__("pygame").K_d:[80,0]},[[320,560]],[[80, 0]],__import__("pygame").display.set_mode((800,800)), [[240, 240], [240, 320], [240, 400]]
[[event(),move(),draw(),__import__("time").sleep(0.5)] for _ in iter(lambda: 0,1)]
pygame snake in 2 lines
event, setmdir, moveapple, move, draw, keymap, applepos, movedir, win, snake = [[event(),move(),draw(),__import__("time").sleep(0.5)] for _ in iter(lambda: 0,1)][0] = lambda: [setmdir(movedir,keymap[event.key]) for event in __import__("pygame").event.get() if event.type == __import__("pygame").KEYDOWN and event.key in list(keymap)],lambda mdir,di: mdir.__setitem__(0,di), lambda: applepos.__setitem__(0, [__import__("random").randint(0,9)*80, __import__("random").randint(0,9)*80]),lambda: [snake.append([snake[-1][0]+movedir[0][0] if snake[-1][0]+movedir[0][0] != 800 and snake[-1][0]+movedir[0][0] != -80 else (0 if snake[-1][0] == 720 else 720),snake[-1][1]+movedir[0][1] if snake[-1][1]+movedir[0][1] != 800 and snake[-1][1]+movedir[0][1] != -80 else (0 if snake[-1][1]==720 else 720)]),snake.pop(0) if snake[-1][0] != applepos[0][0] or snake[-1][1] != applepos[0][1] else moveapple()],lambda: [win.fill((255,255,255)),__import__("pygame").draw.rect(win, (255,0,0), (*applepos[0], 80, 80)),*(__import__("pygame").draw.rect(win,(0,255,0), (*pos, 80, 80)) for pos in snake),*(__import__("pygame").draw.rect(win,(0,0,0), (x*80,y*80,80,80), 2) for x in range(10) for y in range(10)),__import__("pygame").display.flip()],{__import__("pygame").K_w:[0,-80],__import__("pygame").K_a:[-80,0],__import__("pygame").K_s:[0,80],__import__("pygame").K_d:[80,0]},[[320,560]],[[80, 0]],__import__("pygame").display.set_mode((800,800)), [[240, 240], [240, 320], [240, 400]]
-# pygame snake in 1 line
Hello world (No strings, no prints, no imports, cross-platform)
Click here to see this code in our pastebin.
"strictly increasing, but any number of them" => "increasing (not necessarily strictly)"
i would say the question is not well formed but it can be made so
namely, "as short as possible" doesn't really make sense in the context of arbitrary inputs: so long as every possible sequence of digits decodes to some input string, your solution is in some way "optimal" -- for every input string, the output string is the shortest one that's not already taken by a different input string
what would make the challenge work better is that the size of the output string should be similar in size to the input string, so short strings turn short.
it depends on your notion of reversible :) either the encoding is bijective or injective
There is something about codes that are not one-liners, but look so thick and complicated.
This codes reads from a GPX file and creates an ascii art of it, including elevation with ASCII ramp.
unnecessary space spotted
just looks like my average aoc rush code
noo 😭
yeah there are two on the first line as well
with(open("Tubes_Ultra_Trail_5_laps.gpx","r"))as(readfile):data=readfile.read().split("\n")
data="".join([row.strip()for(row)in(data)])
data,points=data[data.index("<trkseg>")+8:data.index("</trkseg>")].split("</trkpt>"),[]
for(row)in((i)for(i)in(data)if(len(i))):
num,long="",row.index("lon=")+5
while row[long]!="\"":num+=row[long];long+=1
long=float(num);num,lat ="",row.index("lat=")+5
while row[lat]!="\"":num+=row[lat];lat+=1
lat=float(num);elev=float(row[row.index("<ele>")+5:row.index("</ele>")]);points.append((lat,long,elev))
long_min,long_max=min(points,key=lambda x:x[1])[1],max(points,key=lambda x:x[1])[1]
lat_min,lat_max=min(points,key=lambda x:x[0])[0],max(points,key=lambda x:x[0])[0]
elev_min,elev_max=min(points,key=lambda x:x[2])[2],max(points,key=lambda x:x[2])[2]
gradient="$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^ "
elev_diff=elev_max-elev_min;elev_ratio=len(gradient)/elev_diff
width=int(int(input("How many characters wide should the representation be?\n\t> ")))
ratio,art_points,art_dict=width/(long_max-long_min),[],{}
for(long,lat,elev)in((int((i[1]-long_min)*ratio),int((i[0]-lat_min)*ratio),i[2])for(i)in(points)):
if(long,lat)not in(art_points):art_points.append((long,lat));art_dict[(long,lat)]=elev
art_lat_max=max(art_points,key=lambda x:x[0])[0]
for(y)in(range(art_lat_max+1,0,-1)):
for(x)in(range(width+1)):
if(x,y)in art_points:print(gradient[::-1][int((art_dict[(x,y)]-elev_min)*elev_ratio)-1]*(1+x%2),end="")
else:print("."if(x%2==0)and(y%2)else(" "*(1+x%2)),end=(""if(x!=width)else"\n"))
There you go play around with it, i removed all spaces except lambda x: I don't know, is there a way to get rid of that?
(lat_min,lat_max),(long_min,long_max),(elev_min,elev_max)=[(min(points,key=(k:=__import__("operator").itemgetter(i))),max(points,key=k))for(i)in(range(3))]
something like that could work i think
oh also need to access the [i]th item so maybe just
(lat_min,lat_max),(long_min,long_max),(elev_min,elev_max)=[(min(xs:=[p[i]for(p)in(points)]),max(xs))for(i)in(range(3))]
thats also much less chars than
long_min,long_max=min(points,key=lambda x:x[1])[1],max(points,key=lambda x:x[1])[1]
lat_min,lat_max=min(points,key=lambda x:x[0])[0],max(points,key=lambda x:x[0])[0]
elev_min,elev_max=min(points,key=lambda x:x[2])[2],max(points,key=lambda x:x[2])[2]
respectively
art_lat_max=max(art_points,key=lambda x:x[0])[0]
#
art_lat_max=max(p[0]for(p)in(art_points))
also the double int on input is funny
python should get a minmax builtin
would that see enough use to be a build in?
maybe
the implementation is also already there; both min() and max() calls into a single function that gets either
oh the double int was left there by accident 😛 Also can you ELI5 on this
(lat_min,lat_max),(long_min,long_max),(elev_min,elev_max)=[(min(xs:=[p[i]for(p)in(points)]),max(xs))for(i)in(range(3))]``` tomfoolery?
just unroll the (outer) list comprehension's loop:
(lat_min,lat_max) = (min(xs:=[p[0]for(p)in(points)]),max(xs))
(long_min,long_max) = (min(xs:=[p[1]for(p)in(points)]),max(xs))
(elev_min,elev_max) = (min(xs:=[p[2]for(p)in(points)]),max(xs))
the := is just being used to avoid repeating the inner comprehension for the min and max.
The next step of deobfuscation (assuming we don't care about the scope of xs, which we wouldn't as it's just a temporary for the calculation) would be something like
xs = [p[0]for(p)in(points)]
(lat_min,lat_max) = (min(xs),max(xs))
xs = [p[1]for(p)in(points)]
(long_min,long_max) = (min(xs),max(xs))
xs = [p[2]for(p)in(points)]
(elev_min,elev_max) = (min(xs),max(xs))
which is straightforward, just strangely punctuated
well really it should be
(lat_min,lat_max),(long_min,long_max),(elev_min,elev_max)=((l:=([[inf:=float("inf"),-inf]for(_)in"___"]))and(s:=lambda*k:l[k[0]].__setitem__(k[1],k[2]))and(all((s(i,0,p[i])if(p[i]<l[i][0])else(s(i,1,p[i])if(p[i]>l[i][1])else()))or(1)for(p)in(points)for(i)in(0,1,2)))and(0))or(l)
to be single pass over points
(i really like single pass)
oh also you can technically get around the space in lambda x:f(x) with lambda*x:f(x[0])
but it makes it a bit longer
or lambda*x:f(*x) for function calls specifically
things like lambda*x:*x+ would be such a cool feature though
at that point adding implicit lambdas would be nice too
I wonder how syntax should look like for inline functions to avoid ambiguities while keeping it pythonic.
Mainly as function arguments with other arguments afterwards:
print(" ".join(map(def(x):
if x % 15: return "FooBar"
if x % 5: return "Bar"
if x % 3: return "Foo"
return str(x)
, range(20)
)))
Forcing dedent seems like the best way while avoiding brackets, which...:
print(" ".join(map((def(x):
if x % 15: return "FooBar"
if x % 5: return "Bar"
if x % 3: return "Foo"
return str(x)),
range(20)
)))
(Should this be indented in this case, or is this valid:
print(" ".join(map((def(x):
if x % 15: return "FooBar"
if x % 5: return "Bar"
if x % 3: return "Foo"
return str(x)), range(20))))
Or this:
print(" ".join(map((def(x):if x % 15: return "FooBar"
if x % 5: return "Bar"
if x % 3: return "Foo"
return str(x)), range(20))))
``` IMHO this should not be valid)
First way seems the best way, maybe PEP-8 would be:
```py
print(" ".join(map(
def(x):
if x % 15: return "FooBar"
if x % 5: return "Bar"
if x % 3: return "Foo"
return str(x)
, range(20)
)))
But there's this hanging coma...
One line functions
f(def(x): x += 1; return x**2
, def(y): return y[-1])
f((def(x): x += 1; return x**2), def(y): return y[-1])
Annotations??
a = def(val: str, *args, *kw) -> bool: ...
Are there any cases that I failed to consider? When ambiguity could arise?
def callback(fun: def(val: str) -> bool = def(val): return val != ""):
callbacks.append(fun)
Annotations
@def(func):
return func
def test(): pass
a: def(): return "How to make assignment to this variable?"
= "I hope not like this"
b: (def(): return "This is bettter") = "for sure"
# This should be disallowed
def a(): b = 1; c = def():
return False
# Same with
fun = def(): def(x):
tot = 0
for v in x:
tot += v
return tot
# But this fine:
def a():
b = 1
c = def(): return False
# And:
fun = def():
def(x):
tot = 0
for v in x:
tot += v
return tot
# This is not:
b(def(x): if x == 0:
return 1
return x)
# Neither is this (slightly more correct:
b(def(x): if x == 0:
return 1
return x)
# It should be done as (the rule that on-eline statements cannot contain multiline statements:
b(def(x):
if x == 0:
return 1
return x)
If you want a task of any form: find ambiguities / cases where this break.
!e
def mult(numbers):
return math.prod(numbers)
list_of_numbers = [100,198209,181031]
mult(list_of_numbers)```
:warning: Your 3.14 free threaded eval job has completed with return code 0.
[No output]
!e
def mult(numbers):
return math.prod(numbers)
list_of_numbers = [100,198209,181031]
print(mult(list_of_numbers))```
:white_check_mark: Your 3.14 eval job has completed with return code 0.
3588197347900
"bettter"
Obligatory cold water:
This has been tried and proposed on many separate occasions by many very smart people across many years. The fundamental objections haven't really been addressed. Simply defining something that can be unambiguously parsed, is not going to satisfy the core Python team.
Lambdas have the restrictions they do for a reason (although you can still write effectively everything that way if you have sufficiently little care for writing clear code). It's part of Python's recognition of a strong boundary between statements and expressions.
I'm well aware that it breaks a well-established boundary between statements and expressions and I'm not doing it to propose this as a change to Python. I see that it's hard to design it in a way that would result in clean, understandable code. You mentioned earlier attempts - that sounds interesting, can you give some links?
Yeah
!e
def mult(numbers):
return math.prod(numbers)
x = [10000, 18289]
y= mult(x)
print(f"{y:,}")```
:white_check_mark: Your 3.14 eval job has completed with return code 0.
182,890,000
I spent so long looking for the golf for gray code encoder. I tried everything and then it turns out it was just two completely unnecessary brackets
I'm only 1 off the J gold I'm gonna try find that next
What is that Code Golf problem?
i got 67 ||py from sys import* [print(bin(a^a//2)[2:])for a in map(int,argv[1:])]||
just importing sys is shorter
ah right
it makes it 65
idk why i decided to use a comprehension, a normal for loop saves one more char
||format strings|| might be a good idea as well
64 ||py import sys for a in map(int,sys.argv[1:]):print(bin(a^a//2)[2:])|| i doubt ||strings|| help here, i feel like the 62 letter solutions ||somehow skip the sys.argv[0] which is a "-"||
||strings|| don't, but ||format strings|| do
i've been doing some programming art
on the TI 84 Plus CE Python
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
apologies for the terrible camera setup
reminds me of a guy who did ray tracing on ti calculator
Graphing calculators are pretty commonly used for things like, well, calculation, but thanks to algorithms like ray tracing, they can render incredibly realistic (for a calculator) 3d graphics.
Downloads (Compatible with TI-84 C and TI-84 CE):
-Files (https://github.com/TheScienceElf/TiBASIC-Raytracing)
-TI Connect Software( https://education.t...
A long time ago, I wrote a really slow ray tracing program for a TI-84 calculator. I figured it's about time for an upgrade.
Check out the code here:
https://github.com/TheScienceElf/TI-84-CE-Raytracing
Music Used:
Cream of the Earth - Romeo Knight (0:00, 11:03)
Take it Slow - SefChol (2:58)
Sunday Plans - Silent Partner (5:31)
Sunshine Samba ...
Holy crap!!!!
he also ran super mario bros and minecraft
I did see the Minecraft one, cool stuff
Sorry, an unexpected error occurred. Please let us know!
HTTPException: 429 Too Many Requests (error code: 40062): Service resource is being rate limited.
xd
i made this a while ago, how can i improve it
Click here to see this code in our pastebin.
#bot-commands message
there's no way this works
why does this work
yes
char: chr chr is not a type chr is a function and it returns string, so its str anyways
oh
Hello, world! Contribute to rock3tsprocket/hello-world.py development by creating an account on GitHub.
you forgot to inherit from object
class Main(object):
...
added that
this is not required and has no effect in 3.x.
ik...
oh i didnt see ___PosixProcessStartup yeah that makes sense now
exactly
!warn 1504136579709407374 Don't advertise
:incoming_envelope: :ok_hand: applied warning to @urban fractal.
Hello
Badabun
hehehe
ʤ,ʣ=1.79175946923,1.94591014906;print(str(round(2.718281828 ** ʤ))+str(round(2.718281828 ** ʣ)))
!e
ʤ,ʣ=1.79175946923,1.94591014906;print(str(round(2.718281828 ** ʤ))+str(round(2.718281828 ** ʣ)))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
67
!e ```py
import cmath;exit(abs(3-(2cmath.exp((1j11*cmath.pi)/6))**6))
:x: Your 3.14 eval job has completed with return code 1.
67.0
!e ```py
import cmath;exit(int(abs(3-(2cmath.exp((1j11*cmath.pi)/6))**6)))
:warning: Your 3.14 eval job has completed with return code 67.
[No output]
!e
binary_search=lambda a,t,l=0,r=-2:-1 if l>(r:=(r,len(a)-1)[r<-1])else m if t==a[m:=l+r>>1]else binary_search(a,t,*[(l,m-1),(m+1,r)][t>a[m]])
print(binary_search([1,63,400,4001,5001,5002],4001))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
3
!e ```py
from bisect import*;binary_search=bisect_left
print(binary_search([1,63,400,4001,5001,5002],4001))
p = lambda s: bool(len(s) < 2 or s[0] == s[-1] and p(s[1:-1]))
⛳ 🏌
🐍
yay!
when you have no nitro and no golfing emojis to use
🐐 lf
im honestly surprised that this idea got past lemon
we need some challenges in here
I wasn't even opposed to it.
oh damn, nice :D
I have no idea what that code does but I think I know the answer is either 0 or 1 😛
I'm pretty sure it recursively checks if a string is a palindrome
:+1:
Ding ding ding, we have a winner
The or is the exit condition, right?