#esoteric-python
1 messages · Page 146 of 1
@humble rune
look at this: https://github.com/AFK-debug-9/test
not poggers
those programs are super long
😔
from requests import post
from time import sleep as z
from random import randint as y,choice
from sys import argv as a,exit as q
print(f"Golfing Progress:{len(open(a[0]).read())-106} characters")#This is just for measuring code length
if "-h"in a:q(f"python3 {a[0]} -i <input file>\nHow to use:\nPut the token(s) on the first line of the file and separate them with \"|\"\nPut the channel ID on the second line\nThen put the messages after\nAfter that you can add optional flags:\n-s: show the amount of messages left\n-r: send messages randomly\n-h: show this")
del a[0]
if 1-("-i"in a):q("missing input file\ntry running -h")
f=open(a[a.index("-i")+1]).read().splitlines()
t,c=f[0].split("|"),f[1]
exec("del f[0];"*2)
s=lambda r:r.status_code
l,r=-1,"-r"in a
while True:
l=[l+1,0][l>=len(f)-1]
m=o=[f[l],choice(f)][r]
m,x=[f"[{l+1}/{len(f)}]: "+m,f"[{f.index(o)+1}/{len(f)}]: "+m][r],0
for i in t:
d=post(f"https://discord.com/api/v9/channels/{c}/messages",headers={"Authorization":i},data={"content":m,"nonce":y(0,int("9"*23)),"tts":False})
if s(d)==404or s(d)==400:q("Channel not found")
elif s(d)==401:q("Incorrect token")
elif s(d)==429:x=int(d.json()["retry_after"])
z(2.5+x)
Any tips on shaving a few characters without harming QoL?
dead chat 😔
!rules 2
2. Follow the Discord Community Guidelines and Terms Of Service.
@humble rune that breaks discord TOS
you can change a type's __dict__ by writing to id(obj) + 264
however, when using __dict__ directly it'll always convert to a mapping_proxy
You can still mutate elements pointed to by mapping_proxy thanks to a cpython bug
er there was a demo here a couple times I think, hold on
Here's one I think
I think you would need write to id + 248 to disable this behavior
tp_getset or whatever it was
specifically changing it to a null pointer
or changing the __dict__'s entry in the table
if you null out tp_dict it will crash when using the type
replacing it can also have weird effects
!e ```py
def getdict(cls, E=type('',(),{'eq':lambda s,o:o})()):
return cls.dict == E
getdict(int)['bit_length'] = 42
print((1).bit_length)```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
42
^ that works too
I was just trying to mess around and make a metaclass that isn't an instance of type so it can have a custom __dict__ that isn't a proxy and then I ended up messing around and reading cpython source code
i wounder how can such code work...
#esoteric-python message here is when i worked through why that bug exists
however without ctypes, you'll be guaranteed to run into errors about your metaclass not being a class, and then that leads your own object class
what this code is supposed to compute?
it exploits a bug with how mappingproxies work, and uses it to get the int types internal class dictionary
Impressive!
Hey @wheat river!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
@fishhook.hook_cls(object)
class Ingredients:
ingredients = [...]*2**30
that would fix it
what does that do?
i dont quite understand how to implement this
And this is why this channel should be quarantined so poor souls can't wander in
@simple plinth #❓|how-to-get-help
this channel is for cursed python
Not the best spot to find help
they banned me from the help channels for some reason

yeah
Who did, and did they give a reason?
i dont know but i dont have permission to type in any of the help channels.
Well that would be dormant ones
Hey. i could use some help getting my pygame to work properly
It's not that we can't help you here, it's that all of us distrust the rest of us to be giving 'good' help while also being tempted to perform for this particular audience ... 😄
💀
!e import fishhook
@wheat river :warning: Your eval job has completed with return code 0.
[No output]
D:::
!e
import fishhook
@fishhook.hook_cls(object)
class Ingredients:
ingredients = [...]*2**2
print(str.ingredients)
print(int.ingredients)
print(type.ingredients)
@wheat river :white_check_mark: Your eval job has completed with return code 0.
001 | [Ellipsis, Ellipsis, Ellipsis, Ellipsis]
002 | [Ellipsis, Ellipsis, Ellipsis, Ellipsis]
003 | [Ellipsis, Ellipsis, Ellipsis, Ellipsis]
owo
What is that hack again where you can make so if you type any unbound variable in a repl it just returns the name of the variable?
I remember seeing it here somewhere but cant find it
>>> x = 3
>>> x
3
>>> foo
"foo"
Ah found it
__builtins__=type('', (dict,), {'__missing__': lambda *args: args[1]})(__builtins__.__dict__)
x)
Hey,
is there any way to make it shorter? for i in range(n)
for i in range(tick):
if Vy < 0.5:
Vy = 0
print("...")
inertia = True
else:
print("....")
Vy = (Vy - 0.08) * 0.98
thats the full code
trying to one-line it
!e deque.rotate for lists:
import random
x = [1, 2, 3, 4, 5]
random.shuffle(x, lambda:0)
print(x)
@sudden osprey :white_check_mark: Your eval job has completed with return code 0.
001 | <string>:3: DeprecationWarning: The *random* parameter to shuffle() has been deprecated
002 | since Python 3.9 and will be removed in a subsequent version.
003 | [2, 3, 4, 5, 1]
bonus points for deprecation warning?
You're calling a function with a keyword argument of the same name? And does the for i in range(n) belong to it?
nah, for i in range(n) for just an example
my bad, typo
table_data = [
data for i, j in zip(soup.find_all('th')[1:15], soup.find_all('td')[1:15])
if '...' not in (data := {
'inline': False,
'name': i.text if i.text else '...',
'value': '...' if valid_chars.match(j.text) else j.text if j.text else '...'
}
).values()
]
needs shortening
if([_:=(...)],[__:=({_}|{_})]):{(lambda:exec("with open(1, 'r+') as console:console.write('Result:'+str({}).format(console.readlines()))"))()};
``` Could anyone help, I am getting:
```Traceback (most recent call last):
File "main.py", line 1, in <module>
if([_:=(...)],[__:=({_}|{_})]):{(lambda:exec("with open(1, 'r+') as console:console.write('Result:'+str({}).format(console.readlines()))"))()};
File "main.py", line 1, in <lambda>
if([_:=(...)],[__:=({_}|{_})]):{(lambda:exec("with open(1, 'r+') as console:console.write('Result:'+str({}).format(console.readlines()))"))()};
File "<string>", line 1, in <module>
io.UnsupportedOperation: File or stream is not seekable.```
use r instead of r+
ooh, wait, no - I see what you're doing. Hm.
you're trying to write to read from stdout.
That's not gonna work.
how can I get input then?
ty
lemme try
if([_:=(...)],[__:=({_}|{_})]):{(lambda:exec("open(1, 'w').write('Result: '+open(0, 'r').readline(1))"))()};
Input: 1+1
output: 1
thinking readline is only catching the first part
if([_:=(...)],[__:=({_}|{_})]):{(lambda:exec(f"open(1, 'w').write('Result:'+str({open(0, 'r').readline(9999)}))"))()};
``` Janked solution, but it works. Thanks @signal herald for the help.
what am I doing wrong here
from ctypes import *
from time import *
tm = POINTER(c_int * 10).from_address(
CDLL("").malloc(sizeof(c_int) * 10)
)
# ok so far
# tm = <__main__.LP_c_int_Array_10 object at 0x5555cd4810>
PyDLL("")._PyTime_gmtime(
c_uint(int(mktime(gmtime(0)))),
tm
) # crash
struct tm {
int tm_sec; /* Seconds. [0-60] (1 leap second) */
int tm_min; /* Minutes. [0-59] */
int tm_hour; /* Hours. [0-23] */
int tm_mday; /* Day. [1-31] */
int tm_mon; /* Month. [0-11] */
int tm_year; /* Year - 1900. */
int tm_wday; /* Day of week. [0-6] */
int tm_yday; /* Days in year.[0-365] */
int tm_isdst; /* DST. [-1/0/1]*/
long int tm_gmtoff; /* Seconds east of UTC. */
const char *tm_zone; /* Timezone abbreviation. */
};```
int _PyTime_gmtime(time_t t, struct tm *tm);```
typedef long int __time_t; /* Seconds since the Epoch. */```
probably a lot wrong but I'm mostly like to not crash
nice exec from a lambda 
shouldn't you do malloc(sizeof(c_int) * 9 + sizeof(c_long) + sizeof(c_char_p))
oops, probably yeah
that far still works 🥳
>>> tm <__main__.LP_c_int_Array_10 object at 0x5555cc3e40>```
also doesn't tm_zone have to have a value or something
hmm
it crashes in PyCPointerType_paramfunc for my
(gdb) p obj $1 = <LP_c_int_Array_10 at remote 0x5555ae19a0>
-->> parg->value.p = *(void **)self->b_ptr;```
lemme see if I can figure out how to initialize that field
oh crap
self.b_ptr is
b_ptr = 0x55b2edf0 <error: Cannot access memory at address 0x55b2edf0>,
I guess it's not a valid pointer to memory
maybe I need two allocations?
like I need to actually allocate space for the pointer
?
probably
or you can create a struct using Structure
now I think you were onto something
>>> st = c_size_t(addressof(tm))
>>> PyDLL("")._PyTime_gmtime(c_uint(int(mktime(gmtime(0)))), st) Reading in symbols for offtime.c...
Program received signal SIGSEGV, Segmentation fault.
0x0000007ff78b1648 in __offtime (Reading in symbols for tzset.c...
Reading in symbols for /data/media/0/src/python3/src/Python/pytime.c...
t=0, t@entry=0, offset=0, offset@entry=0, tp=0x55b2edf0, tp@entry=0x55b2edf0) at /data/media/0/src/glibc/2.31/src/time/offtime.c:52
52 tp->tm_wday = (4 + days) % 7;```
thatd be the better way, I would need to read the values eventually anyway I guess
there is struct_time in the time module but I wasn't sure if I could use that
yes my tp is pointing to invalid memory apparently
(gdb) p tp $1 = (struct tm *) 0x55b2edf0 (gdb) p tp[0] Cannot access memory at address 0x55b2edf0
I didn't don't know it was gonna be this hard to make one call 😂
definitely gives me an apprefciation for the volumes of C code
thanks for your help, I will keep fiddling with it.. trying that next
thanks lol
:incoming_envelope: :ok_hand: applied mute to @spice wren until <t:1649559471:f> (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
!e ```py
from ctypes import *
from time import *
class tm(Structure):
fields = [
('tm_sec', c_int),
('tm_min', c_int),
('tm_hour', c_int),
('tm_mday', c_int),
('tm_mon', c_int),
('tm_year', c_int),
('tm_wday', c_int),
('tm_yday', c_int),
('tm_isdst', c_int),
('tm_gmtoff', c_long),
('tm_zone', c_char_p)
]
pythonapi._PyTime_gmtime.argtypes = [c_long, POINTER(tm)]
T = tm()
pythonapi._PyTime_gmtime(int(mktime(gmtime())), byref(T))
print(T.tm_sec, T.tm_zone)```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
15 b'GMT'
@rapid sparrow ^
Hey, is there any writeup or something about how to one-line code?
Would love to learn it
oh wow, thanks ! you are the master 
so I needed to define .argtypes for it to work?
also didn't know byref was a thing
!e ```py
from ctypes import *
from time import *
class tm(Structure):
fields = [
('tm_sec', c_int),
('tm_min', c_int),
('tm_hour', c_int),
('tm_mday', c_int),
('tm_mon', c_int),
('tm_year', c_int),
('tm_wday', c_int),
('tm_yday', c_int),
('tm_isdst', c_int),
('tm_gmtoff', c_long),
('tm_zone', c_char_p)
]
T = tm()
pythonapi._PyTime_gmtime(int(mktime(gmtime())), byref(T))
print(T.tm_sec, T.tm_zone)
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
18 b'GMT'
it's unneeded
interesting
y,vy=0,0.42
for i in range(130):
print("tick n°",i,"| Y speed:",vy,"| Y position:",y)
y,vy=y+vy,(vy-0.08)*0.98
if(abs(vy)<0.005):vy=0
How can I one-line it?
y,vy=0,0.42
type = lambda w: ([(print("tick n°",i,"| Y speed:",vy,"| Y position:",y)) for i in range(w)], if(abs(vy)<0.005):vy=0
i've been searching thru this channel trying to learn how to one line stuff
but yeah, not going well
type = lambda w: [y := 0, vy := 0.42, [[print("tick n°", i, "| Y speed:", vy, "| Y position:", y), y := y + vy, vy := (vy - 0.08) * 0.98 if abs(vy) >= 0.005 else 0] for i in range(130)]]
(y:=0,vy:=.42,lc:=locals(),[(print("tick n°",i,"| Y speed:",lc['vy'],"| Y position:",lc['y']),[[[]for lc['vy'] in [0]]if abs(lc['vy'])<5e-3 else None for lc['y'],lc['vy'] in[(y+vy,(vy-0.08)*0.98)]])for i in range(130)])and None
``` does this work
it's only a SyntaxWarning in 3.11+
wait actually?
Thats way more complicated than i expected it to be
that does not work as you forgot to take into account that (old_vy - 0.08) * 0.98 is supposed to be the vy in abs(vy) >= 0.005
oh yea
do @wheat river's solution ```py
type = lambda w:[y:=0,vy:=0.42,[[print("tick n°",i,"| Y speed:",vy,"| Y position:",y),y:=y+vy,vy:=(0 if abs(vy:=(vy-0.08)*0.98)<0.005 else vy)]for i in range(w)]]and None
discard the resulting unneeded list
u can't assign vars with = in a list comp
so u have to use the walrus operator, i.e :=
*in an expression
yea
what the f
welcome to estoric python
!e
fizzshit = lambda n: [x:=n%3,y:=n%5,n%15,'fizzbuzz'[0 if not x else 4: 4 if y else 8]][-1] or n
for i in range(1, 100):
print(fizzshit(i))
@wheat river :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 2
003 | fizz
004 | 4
005 | buzz
006 | fizz
007 | 7
008 | 8
009 | fizz
010 | buzz
011 | 11
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/dizomugibi.txt?noredirect
!e
fizzshit = lambda l: [[x := n % 3, y := n % 5, n % 15, 'fizzbuzz'[0 if not x else 4: 4 if y else 8]][-1] or n for n in range(1,l)]
print(*fizzshit(100),sep='\n')
@wheat river :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 2
003 | fizz
004 | 4
005 | buzz
006 | fizz
007 | 7
008 | 8
009 | fizz
010 | buzz
011 | 11
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/zexizemayu.txt?noredirect
fizzshit = lambda l: [[x:=n%3,y:=n%5,n%15,'fizzbuzz'[4 if x else 0: 4 if y else 8]][-1] or n for n in range(1,l)]
how can i use or instead of if-else
fizzshit = lambda l: [[x:=[0,4][bool(n%3)],y:=[8,4][bool(n%5)],n%15,'fizzbuzz'[x:y]][-1] or n for n in range(1,l)]
how is this longer than if else 😔
fizzshit = lambda l: [[x:=[0,4][0<(n%3)],y:=[8,4][0<(n%5)],n%15,'fizzbuzz'[x:y]][-1] or n for n in range(1,l)]
u can make it 3 chars shorter
by removing spaces
Not sure if golfing is your goal here
.argtypes isnt 100% required, but otherwise ctypes will attempt to guess converters (and that can fail on some builds)
also if you have a C function that returns a specific type (ie a pyobject or a pointer to a struct) you can set .restype=whatever_c_type
!e ```py
fizzshit=lambda l:[[x:=(0<n%3)*4,y:=8-(0<n%5)*4,n%15,'fizzbuzz'[x:y]][-1]or n for n in range(1,l)]
print(*fizzshit(100),sep='\n')
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 2
003 | fizz
004 | 4
005 | buzz
006 | fizz
007 | 7
008 | 8
009 | fizz
010 | buzz
011 | 11
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/vaxibivoba.txt?noredirect
@wheat river made 12 characters shorter
oh wait we don't need the majority of the code
!e ```py
fizzshit=lambda l:[['fizzbuzz'[(0<n%3)*4:8-(0<n%5)*4]][-1]or n for n in range(1,l)]
print(*fizzshit(100),sep='\n')
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 2
003 | fizz
004 | 4
005 | buzz
006 | fizz
007 | 7
008 | 8
009 | fizz
010 | buzz
011 | 11
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ezuqucaquk.txt?noredirect
made 27 characters shorter
15 characters shorter from the last thing i did
Oh damn, sick
Thanks 👍
fizzshit=lambda l:['fizzbuzz'[(0<n%3)*4:8-(0<n%5)*4]or n for n in range(1,l)]
``` we don't need the second list anymore
Cool
!e
import __future__
flags = ["foo", "single", __future__.CO_FUTURE_BARRY_AS_BDFL]
exec(compile(
'print(f"{1 <> 0=}")',
*flags
))```
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
1 <> 0=True
What does the * do in print(*fizzshit(100))?
its for unpacking an iterable
so in case of
print(*[1, 2, 3])
it would look like
print(1, 2, 3)
it like fills the args when u do it inside a function
u can use ** to do the same but for kwargs
Ooh
Thats super cool
Good for golfing
I don't have to use for loop to print my list
star unpacking is useful for all sorts of golfing
for example, [*iterable] is shorter than list(iterable)
oh no, poor goto
goto should still work, will just need some slight modifications
heres a puzzle. pkgutils.iter_modules generates tuples (..., str, bool). i need to make 2 sets of these strs corresponding to their bool
so group by -1st element, map by the -2nd element in each bucket?
3 lines and 142 characters? PFFFFFF
[print("Fizz"*(i%3==0)+"Buzz"*(i%5==0)or i)for i in range(1,101)]
i got 1 line 65 characters
for py [ (_, 'a', True), (_, 'b', False), (_, 'c', False), (_, 'd', True), ] output should be {'a', 'd'}, {'b', 'c'}
66 if you include the newline that editors add at the end
anyone wanna show me some python code golfing moments?
🥺
Interesting, this is a syntax error in my xonsh shell
The more you know ¯_(ツ)_/¯
No, it works fine in python, just interesting that the )or is a syntax error in Xonsh, it is lateral to python
hm
xonsh wont tolerate my code golfing antics
any fellow code golfers who want to share golfed code?
i would be very happy
for i in range(1,101):print("Fizz"*(i%3==0)+"Buzz"*(i%5==0)or i)
One char shorter xD
yooooo
niceeeee
You can go down to 59, but that is beyond me
the ==0s are redundant though
or am i tripping
the first step is to reduce to
i=1;while i<100:print("Fizz"*(i%3==0)+"Buzz"*(i%5==0)or i);i+=1
!e
for i in range(1,6):print("Fizz"*(i%3)+"Buzz"*(i%5==0)or i)
its to check if its divisible by 3 or 5
@primal idol :white_check_mark: Your eval job has completed with return code 0.
001 | Fizz
002 | FizzFizz
003 | 3
004 | Fizz
005 | FizzFizzBuzz
of course you can also turn ==0 to <1
good idea
Isnt that is a syntax error?
for i in range(100):print(i%3//2*'Fizz'+i%5//4*'Buzz'or-~i)
wait what the fuck?
why does -~ add 1
my brain hurts
~ reverses all bits
for ints its the same as (-x) - 1
then invert it again with -
ohhhh damn
hm
why does it subtract 1 tho
im confused
eh
it just works i guess
for i in range(100):print('FizzBuzz'[i%~2&4:12&8+i%~4]or i)
!e
print(*('FizzBuzz'[i%~2&4:12&8+i%~4]or i for i in range(1,101)),sep='\n')
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 2
003 | Fizz
004 | 4
005 | Buzz
006 | Fizz
007 | 7
008 | 8
009 | Fizz
010 | Buzz
011 | 11
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ihurisefig.txt?noredirect
does eval work for everyone here?
generates a random, non intersecting path
damn
what font is that, why is it so clean
text on windows is ugly af
Noto Mono
nice
Ubuntu mono as a 2ndary
here's a super inefficent integration function lol
integrate = λ(sum(λ(λt(λ(f(x)*dx)(x=x*dx))(Δ[int(a/dx):int(b/dx)]),f=x,dx=y,a=z,b=w)()))
whats λ?
i see
λt is for map
Δ[a:b:c] is for range
bro, your avatar is epic .
I'll post a sin here.
https://paste.pythondiscord.com/suroyeheru.py
19 lines of code to make the parens around await request() optional.
@chain_coro
async def request():
await asyncio.sleep(1)
return "hello"
async def test_chained_async():
# normally, (await request()).upper()
assert await request() == "hello"
assert await request().upper() == "HELLO"
assert await request().upper()[0] == "H"
assert await request().upper()[:2] == "HE"
assert await request().upper()[::-1].lower() == "olleh"
ok cool
https://paste.pythondiscord.com/kizoxelaja a few more lines of code to make it more performant (untested)
I actually did update it a bit.
https://paste.pythondiscord.com/fokivirova.py
You can chain as many sync or async methods/attrs as you like, then await it at the end.
I also made a decorator to help with __await__()
def async_await(func):
@functools.wraps(func)
def decorator(*args, **kwargs):
return (yield from func(*args, **kwargs).__await__())
return decorator
what about adding support for nested awaits await (await asyncio.sleep(0, result=asyncio.sleep(10)))?
out of scope
this is just fluent async
Posted originally in #async-and-concurrency btw
Hello everyone! 🌻
Hello.
hey
Hi
Im still busy with my python eso project lmao https://github.com/TechnoTanuki
ima list common things and list golfed solutions under it
if not condition:
if 1-condition
#------
if condition:
variable=value1
else:
variable=value2
variable=[value1,value2][condition]
#------
if condition:
print("Bigger Bungus Better Person")
print("Bigger Bungus Better Person"*condition) #will print a newline if the condition isnt true
#------
if condition1 or condition2:
if condition1|condition2: #may not work in some cases
#------
if condition1 or condition2:
if condition1or condition2: #will only work if the character before the OR is a ", ', a number, or any other thing like ( or [
oh yeah heres some more
var1=1
var2=1
var3=1
var1=var2=var3=1
#------
var1="Risk"
var2="of"
var3="Rain"
var4=2
var5="is"
var6="a"
var7="good"
var8="game"
var1,var2,var3,var4,var5,var6,var7,var8="Risk","of","Rain",2,"is","a","good","game"
#------
var1="a"
var2="b"
var3="c"
var4="d"
var5="e"
var1,var2,var3,var4,var5="abcde"
True,False
1,0
#---
[1,2][condition],[2,1][condition]
1+condition,2-condition
#---
(list_element1,list_element2,...],b)[1]
[list_element1,list_element2,...]and b # b is a variable that contains a list
[list_element1,list_element2,...]*0+b # works for tuple-tuple as well
#---
def a(*a,**k):return a,k
a=lambda*a,**k:(a,k)
#---
a.__setitem__(0,a1)or a.__setitem__(1,a2)or a.__setitem__(2,a3)
a.__setitem__(slice(0,3),[a1,a2,a3]) # also works with __getitem__
#---
bool(x%y),bool(y%x)
x%y>0,0<y%x
#---
n/100000000,10000.0
n*1e-8,1e4
n/1e8,1e4
more golfing tips
code golfing in python is cracked
like theres so many techniques
i just shrunk a 3500 character perfectly readable and commented python file
into a 560 character mess with more spaghetti than an italian diner
>>> λ = lambda *a,**k:a,k
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'k' is not defined
ehh???
oh i need parens
lmao
Thanks @humble rune @quartz wave ! So many cool techniques
👍
thanks xD
some better
if not condition:
if 1-condition
if ~condition
#------
if condition:
print("Bigger Bungus Better Person")
print("Bigger Bungus Better Person"*condition) #will print a newline if the condition isnt true
condition and print("Bigger Bungus Better Person") #wont print a newline if the condition isnt true but longer
#------
if condition1 or condition2:
if condition1or condition2: #will only work if the character before the OR is a ", ', a number, or any other thing like ( or [
if condition1+condition2:
if ~condition:
``` only works if `condition` is `False`/`0` or `-1`
oh yeah ur correct my mistake ~-condition shud work, but welp it doesn't reduce the characters
like print for example
Does anyone miss postfix await from Rust and how it lets you chain methods nicely? You can easily have it in Python:
!e
#* snip *#
async def main():
sleeper = Sleeper()
(sleeper
.sleep(1)[await ing]
.sleep(2)[await ing]
.sleep(0.5)[await ing]
)
asyncio.run(main())
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 | Slept for 1s
002 | Slept for 2s
003 | Slept for 0.5s
Full code: https://paste.pythondiscord.com/ehesibuvus
Hmm, is it possible to instead @hook this functionality to the type of coroutines?
well, not all awaitables are coroutines
ah
github copilot knows whatsup
*#esoteric-python intensifies*
Hey @wheat river!
It looks like you tried to attach file type(s) that we do not allow (.md). 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.
I've been trying to read your name as "shnusaitinaveasooliiskiamee" for more than I'd like to admit
that's also how i would read it
but others have innaccurate greek letter nicknames that are supposed to be read like their latin lookalikes so 🤷
actually i think that has disappeared
!e
from re import compile
code = """
def func(var1, var2):
return var1 + var2
"""
DEF_TO_LAMBDA_RE = compile(r'def (.*)\((.*)\)')
RETURN_VALUE_RE = compile(r'return (.*)')
def to_lambda(code):
signature = DEF_TO_LAMBDA_RE.findall(code)
return_value = RETURN_VALUE_RE.findall(code)
signature = [i[0] if len(i.split())==1else ','.join(x[0] for x in i.split()) for j in signature for i in j]
return_value = [''.join(x[0] for x in i.split()) for i in return_value]
return '{}=lambda {}:{}'.format(*signature, *return_value)
print(to_lambda(code))
code-golfer v1
@wheat river :white_check_mark: Your eval job has completed with return code 0.
f=lambda v,v:v+v
hmm you need to fix that
!e
from re import compile
code = """
def func(var1, var2):
return var1 + var2
"""
DEF_TO_LAMBDA_RE = compile(r'def (.*)\((.*)\)')
RETURN_VALUE_RE = compile(r'return (.*)')
def to_lambda(code):
signature = DEF_TO_LAMBDA_RE.findall(code)
return_value = RETURN_VALUE_RE.findall(code)
signature = [i[0] if len(i.split())==1else ','.join([t:=[],[t.append(x[0]) if x[0] not in t else t.append(f'{x[0]}{t.count(x[0])}') for x in i.split()]][0]) for j in signature for i in j]
return_value = [''.join([t:=[],[t.append(x[0]) if x[0] not in t else t.append(f'{x[0]}{t.count(x[0])}') for x in i.split()]][0]) for i in return_value]
return '{}=lambda {}:{}'.format(*signature, *return_value)
print(to_lambda(code))
@wheat river :white_check_mark: Your eval job has completed with return code 0.
f=lambda v,v1:v+v1
nah this doesn't work either
!e
from re import compile
code = """
def func(var1, var2, var3, var4):
return var1 + var2 + var3 + var4
"""
DEF_TO_LAMBDA_RE = compile(r'def (.*)\((.*)\)')
RETURN_VALUE_RE = compile(r'return (.*)')
def to_lambda(code):
signature = DEF_TO_LAMBDA_RE.findall(code)
return_value = RETURN_VALUE_RE.findall(code)
signature = [i[0] if len(i.split())==1else ','.join(x[0]+x[-1] for x in i.replace(' ','').split(',')) for j in signature for i in j]
return_value = [''.join(x[0]+x[-1] if len(x)>1 else x[0] for x in i.split()) for i in return_value]
return '{}=lambda {}:{}'.format(*signature, *return_value)
print(to_lambda(code))
@wheat river :white_check_mark: Your eval job has completed with return code 0.
f=lambda v1,v2,v3,v4:v1+v2+v3+v4
i absolutly LOVED the pipe oparator in elixir |>
This take the return a function and puts it as first argument of the next function
this(is(kinda(bad("right"))))
to
this("is")
|> kinda
|> cool
|> right
how would i go about impletmenting this into python
regex :v
how??
!e
f1=lambda *a:a
f2=lambda *a:a
f3=lambda *a:a
string = """\
f1 |> f2 |> f3 |> 4
"""
def constructor(code: str):
code = map(lambda x: x.strip(), code.split('|>'))
code = ''.join(f'({i}' for i in code)
code += ')' * code.count('(')
code = 'print' + code
eval(code)
constructor(string)
@wheat river :white_check_mark: Your eval job has completed with return code 0.
(((4,),),)
@vestal vector
(Ape noises)
def XOR(t,k,o=""):
for c in t:
for l in k:
c=chr(ord(c)^ord(l))
o+=c
return o
any golfers wanna help me?
(without changing definition name)
i mean, why not just use ast
import ast
from ast import FunctionDef, Assign, Name, Store, Lambda, fix_missing_locations
code = """
def function(a, b):
c = a**b
return c
"""
class RewriteFunctions(ast.NodeTransformer):
def visit_FunctionDef(self, node: FunctionDef) -> Assign:
return Assign(
targets=[Name(id=node.name, ctx=Store())],
value=Lambda(
args=node.args,
body=node.body[0].value
)
)
tree = ast.parse(code)
tree = fix_missing_locations(RewriteFunctions().visit(tree))
print(ast.unparse(tree))
XOR=lambda t,k,o='':[o:=o+chr(ord(c)^ord(l))for c in t for l in k][-1]
👀 never uses ast b4
you are using the broken one
neither have i, just decided to try it out kek
i fixed a thing that made my program break
>>> XOR=lambda t,k,o='':[o:=o+chr(ord(c)^ord(l))for c in t for l in k][-1]
>>> XOR("TEST","BEST")
'\x16\x11\x07\x00\x07\x00\x16\x11\x11\x16\x00\x07\x16\x11\x07\x00'
>>> XOR('\x16\x11\x07\x00\x07\x00\x16\x11\x11\x16\x00\x07\x16\x11\x07\x00',"BEST")
'TSEBSTBEEBTSBESTEBTSBESTTSEBSTBESTBETSEBBESTEBTSTSEBSTBEEBTSBEST'
we get this output with it
since you golfed the broken one
XOR=lambda t,k:"".join(chr(ord(c)^ord(l)) for c,l in zip(t,k)) probably
it outputs bytes instead of chars sadly
what
what do you want it to output-
a string?
yeah idk how you get that-
gonna try working on and see how it goes kek
does this belong here?
print((lambda decimals: bytes(decimals).decode())((lambda binary: [int(byte, 2) for byte in list(binary)])((lambda text: ([bin(ord(i)).replace('b', '') for i in str(text)]))("".join(map(lambda i: i, (i for i in (lambda string: [i for i in str(string)])('Hello world!'))))))))```
print hello world
ew ungolfed code!
print("Hello world!")
golfed your code!(joke)
#include<stdio.h>
#define The only language
int main(){prinft("hi");}
🤢
get that heretic garbage out of here
that wouldnt even work you typed prinft("hi");
True lang
defmodule Hello
def main do
IO.putline "hi"
end
end
🤢🤢🤢🤢🤢🤢🤢🤢
not chad
cringe
you use languages other than python
you cheated on python
eff you dude, python cheated on me before i cheated
why is the interpreter written in c
just why
it should be pure python all the way down
XOR=lambda t,k,o='':[o:=o+chr(ord(c)^ord(l))for c in t for l in k][-1][1::5]
!e
def XOR(t,k,o=""):
for c in t:
for l in k:
c=chr(ord(c)^ord(l))
o+=c
return o
print([ord(i) for i in XOR('TEST', 'BYTES')])
XOR=lambda t,k,o='':[o:=o+chr(ord(c)^ord(l))for c in t for l in k][-1][1::5]
print([ord(i) for i in XOR('TEST', 'BYTES')])
@wheat river :white_check_mark: Your eval job has completed with return code 0.
001 | [13, 28, 10, 13]
002 | [13, 28, 10, 13]
poggers
this is next level golfing
idk how you guys use list stuff tho
list formatting starts my brain on the path towards a padded cell
ah i just pprinted [o:=o+chr(ord(c)^ord(l))for c in t for l in k] and analyzed the output
true lang: ```brainfuck
++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
Witaj świecie!
^ true lang
No, more like, Python should be like English: https://www.zazzle.com/english_doesnt_borrow_from_other_languages_it_t_shirt-235501771001317548
I'm not cheating on python, I'm carrying on the good work...
!e ```py
from ast import *
from itertools import product
code = """
def function(bb, aa):
return (bb + aa) * 8
"""
names=([*'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ']
+ [*map(''.join, product('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'))])
class RewriteExpression(NodeTransformer):
def init(self, namespace: dict):
self.namespace = namespace
def visit_Name(self, node: Name) -> Name:
return Name(self.namespace.get(node.id, node.id), ctx=node.ctx)
class RewriteFunctions(NodeTransformer):
def visit_FunctionDef(self, node: FunctionDef) -> Assign:
node_arguments = node.args
posonlyargs = []
args = []
kwonlyargs = []
d = {}
pargs, nargs, kargs = node_arguments.posonlyargs, node_arguments.args, node_arguments.kwonlyargs
for i in range(j := len(pargs)):
d[pargs[i].arg] = names[i]
posonlyargs.append(arg(arg=names[i]))
minus = j
for j in range(minus, (i := len(nargs))):
d[nargs[j-minus].arg] = names[j]
args.append(arg(arg=names[j]))
minus = i
for i in range(minus, len(kargs)):
d[kargs[i-minus].arg] = names[i]
kwonlyargs.append(arg(arg=names[i]))
return Assign(
targets=[Name(id=node.name, ctx=Store())],
value=Lambda(
args=arguments(
posonlyargs=posonlyargs,
args=args,
kwonlyargs=kwonlyargs,
kw_defaults=node_arguments.kw_defaults,
defaults=node_arguments.defaults
),
body=fix_missing_locations(RewriteExpression(d).visit(node.body[0].value))
)
)
tree = parse(code)
tree = fix_missing_locations(RewriteFunctions().visit(tree))
print(unparse(tree))
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
function = lambda a, b: (a + b) * 8
thanks @pastel sparrow for the node transformer idea
remembering when i made a 20k character line to just print hello world
!e How would y'all golf root finding? Here's what I tried for Newton-Raphson:
root=lambda f,x=1,k=1e-9:r if-k<(r:=x-f(x)*k/(f(x+k)-f(x)))-x<k else root(f,r)
E.g.:
print(root(lambda x:x*x-169))
@prisma coral :white_check_mark: Your eval job has completed with return code 0.
13.0
TIL you can separate codeblocks by text and it will still register as one for the !e command
!e py exec(len("dbgPFtLzdIbeayKQVOFdZUJhsqAJSBglrwZxpfICYDVlGEeHRTGxdFzJYMCCSWIYZllTtlifMyJuJMVhtrjbWmUKrwscnzaMCqambZHYbbPkvEty")+len("OUePAWaqwIIHRwRetbfqKfOZAQTshWsyJvPIfZiNvESMntGrqGxJpVgCSqeAbtpAxUHQyPSrxnZzyJWgXXppZLbVUcZhvfsORyshMqrYsJiWKVNGPs")+len("NwfgkUZZIZtXZNyWEKgRlLWuPNROzyoHeTILPxVwEYxtvHasSOBBlQqdfbJBfazgEoALGVeTckUSBBrFywktLahjBIKhLYXbNrfSPtkbp")+len("tJRofAhHoHyQCDcDkAAoPQihrwClcDlAWMShJLqnajBvfdOfTdLgcTVrAwGYGOvEvcOrIDgGXvNSvBTzUgjoBpGcHSrTMkZXDNUZQALpRkCckC")+len("WlgmYchSASPqRAVXVgLWMIWalyDUGmktQgthGvpsxqEjzZEJBWGXWJkupMHJwvIqOESWEAtQroOahqEuqhnXfFEiCSEXjRUFBWnWDETWxpdtDWaSMPML")+len("ckpsCywKDpDYTmhdDwOjpTUlxxEOXAygQMUOmXbF")+len("OHPtUqRFibajrAJsTGsLqhdioPSqMvVHfSRQKAw")+len("mKLnbJeNOlOzgsSXwPQIPiLFmAuOrzsdjmIrpnGVrHcImhBdqhBnlsrObDvzwPeKuxjgiDHA")+len("pENoMCZotrzeVRmsJvSmxPhkYbBASoWyqUQjgxgUTZGptGWDvFrSSyYHEzpKrXjyNPyfuTmXChVLGMeCCeDCGkVKlTXjaGTfFFNhB")+len("nBWTTkaZvgTsYxXcosyFYRNdbGnzfUCEGIAjxPwcyGoAtHrmktZMYvfPlCDskkivjqvKfmlwSyggncHAWmBjBeULFueGRMjTFWOMrjlNoorT")+len("gefBklAClbeFkXdPQORdiGqwAHnxhklPPdhvhSNPsiIWlMlovNvnYpwMoZSwPbEOvUBkwqoTtYCwAJPFLdGZFGhfJlYNMPECowIvroCIcFaV")+len("mBwVnipdmcdEubnmKFgDuRnozisCSejSAlMRLNlMavkuPcBpgHRgJnobgXYSNaQwAADEJkkjeKGNqsUFeAMZNYKmYdkEWIVyfgIQgNDaYNwkefS")+len("eAIzbBNoBSOurGkcpNDsCvpTrwYNhylX")+len("CjufWRLcTMuuxciwkQNOZAPlOmqduSeJmhHopYenBvFRUUJGQePvAdYlBPBNDOAJXyYFJKXtoywDgJbKctQxJqO")+len("GImLsFiOrSiXIhuEEmkRRAqbreUICAEpERabbfHhfPjhnRXabSorciwMPNfWPPcGnrPeTvjXsFASAgKQUbpEEYkIPOymEddKBNmjJOakaglvnxP")+len("oYgieeDiAWgeNpqFbrTxYqSFFIgOiTIXfzeZcZViFcEZEjufQRtnfPzyYzNQBsKmyZzXgQaWWcUBdLXHQEUvmvSzVAwDTAzNZslVeOwQVklbVHHULF")+len("ADdGtadudVRvseeTRuRIZoflPZudvSvgUEhVIbStGxrEmVETaSMmZjKnevdEgmNUFcrwKqwUxORjJClmInPdiQSKtDEoDXYkAkKfwLiJPsgd")+len("gkhyBMEIZVoypWSeiinJwVhOunbWIpHTffmfCdfWNAbSLHoRKJqLskLjZLaZVkHJvVkmfMrVCcDfttCFqOtfJwDfyDpWmAicpgeY")+len("rifTgPsXqcPuROFveRmnjbpqYPNKoWBbf")+len("widUAtOZdVXWLXgeCPleDobLJFfunWHqdsfSDMLON"))
@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 | TypeError: exec() arg 1 must be a string, bytes or code object
!e py print(str(len("wPWrbOZTxCYabxeVkutKBOBoCnHubCDAqvlXZHaRhGhrzSYRuczSnysIndATRfWjMIRDBfHFDbDhOwUajTbrgtQRAvSSruwWMhKAFjTEXAIvetPa")+len("fKvWqfvkdhdaYNPtnXIdoCCpYFRIYUrGvRDlhcRHpOPzTgzfyozsenApohqtAtKkcsIpYrDdwCllrYSmzGccbFtxYgWDKDdKiLrUsmeOgmeiiGenUI")+len("JBkQOfEmrhbQwQahRNjnpGnBcQwUhBykKOkoUHzAXnfdWWsnGnkMYjfsmfbvvSoBAgxTkyeYdxCKbFYlMEvFqzRYAQGIzNujsfKHdFlVh")+len("NNIGnkNAmWKoXNUxGJlDmrttbmbUFOrNdauAVUypVhWcKHzWXuJNHGcmUbafiCsOPzHuVIphlJwUAmoHDRkoxEXHNGWjzpQoermUVxsxJFmepG")+len("PMkyahhCfYZlGXiLNZwZxxnBPTmSdkOJaowOMUZOpfVpXHytggtXRuqYqwtbQdmamhVtOfFVHHWtxfEHWQYCpLBwCVUcJjXbJgKuZneVKafCoFbGsZWZ")+len("ozjpmaioJwARQgNQjTjkdYUGbaRmfHXHPcNKaqxB")+len("AwXMBeSmUtsLAmZhdBlZziPRaHWureluDqXbmDb")+len("hHsXXvisxpOPAZphmeppAfRHUSAaKfNUNiqVtNwHbYmLkvceXRPpkDPjOXCJwWHZLPEOhwrS")+len("IteIZZtmRnyoaxbKbeIlFNXevYjXtvGmxUlIPvyPoxkVtrMXdTRVtOgSznfuGIrPLglyJScBThxtqqKsLFGTaxHCInBcGuxBZKwxT")+len("cZZrPMnWomRXotQdwENkqSZKJtLWVyQDAvbMdURgNesnJDyyvCfIDoWvhqvmDvDsyXwiOTvtwlNtAyWpGwLDTyMamSTpmuvuJZgAcgRwiZdX")+len("WeZlWVBVKmGLwFmJDIbJMPkHQnLHMANWgSQVTFKqQVDOVinaMPAQDDMhIbIGtympqaouQtXWllZlzuUZqeXQXtXHvOKKTApXSvSmiSTQxPpz")+len("HgMEbmSVPRUghEvoWBWeKguxPKuTIjUbFSghBzZyIYfwnttzePtCmDodlAwuGcYSMryWBuuCUsoCodoCVoxSuogpgMdzOuuosAXJKDMCXCTcyXl")+len("gBwCaVdvdUzmTuheBnaUaIwAmpKvbzfk")+len("DPOuVJiKJJBCpLnCmoQbjvNYdCbhdUYKHgfzVlTBHCMZuxmxKqOHghPmuSiwxjTpeCNSnfZZaGIqFCNTurkwxwZ")+len("suCZQHVqcrDuWqEuFllVwXZQirVicLFOvwAcLkjhmYacJUlMPlFEBduocZAvTkODXfuCjXFnBCVyjOGTtaxXsPndoeIcXgJCYzIygSsclPqaLTO")+len("KIMnWaFbruBGOaMvNSCmeCsbxtDbGhSUHUjztXKwSxfSDPNOhKIRpqFxeGfzENMAYPsJEXZAkMEiZvbstOpcgDviGDPYYgUyDXHhNHcODkwNzMfzcH")+len("NFxfbQbciEEjYtxxnrvbFMdkwaqMvhKXmuWLQvQaFUYUUokBNorvZOYFOxqyKjEaOJIaKZGqSFhEaxpjtoXzVTfpRMxTbcymlWazVMbinexY")+len("vgbtnngstPbBWdsqbwwEmGiUqrTwzshxgOjABRUTdlEIEwPcnKkYxrxBAVmkPjSIEhOWMibvWpiAXFbYpqQCYOPycbnsuaeaNmVk")+len("FqadgzbNrleqEZChJEtQXoNPBBOKeLFNT")+len("AYWBCmXiEWDKOAVwmSSPTaTuwxRcYugMvoPBVfKsY")))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
1762
I hate this
i could make it better but dont want to
looks like base64 at first
it just takes a normal string and turns each letter into bytes then creates a randomized string with that amount of letters (the byte number) and does len() to turn it back to bytes
try: open('obfuscated.py','x')
except: pass
code = "print('Hello World!')"
import string
import random
import codecs
print('exec(str(', end='')
for letter in bytes(code,'utf-8'):
line = ''.join([random.choice(string.ascii_letters) for _ in range(letter)])
#print(f'len("{line}")+', end='')
print(f"codecs.decode(len('{line}').to_bytes(1, byteorder='big'))+", end='')
print('""))', end='')```
here the code its really simple
ignore the top part
its NOT a good obfuscation method to protect your code, its just funny to look at
doesn't this do exactly the same thing as what i did?
!e ```py
import ast
from ast import FunctionDef, Assign, Name, Store, Lambda, fix_missing_locations
code = """
def function(bb, aa):
return (bb + aa) * 8
"""
class RewriteFunctions(ast.NodeTransformer):
def visit_FunctionDef(self, node: FunctionDef) -> Assign:
return Assign(
targets=[Name(id=node.name, ctx=Store())],
value=Lambda(
args=node.args,
body=node.body[0].value
)
)
tree = ast.parse(code)
tree = fix_missing_locations(RewriteFunctions().visit(tree))
print(ast.unparse(tree))
@pastel sparrow :white_check_mark: Your eval job has completed with return code 0.
function = lambda bb, aa: (bb + aa) * 8
ah, just realised you shortened the variable names
Adding slowly some docs to my pure python graphics eso lib https://github.com/TechnoTanuki/Python_BMP building things ground up is fun
someone should rewrite pillow or something but its code bowled
My library can do some stuff pillow can lmao like resize, crop, brightness adj, gamma correct, add text, lines , circles etc
Pure python with some eso byte array manipulations in memory CPU only
'''def horitransformincircregion(bmp,x,y,r,trans): def flip24(): bmp[s1:e1-2:k],bmp[s2:e2-2:k],bmp[s1+1:e1-1:k],bmp[s2+1:e2-1:k],bmp[s1+2:e1:k],bmp[s2+2:e2:k]=bmp[s2:e2-2:k],bmp[s1:e1-2:k],bmp[s2+1:e2-1:k],bmp[s1+1:e1-1:k],bmp[s2+2:e2:k],bmp[s1+2:e1:k] def flip8(): bmp[s1:e1:k],bmp[s2:e2:k]=bmp[s2:e2:k],bmp[s1:e1:k] def mirror24R(): bmp[s1:e1-2:k],bmp[s1+1:e1-1:k],bmp[s1+2:e1:k]=bmp[s2:e2-2:k],bmp[s2+1:e2-1:k],bmp[s2+2:e2:k] def mirror8R(): bmp[s1:e1:k]=bmp[s2:e2:k] def mirror24L(): bmp[s2:e2-2:k],bmp[s2+1:e2-1:k],bmp[s2+2:e2:k]=bmp[s1:e1-2:k],bmp[s1+1:e1-1:k],bmp[s1+2:e1:k] def mirror8L(): bmp[s2:e2:k]=bmp[s1:e1:k] bits,c=bmp[bmpcolorbits],getcomputeBMPoffsetwithheaderfunc(bmp) if trans=='L': if bits==24: f=mirror24L elif bits==8: f=mirror8L elif trans=='R': if bits==24: f=mirror24R elif bits==8: f=mirror8R elif trans=='F': if bits==24: f=flip24 elif bits==8: f=flip8 for v in itercirclepartvertlineedge(r): x1,x2=mirror(x,v[0]) y1,y2=mirror(y,v[1]) k=getxcharcount(bmp) s1,e1,s2,e2=c(bmp,x1,y2),c(bmp,x1,y1)+k,c(bmp,x2,y2),c(bmp,x2,y1)+k f():'''
Eso byte array manip from library using python slice op lmao
Goddamn
https://paste.pythondiscord.com/vanukagaba.py function-to-lambda v5
def function(bb, aa):
return bb + f"+ 3 {'and this'}{123}" + aa
``` gets unparsed into ```py
function = lambda a, b: a + '+ 3 and this123' + b
damn, i need to learn some ast
https://paste.pythondiscord.com/busowumewu.py function-to-lambda v6
def function(bb, aa):
return [bb for bb in aa] + [x for x in [1, 2, 3, 4]]
``` gets unparsed into ```py
function = lambda a, b: [*b] + [1, 2, 3, 4]
https://paste.pythondiscord.com/axuxavehok function-to-lambda v7 py def function(bb, aa): return ([bb for bb in aa] + [x for x in [1, 2, 3, 4]] + [1,2,3,*(4,5,6)] + [*{'a': 3, 'b': 4}], [bb for bb in aa] + [x for x in [1, 2, 3, 4]] + [1,2,3,*(4,5,6)] + [*{'a': 3, 'b': 4}] and {7, 4, 9, 9, 8}) gets unparsed into ```py
function = lambda a, b: ([*b, 1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 'a', 'b'], {7, 4, 9, 8})
i did not expect it would go this far
thanks again @pastel sparrow for the headstart
wow
you can rearrange a little and get -2 chars:
root=lambda f,x=1,k=1e-9:(-k<(r:=x-f(x)*k/(f(x+k)-f(x)))-x<k)*r or root(f,r)
it isnt true in general
iter(aa) can have side-effects
Maybe there's some background thread whose behavior heavily depends on the execution speed of this function 🤔
wait what side-effects
it calls aa.__iter__
you could theoretically pass an object that mutates itself when __iter__ is called
Even in the example, if you'd used fishhook and modified list iter you wouldn't get the same result from your new lambda
Code analysis should not have to assume builtin immutable types are mutable, so that's a little moot.
Hey,
I once asked what and None meant in this code:
type=lambda w:[y:=0,vy:=.42,[[print("tick n°",i,"| Y speed:",vy,"| Y position:",y),y:=y+vy,vy:=(0if abs(vy:=(vy-.08)*.98)<.005 else vy)]for i in range(w)]]and None
and someone told me:
discard the resulting unneeded list
What does that mean?
why I have to do this?
it's so that the function return None instead of a junk list (that's only used to sequence operations)
!e
type=lambda w:[y:=0,vy:=.42,[[print("tick n°",i,"| Y speed:",vy,"| Y position:",y),y:=y+vy,vy:=(0if abs(vy:=(vy-.08)*.98)<.005 else vy)]for i in range(w)]]
print(type(3))
without and None
@wheat river :white_check_mark: Your eval job has completed with return code 0.
001 | tick n° 0 | Y speed: 0.42 | Y position: 0
002 | tick n° 1 | Y speed: 0.33319999999999994 | Y position: 0.42
003 | tick n° 2 | Y speed: 0.2481359999999999 | Y position: 0.7531999999999999
004 | [0, 0.42, [[None, 0.42, 0.33319999999999994], [None, 0.7531999999999999, 0.2481359999999999], [None, 1.0013359999999998, 0.16477327999999988]]]
!e
type=lambda w:[y:=0,vy:=.42,[[print("tick n°",i,"| Y speed:",vy,"| Y position:",y),y:=y+vy,vy:=(0if abs(vy:=(vy-.08)*.98)<.005 else vy)]for i in range(w)]]and None
print(type(3))
with and nOne
@wheat river :white_check_mark: Your eval job has completed with return code 0.
001 | tick n° 0 | Y speed: 0.42 | Y position: 0
002 | tick n° 1 | Y speed: 0.33319999999999994 | Y position: 0.42
003 | tick n° 2 | Y speed: 0.2481359999999999 | Y position: 0.7531999999999999
004 | None
so i'm pretty sure you're referring to [bb for bb in aa]?
oh wait i just realized a bug in HasChanging
hi i'm know in python i'm take some basic thing about list and tuple but my not full understand the my cod i want create list have three index in each index have tuple with tow index like this [('a','b'),('b','c'),('c','d')] the first index in tuple have tow char or the length context when have like this [('~a','a'),('ab','b'),('bc',' c')] can any one help my ? The sample out put the my code
def getNGrams(wordlist, n):
ngrams = []
padded_tokens = "~"*(n) + wordlist
t = tuple(wordlist)
for i in range(3):
t = tuple(padded_tokens[i:i+n])
ngrams.append(t)
return ngrams
Just i need to specific index 0 in tuple to take one or tow or any number of char depending on ngram
Can anyone help me 🙏🏻
https://paste.pythondiscord.com/vihupicoxu.py function-to-lambda v8 py def function(bb, aa): return ([bb for bb in aa] + [x for x in [1, 2, 3, 4]] + [1,2,3,*(4,5,6)] + [*{'a': 3, 'b': 4}], [x for x in [1, 2, 3, 4]] + [1,2,3,*(4,5,6)] + [*{'a': 3, 'b': 4}] and {7, 4, 9, 9, 8}, [bb for bb in aa] and {7, 7, 5}) now turns into ```py
function = lambda a, b: ([*b, 1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 'a', 'b'], {7, 4, 9, 8}, [*b] and {7, 5})
i think you went to the wrong channel
either go to #python-discussion or see how to get help in #❓|how-to-get-help
l=[int(x)for x in sorted(input().split())]
print(sum(l)/(len(l))+l[len(l)//2]if len(l)%2 else(l[len(l)//2]+l[len(l)//2+1])/2)
can someone make this shorter (finds mean and median, iinput is string ex "1 3 2")
what are the braces for
l=[*map(int,sorted(input().split()))]
print(sum(l)/n+l[n//2]if(n:=len(l))%2else l[n:=n//2]+l[n+1]/2)
``` i think this would work
@fleet bridge is this ok now
https://paste.pythondiscord.com/azimamokeb.py function-to-lambda v9 py def function(bb, aa): return ([bb for bb in aa] + [x for x in [1, 2, 3, 4]] + [1,2,3,*(4,5,6)] + [*{'a': 3, 'b': 4}], [x for x in [1, 2, 3, 4]] + [1,2,3,*(4,5,6)] + [*{'a': 3, 'b': 4}] and {7, 4, 9, 9, 8}, [bb for bb in aa] and {7, 7, 5}, [int(x) for x in input()], [*[y for x in [range(10)]*5 for y in x]]) gets turned into ```py
function = lambda a, b: ([*b, 1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 'a', 'b'], {7, 4, 9, 8}, [*b] and {7, 5}, [*map(int, input())], [y for x in [range(10)] * 5 for y in x])
the map() trick is only possible if use_map=True
so by default the golfer class assumes map is assigned to and will not use it
https://paste.pythondiscord.com/ejosapemej.py function-to-lambda v1.0 (pretty major update) py def function(bb, aa): return ([bb for bb in aa] + [x for x in [1, 2, 3, 4]] + [1,2,3,*(4,5,6)] + [*{'a': 3, 'b': 4}], [x for x in [1, 2, 3, 4]] + [1,2,3,*(4,5,6)] + [*{'a': 3, 'b': 4}] and {7, 4, 9, 9, 8}, [bb for bb in aa] and {7, 7, 5}, [int(x) for x in input()], [*[y for x in [range(10)]*5 for y in x]], '7'if (bb+aa)*8>2**(bb+aa) else '4') turns into ```py
function=lambda a,b:([*b,1,2,3,4,1,2,3,4,5,6,'a','b'],{7,4,9,8},[*b]and{7,5},[*map(int,input())],[y for x in[range(10)]5 for y in x],'7'if(a+b)8>2(a+b)else'4')
so yeah now it disables spaces whenever it can
didn't remove spaces for this part ```py
[y for x in[range(10)]*5 for y in x]
^
have we maxed out yet or should we do more
function=lambda a,b:([*b, *range(1,7),'a','b'],{7,4,9,8},[*b]and{7,5},[*map(int,input())],[y for x in[range(10)]*5 for y in x],'7'if(a+b)*8>2**(a+b)else'4')
that should work right?
nope
For the last part I might suggest
...('7','4')[(a+b)*8>2**(a+b)]
It's more exotic.
Less pythonic tho
(I love playing with implicit casts from any type to bool)
hmm i can implement that
for the sake of side effects i can't do that
https://paste.pythondiscord.com/ovucejosol.py function-to-lambda v1.1 py def function(bb, aa): return ('7'if (bb+aa)*8>2**(bb+aa) else '4', bb if [1, 2, 3] else aa) turns into ```py
function=lambda a,b:('7'if(a+b)8>2*(a+b)else'4',a)
:0
For the sake of making and example, that turns into:
function=lambda a,b:(('4','7')[(a+b)*8>2**(a+b)],a)
gfg exaplains it pretty good: https://www.geeksforgeeks.org/ternary-operator-in-python/
Basically, you have a tuple of two elements ('4','7'). You know you can access the '4' by doing ('4','7')[0], and same with seven, right? ('4','7')[1]
Then, you can do this: ('4','7')[my_condition], why? Well, indexes are ints, when you cast a bool to an int, you get: false -> 0, and likewise: true -> 1.
For instance, imagine my_condition = true, then ('4','7')[my_condition] -> ('4','7')[true] -> ('4','7')[1] -> '7'
i know that
but for the sake of side effects i won't do that
Ah, I see
for example the left side and the right side can be a call
Oh, okay, okay. Then fair enough :P
https://paste.pythondiscord.com/akiluzaqoz.py function-to-lambda v1.2 py def function(bb, aa): return (bb(c, d, *bb, *aa, **l, **k, g=4, **{'y': 7, 'x' f'l{bb}': 5}), [*map(str, [*range(10)])]) now turns into ```py
function=lambda a,b:(a(c,d,*a,*b,**l,k,g=4,y=7,{f'xl{a}':5}),[*map(str,range(10))])
while making this update i discovered the possibility of name collisions
any ⛳ enthusiasts wanna help me?
def xor(t, k):
nt,nk=[],[]
for i in t:nt.append(ord(i))
for i in k:nk.append(ord(i))
no,l,o=[],-1,""
for i in nt:
l=[-~l,0][l>=len(nk)-1]
no.append(i^nk[l])
for i in no:o+=chr(i)
return o
a=lambda:print(xor(xor("THIS IS TO TEST IF IT WORKS","Python Golfer"),"Python Golfer")=="THIS IS TO TEST IF IT WORKS")
also no i cannot use nt=nk=[] for some reason it dont work
nt,nk=[*map(ord,t)],[*map(ord,k)]
thanks
golfed it a bunch using this new map tech
def xor(t,k):
z,y,x,l=[*map(ord,t)],[*map(ord,k)],[],-1
for i in z:exec("l=[-~l,0][l>=len(y)-1];x.append(i^y[l])")
return "".join([*map(chr,x)])
def xor(t,k):
y,x,l=[*map(ord,k)],[],-1
for i in [*map(ord,t)]:exec("l=[-~l,0][l>=len(y)-1];x.append(i^y[l])")
return "".join([*map(chr,x)])
golfed more
Compressed a little more
def xor(t,k):
y,l=[*map(ord,k)],-1
return"".join(chr(i^y[l:=[-~l,0][l>=len(y)-1]])for i in map(ord,t))
oh you used list oddities
list formating will forever be black magic voodoo to me
What do you mean by list formatting? As in the comprehension expression I used?
yeah lol
ah
xor=lambda t,k:[y:=[*map(ord,k)],l:=-1,"".join(chr(i^y[l:=[-~l,0][l>=len(y)-1]])for i in map(ord,t))][2]
Actually worlds smallest implementation of One-Time Pad algorithm in Python programming language - otp.py
does the same thing
https://paste.pythondiscord.com/fakuziruma.py function-to-lambda v1.3 py def function2(bb, aa): return (bb(a, b, *c, *d, **e, **f, g=4, **{'y': 7, 'x' f'l{bb}': 5}) + aa) turns into ```py
function2=lambda g,h:g(a,b,*c,*d,**e,f,g=4,y=7,{f'xl{g}':5})+h
d = {3:"Fizz", 5:"Buzz", 7:"Fuzz"}
print("\n".join([("".join(o) if o else str(i)) for o,i in [([d[g] for g in d if not i%g],i) for i in range(1,101)]]))
fizzbuzz scalable version in 2 lines
thanks to @viral rose for helping a bit with this btw
not really the most efficient script though since it iterates over every number in the range twice but it's still pretty good
how it works is it makes a list for every number containing all the valid words and then it iterates over all of those outputs again, checking if each one is an empty list and replacing it with the number if it is
this channel just made my brain explode
you can make it a bit shorter :)
d = {3:"Fizz", 5:"Buzz", 7:"Fuzz"}
print(*[''.join(d[k]for k in d.keys()if i%k<1)or i for i in range(1,101)],sep='\n')
ooooooo
i didn't know you could use or in that way in python
if the string is empty, use the integer value
that only works if strs are same length
xor=lambda t,k:"".join(chr(ord(a)^ord(b))for a,b in zip(t,k*len(t)))
you can make it even shorter 😉
d={3:"Fizz",5:"Buzz",7:"Fuzz"}
for i in range(1,101):print(''.join(d[k]for k in d if i%k<1)or i)
What the fuck is this
Lol
then
def encrypt(_0,_1):_2=[list(map(ord,_0)),list(map(ord,_1))];[_2.__setitem__(1,(_2[1][0:len(_2[0])],_2[1]+_2[1][::-1])[len(_2[1])<len(_2[0])])for(_)in range(len(_2[0]))];return __import__("base64").b64encode("".join(map(chr,[_2[0][_]^_2[1][_]for(_)in range(len(_2[0]))])).encode("utf-8"))
https://paste.pythondiscord.com/imewuyiqeb.py function-to-lambda v1.4 py def function2(bb, aa): return (bb(a, b, *c, *d, **e, **f, g=4, **{'y': 7, 'x' f'l{bb}': 5}) + aa, {*()} | {x for x in range(10)} and {x: y for x, y in zip(bb, aa)} | {}, not not [1, 2, 3], not 7) turns into ```py
function2=lambda g,h:(g(a,b,*c,*d,**e,f,g=4,y=7,{f'xl{g}':5})+h,{*range(10)}and{x:y for(x,y)in zip(g,h)},True,False)
OwO
This eso python project has been getting some stars of late so surprised lmao https://github.com/TechnoTanuki/Python_BMP ....not yet done with sample codes for it ... so moar soon
kek i have a 59 char one
for i in range(100):print(i%3//2*'Fizz'+i%5//4*'Buzz'or-~i)
me after violently golfing my code so much i dont know what does what anymore
😎
this is a relatively simple golf
def xor(a,b):
c,d,e=[*map(ord,b)],[],-1
for i in[*map(ord,a)]:exec("e=[-~e,0][e>=len(c)-1];d.append(i^c[e])")
return "".join([*map(chr,d)])
its slightly readable
def xor(a,b,d=[],e=~0):
c=[*map(ord,b)]
for i in[*map(ord,a)]:exec("e=[-~e,0][e>=~-len(c)];d.append(i^c[e])")
return "".join(map(chr,d))
149 chars
def xor(a,b,d=[],e=~0):
c=[*map(ord,b)]
for i in[*map(ord,a)]:e=[-~e,0][e>=~-len(c)];d.append(i^c[e])
return "".join(map(chr,d))
this works apparently?
141 chars
def xor(a,b,d="",e=~0):
c=[*map(ord,b)]
for i in[*map(ord,a)]:e=[-~e,0][e>=~-len(c)];d+=chr(i^c[e])
return d
121
119
any code golfers wanna help me out a bit?
Remove space before for
did not know that works
It looks like it should work
!e ```py
xor=lambda a,b:"".join(chr(ord(c)^ord(d))for c,d in zip(a,b))
print(xor("test", "longerstring"))
@pastel sparrow :white_check_mark: Your eval job has completed with return code 0.
001 |
002 |
4 bytes fair enough
any communities/channels that combine paranormal/supernatural with coding. such as summoning spirits via code etc.? I heard of it a while ago but can't find it now.
@rare jay
getattr(__import__('ghost'), 'CreateGhostInstance'))('Pydis-ghost')
maybe they do
if it isnt bait im gonna lose my mind
what if there is a secret cult which spawns ghosts with python scripts
world(x,y).append(entity["ghost"])
Hey @humble rune!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
while True 😳😳😳
💀
does anyone have obfuscation that protects source code efficiently?? i dont want that exec stuff because you can just replace it with print to get the code
Ultimately futile. But you can try PyArmor, or just distributing .pyc files
pyarmor is vulnerable
def fn_to_lambda(fn: function) -> lambda:
return lambda *args, **kwargs: fn(*args, **kwargs)
ultimately futile
yea, pyc would work anyways
you could add some boilerplate
update it doesn't crash anymore in 3.11.0a7
uncompyle6 says hello
where uncompyle6 in python 3.9+
why does this print 7?
https://paste.gg/p/anonymous/cbb22243f6844f9cb7f0cb7eab5e93ea
it’s supposed to count and print all ints from x to y
!e (lambda x,y: print((chr(((int(None is None)+int(None is None)*(int(True is True)+int(False is False))))*(int(True)+int(True))+int(True)+int(True)).join(map(str, range(x,y+int(True is True)))))))(0,7)
@sick hound :white_check_mark: Your eval job has completed with return code 0.
01234567
!e ```py
print(int(True)+int(True)+int(True)+int(False)+int(True)+int(False)+int(True)+int(True)+int(False)+int(True)+int(True)+int(True)+int(True)+int(True)+int(True)+int(False)+int(True)+int(True)+int(True)+int(True)+int(True)+int(True)+int(False)+int(True)+int(True)+int(False)+int(True)+int(False)+int(True)+int(True)+int(True)+int(True)+int(False)+int(True)+int(False)+int(True)+int(False)+int(True)+int(False)+int(True)+int(True)+int(False)+int(True)+int(True)+int(True)+int(False)+int(True)+int(True)+int(False)+int(True)+int(True)+int(True)+int(True)+int(False)+int(True)+int(False)+int(True)+int(True)+int(True)+int(False)+int(True)+int(True)+int(True)+int(True)+int(False)+int(True)+int(True)+int(False)+int(True)+int(False)+int(True)+int(False)+int(True)+int(False)+int(True)+int(True)+int(False)+int(True)+int(False)+int(True)+int(True)+int(True)+int(True)+int(True)+int(True)+int(False)+int(True)+int(False)+int(True)+int(False)+int(True)+int(False)+int(True)+int(True)+int(True)+int(False)+int(True)+int(False)+int(True))```
@sick hound :white_check_mark: Your eval job has completed with return code 0.
69
Lmao
what is this channel
btw you can add bools directly because bool is a subclass of int
True + False == 1
!e ```py
print(True + False)
@sick hound :white_check_mark: Your eval job has completed with return code 0.
1
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 0
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 0
003 | 1
004 | 1
005 | 0
006 | 1
!e ```py
print(int(bool([None]))+int(bool([None]))+int(bool([None]))+int(bool([None]))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool([None]))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool([None]))+int(bool([None]))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool([None]))+int(bool([None]))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool([None]))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool([None]))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool([None]))+int(bool([None]))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool([None]))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool([None]))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool(None))+int(bool([None]))+int(bool([None]))+int(bool([None]))+int(bool([None])))```
@sick hound :white_check_mark: Your eval job has completed with return code 0.
69
nice
nice
nice
import random, os
os.system('cls' if os.name =='nt' else 'clear')
string = bytes("Hello World!", 'utf-8')
number = ''
for i in string:
for _ in range(i):
if _ == (i - 1): plus = ''
else: plus = '+'
number += 'int(bool([None]))'+plus
if random.randint(1,2) == 2:
number += 'int(bool(None))'+plus
print(f"print(({number}).to_bytes(1, byteorder='big'));", end='')
number = ''``` can someone have a look at this code for me, its supposed to make golfed strings but i get invalid syntax
where do you get invalid syntax
are you in 3.6+
you cant print strings larger than ~16k
any alternative?
s = '...'
while s:
print(s[:100], end='')
s = s[100:]
get rid of the if _ == (i - 1): plus = '' else: thingy
i need that
or its gonna put + at the end where i dont need it
and its too hard to manually remove on every single letter
then at the end of the second for-loop just do number = number.removesuffix('+')
plus = '+' * (_ == i - 1)
no just do plus = '+'
and ^
it should work now
!e
string = b'\1\2\3'
print(*map(lambda i: f'print(({"+".join(["int(bool([None]))"]*i)}).to_bytes(1, byteorder="big"))', string),sep='\n')
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
001 | print((int(bool([None]))).to_bytes(1, byteorder="big"))
002 | print((int(bool([None]))+int(bool([None]))).to_bytes(1, byteorder="big"))
003 | print((int(bool([None]))+int(bool([None]))+int(bool([None]))).to_bytes(1, byteorder="big"))
!e
string = b'\0'
print(*map(lambda i: f'print(({"+".join(["int(bool([None]))"]*i) or 0}).to_bytes(1, byteorder="big"))', string),sep='\n')
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
print(().to_bytes(1, byteorder="big"))
@sick hound do ```py
import random, os
os.system('cls' if os.name =='nt' else 'clear')
string = bytes("Hello World!", 'utf-8')
for i in string:
number = []
for _ in range(i):
number.append('int(bool([None]))+')
if random.randint(1,2) == 2:
number.append('int(bool(None))+')
print(f"print(({''.join(number)[:-1]}).to_bytes(1, byteorder='big'));", end='')
ok ill try it
import random, os
os.system('cls' if os.name =='nt' else 'clear')
string = bytes("Hello World!", 'utf-8')
for i in string:
number = []
for _ in range(i):
number.append('int(bool([None]))+')
if random.randint(1,2) == 2:
number.append('int(bool(None))+')
print(f"print(({''.join(number)[:-1]}).to_bytes(1, byteorder='big').decode(), end='');")``` final result, thanks @quartz wave @fleet bridge for helping
Hey @sick hound!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
code
!eval <code>
Can also use: e
*Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*
bruhh i cant send the code its too long
is 30k char long enough? or does it need to be longer
It isn't exactly mine, but if it helps you, that’s good.
just golf your code so hard nobody can read it 😎
golf yo code jesus
my take on the string obfuscator: ```py
from random import choice
plainstring = "Hello World!"
cipherstring = '"".join(map(chr,'
def f():
return choice([True, False])
def g():
return choice([">", "<", "^"])
chars = list(map(ord, plainstring))
cipherchars = []
for c in chars:
intermediate = []
while c != 0:
res = f"(({f()}{g()}{f()}{g()}{f()}{g()}{f()}){g()}{f()})"
c -= eval(res)
intermediate.append(res)
cipherchars.append("+".join(intermediate))
cipherstring = cipherstring + str(cipherchars).replace("'", "") + "))"
you'll never get the same output for the same input
the thing is, how tf are you supposed to read that then
nvm i just realized u can do eval() on cipherstring lol
now thats epic
you're not?
that's the point
yeah just run it like normal python code
yeah i just did
Im commenting my code samples rn for pure python 3D rendering
Run that script it should generate that bitmap from scratch using pure python
(You need my eso library ofc to do that lmao)
!e ```py
def cast(v, t1, t2, bufsize=tuple.itemsize):
conv = memoryview(bytearray(bufsize))
conv.cast(t1)[0] = v
return conv.cast(t2)[0]
load_addr = lambda addr: type(m:=lambda n:lambda:n)(
(M:=m.code).replace(
co_code=b'\x88'+M.co_code[1:]
),{}
)(cast(addr, 'q', 'd'))()
print(load_addr(id(1)))
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
1
!e ```py
BYTES_HEADER = bytes.basicsize - 1
PTR_SIZE = tuple.itemsize
ENDIAN = ['big','little'][memoryview(b'\1\0').cast('h')[0]&0xff]
def cast(v, t1, t2, bufsize=tuple.itemsize):
conv = memoryview(bytearray(bufsize))
conv.cast(t1)[0] = v
return conv.cast(t2)[0]
load_addr = lambda addr: type(m:=lambda n:lambda:n)(
(M:=m.code).replace(
co_code=b'\x88'+M.co_code[1:]
),{}
)(cast(addr, 'q', 'd'))()
memory_backing = bytes(PTR_SIZE)
+ id(bytearray).to_bytes(PTR_SIZE, ENDIAN)
+ bytes([255] * (PTR_SIZE - 1) + [127])
+ bytes(PTR_SIZE * 4)
memory = memoryview(load_addr(id(memory_backing) + BYTES_HEADER))
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 Return(val):
frame = getframe(1)
offset = id(frame.f_code.co_code) + bytes.basicsize + frame.f_lasti - 1
memory[offset + 2: offset + 4] = bytes((83, 0))
return val
def test(x):
Return(x + 1)
print(test(1))
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
2
🤔
@quartz wave questions?
this somehow doesn't work on windows 3.10
where does it crash?
3.11 makes sense cause of all the frame and bytecode changes
3.11 broke creating custom code objects
it broke them entirely?
class j():
class o():
class e():
class m():
class a():
class m():
def a():
print("joemama")
j.o.e.m.a.m.a()
what do we got using this speed?
optimizing stuff in python 3.11 decided to CACHE some of my vital instructions in something i tried to make
why's greyblue in esoteric python
he's been here for a long time now
i thought he doesn't like cursed stuff
well he's been here for a long time now
akward
why would you think that ?
because your personality
hello, what's the topic of this specific channel?
Weird stuff we do with Python
I have one big weird project pure python image processing, 2D and 3D graphics that outputs to Bitmap format
Outputs that ...pure python lmao
Stack named tuples 🗿
Hmm, has anyone toyed around with cracking the PRNG in the random module?
I heard you only need a few hundred random() calls to completely figure out the seed.
did it once or twice during ctfs, though always with a library
Not exactly for sourcecode , but PjOrion obfuscates bytecode. It is designed for python 2 and mods for the game world of tanks but it works for python 3 and etc. Might not support the newest versions though.
I did crack one a long time ago ...lmao it was in a commercial product
uh oh that's not good xD
Mua hahahaha
someone's done it
Imagine having ≠ in your command line's font
Damn, even an arrow pointing left
actually it seems fine when viewed raw (b'r' is POP_JUMP_FORWARD_IF_FALSE) ```py
(c_char * 62).from_address(id(c.code) + type(c.code).basicsize)[18]
b'r'
``` if youdisthe code, it'll showCACHEat position 18
https://github.com/python/cpython/blob/main/Objects/codeobject.c#L1157-L1175 this seems to be the root of the problem
PyObject *
_PyCode_GetCode(PyCodeObject *co)
{
PyObject *code = PyBytes_FromStringAndSize(NULL, _PyCode_NBYTES(co));
if (code == NULL) {
return NULL;
}
_Py_CODEUNIT *instructions = (_Py_CODEUNIT *)PyBytes_AS_STRING(code);
for (int i = 0; i < Py_SIZE(co); i++) {
_Py_CODEUNIT instruction = _PyCode_CODE(co)[i];
int opcode = _PyOpcode_Deopt[_Py_OPCODE(instruction)];
int caches = _PyOpcode_Caches[opcode];
instructions[i] = _Py_MAKECODEUNIT(opcode, _Py_OPARG(instruction));
while (caches--) {
instructions[++i] = _Py_MAKECODEUNIT(CACHE, 0);
}
}
return code;
}
orb
from random import choice
import string
alpha=list(string.ascii_letters+string.digits+string.punctuation+" ")
alpha.remove("\\")
alpha.remove("\'")
alpha.remove("\"")
string=input("String to obfuscate: ")
number=int(input("Split number: "))
output=""
for i in range(len(string)):
output+=string[i]
for i in range(number):
output+=choice(alpha)
print(f"\"\"\"{output}\"\"\"[::{number+1}]")
"IFc`Bc8ON0IfU1A1+: N*hu_+);]+Ma1RXmqaXy/I9= <j_d#&Ck{7dDH,f+)WkwX$af$uYVdS{:F_CO9F:l,JpF$we]Qqwge|BB37KoT{GEd(Pm9h)cKp@%P2a[8: H91r]:5Uq`nXw~r&)au(fD]Vl&8$HYO#CJG wXO~B[gZfZ+2.lC0;R-Y:_.fN-#rxJ2S~|_Ab2G{e%CMN>oTa&C>!T~)#iwh(%Z=0G(zJ@e l/jMWMcMNp+;IaC?No~4$=&G.$t]xyE9f=QnT]Lt$A6zZnyK -=zLtsO }aTJJWqnW!>&X1o:}MyJoUgb,@~yrV|F !57@/*6M[wMw(z=V7y6K/GV}Iy^ASI?dmT8orJH8eHHd,HSxw~n?gu3Zh5MR,WnNcD5z#)NruZOULc&#ZrqJP2R5` fO0%}B}A4NN9^`_~rPkM#;^TYEkVF@NaQ.uCBm:tTwsLVLcFIX1>h!qR#EJ[009GoT 4~cu E{y_icwp F]|d00gqT}E>A{|<GvC>V.se2}r5%_VGeq%xeDaObLkaoj(k7-%^`u?:khTk(gln9-Su}:/IS%4xopd-lufN-lSW6-oLcFg-O/eFH$O2JQDBrdD8Eiz!dz3_yS9:F9GI02EvkR [2(Y{B/xU?N=oU(8ceWx@Z|Mx44*NZ3Kvrwp-n%lm|Qq)jS..I?(miIo;bo/0_Rf Oa|&sIcw?gPK9f)}y>((<Ibx UQ,8nu6-CV! (Dy1fsc&&x[t&XI6uhpYEU#tVy$_.~l~]0<sX4x:]yr!O@)RNm$LVpZylFfl%/?HK|j=CNXVO5d6Oe?(9#3r.]0@5Q+l1>y!MY1|/t/@0{3wprI&U"[::18]
put this in your python interpreter
trust me its legit
print([(a:=getattr(__import__('re'), 'sub')(r'\s\'"\\','',getattr(__import__('string'),'printable'))),s:=input('string: '),n:=int(input('num: ')),o:=''.join(i+''.join(getattr(__import__('random'),'choices')(a,k=n))for i in s),print(o),print(o[::n+1])]and None)
i just got banned from a python server i was in
for saying to run this in their console
😔
😔
onto your PC
Joke's on you, I ran it on my phone
quicker way to do .replace("[", "").replace("]", "")? (stdlib only)
shorter way*
I guess I'll just say the context then
I have a list, and I need to turn it into a string and remove the brackets it has
!e py x = [1,2,3] print(repr(str(x)[1:-1]))
yo
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
'1, 2, 3'
assuming you don't have nested lists that'll work
u can use regex for nested lists
!e
print("[1, 2, [3, 4], 5]".translate(str.maketrans("","","[]")))```
@runic mirage :white_check_mark: Your eval job has completed with return code 0.
1, 2, 3, 4, 5
what happens if I do?
from random import choice as z
import string
alpha=string.ascii_letters+string.digits+string.punctuation+" "
alpha,string,number,output=list(alpha.replace("\\","").replace("\'","").replace("\"","")),input("String to obfuscate: "),int(input("Split number: ")),""
for i in range(len(string)):
output+=string[i]
for i in range(number):output+=z(alpha)
print(f"\"{output}\"[::{number+1}]")
!e ```py
print("[1,2, [3, 4], 5]".translate({91:0,93:0}))
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
�1,2, �3, 4�, 5�
^ just removes the str.maketrans call
!e
f=lambda l:", ".join(f(x) if isinstance(x,list) else repr(x) for x in l)
print("[1, 2, [3, 4], 5]")
use choices instead of choice
Huh
!e ```py
print("".join(c for c in "[1,2,3,[4]]"if c not in "[]"))
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
1,2,3,4
f=lambda l:", ".join(f(x)if isinstance(x,list)else repr(x)for x in l)
print("[1, 2, [3, 4], 5]")
!
code
!e
code
@humble rune :white_check_mark: Your eval job has completed with return code 0.
[1, 2, [3, 4], 5]
why?
!e
print(', '.join(getattr(__import__('re'), 'findall')('\d', "[1,2,3,[4]]")))
@wheat river :white_check_mark: Your eval job has completed with return code 0.
1, 2, 3, 4
a = choices(iterable, k=n)
================================================
a = []
for i in range(n):
a.append(choice(iterable))
oh nice
!e ```py
import fishhook
@fishhook.hook(list)
def repr(self):
return fishhook.orig(self)[1:-1]
print([1,2,3, [4, 5]])```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
1, 2, 3, 4, 5
this is cool
There’s strings in it too and I have to remove the ’ chars
What are the translate codes for that?
you can do ord(char)
!e ```py
print("".join(c for c in "[1,2,3,[4], 'abc']"if c not in "[]'"))
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
1,2,3,4, abc
!e py print("[1,2, [3, 4], 5, 'abc']".translate({91:0,93:0,39:0}))
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
�1,2, �3, 4�, 5, �abc��
!e
@getattr(fh := __import__('fishhook'), 'hook')(list)
def __repr__(self): return fh.orig(self)[1:-1]
@getattr(fh, 'hook')(str)
def __repr__(self): return fh.orig(self)[1:-1]
print([1, 2, 3, [4, 5], 'a'])
@wheat river :white_check_mark: Your eval job has completed with return code 0.
1, 2, 3, 4, 5, a
Hey @final cedar!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
https://paste.pythondiscord.com/wesuducale Hey everyone, I am trying to run this so I can explain what it is and how it works on my podcast. Can someone please tell me how to fix this error? ```py
note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed
× Encountered error while generating package metadata.
╰─> See above for output.
I've seen that error many times (namely while trying to install the esoterrible module)
I don't know how to fix it
!e py x = [1,2,3] print(str(x)[1:-1]))
@cyan nova :x: Your eval job has completed with return code 1.
001 | File "<string>", line 2
002 | print(str(x)[1:-1]))
003 | ^
004 | SyntaxError: unmatched ')'
@cyan nova :x: Your eval job has completed with return code 1.
001 | File "<string>", line 2
002 | print(repr(str(x)[1:-1])
003 | ^
004 | SyntaxError: '(' was never closed
@sick hound :white_check_mark: Your eval job has completed with return code 0.
1, 2, 3
@cyan nova
Thanks mate
@sick hound :white_check_mark: Your eval job has completed with return code 0.
1, 2, 3, 6, 7, 9
I was checking code from up here, I don’t remember who wrote it prolly @rugged sparrow
all good,
He wrote
!e py x = [1,2,3] print(repr(str(x)[1:-1]))
And I was wondering what difference it made to the code
Okay
it just adds ' '
Ooh, did not realize that
!e
x = [1,2,3]
print(repr(str(x)[1:-1]))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
'1, 2, 3'
See
Aha
👍
quickest way to test if variable is a list stdlib only?
v = [1, 2, 3] # variable
print(type(v) == list)
```???
you can use isinstance too
oh right
v = [1, 2, 3] # variable
print(isinstance(v, list))
Technically you could do py print(type([]) is list)
[].__class__ is list
I need to print out comma-separated contents of a list that can take two possible forms. Either ['label', value] or ['label', [values]]. So, for instance, I would need to output label, value or label, val1, val2, ..., valn. I think this is possible with one statement but my previous attempts have run into typing issues. Any ideas? (stdlib only)
nvm, got it
just asking, are there any plans to revive those? https://github.com/python-discord/esoteric-python-challenges/
(sounds like a fun thing and too bad im late to the party)
:incoming_envelope: :ok_hand: applied mute to @mellow tapir until <t:1650362875:f> (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
You know about https://codegolf.stackexchange.com?
i know about that but looking at the past challenges it is nowhere near what is going on at codegolf today
and those challenges strictly require least amount of characters, while not only python, what im looking for is exactly esoteric python
Im glad that this channel exists anyway
I didn't know that this website existed!
What a cool place
I'm gonna start sharing stuff here I found installed as .pth files in my dist-packages
these are really little gems of esotericness
credit matplotlib:
import sys, types, os;has_mfs = sys.version_info > (3, 5);p = os.path.join(sys._getframe(1).f_locals['sitedir'], *('mpl_toolkits',));importlib = has_mfs and __import__('importlib.util');has_mfs and __import__('importlib.machinery');m = has_mfs and sys.modules.setdefault('mpl_toolkits', importlib.util.module_from_spec(importlib.machinery.PathFinder.find_spec('mpl_toolkits', [os.path.dirname(p)])));m = m or sys.modules.setdefault('mpl_toolkits', types.ModuleType('mpl_toolkits'));mp = (m or []) and m.__dict__.setdefault('__path__',[]);(p not in mp) and mp.append(p)```
theres a bunch... and they are testing for python 3.5 (???) despite being in a 3.9-specific location
perhaps a way to gain some startup speed 👀
damn
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: call stack is not deep enough
first time seeing this error
That's probably because they are relying on 3.5+ specific behaviour of importlib.util.module_from_spec and importlib.machinery.PathFinder.find_spec
And they want to support multiple Python versions with the same code

!e
import ctypes
x = "hello"
for i, ctypes.c_byte.from_address(id(x) + i).value in zip(range(51, 53), range(112, 0, -79)):...
print(x)
@restive void :white_check_mark: Your eval job has completed with return code 0.
help!
i wanna make my own server specifically for code golfing but i wanna evaluate code for a discord bot
one problem
how do i do that without a script kiddie putting a RAT on my PC
Don't host it on your pc
pog
Cone rendered with pure Python
Source code here https://github.com/TechnoTanuki/Python_BMP/blob/main/Hello_Cone.py
Hello all. I once posted about how our organization is using Nameko in production and someone on the IRC channel pointed out that the green threads implementation has an issue. Was hoping to discuss this further with the intention of identifying the issue and possible solutions. We're opting to move to Go, but I'd like to understand the exact issue and propose solutions to mgmt. Thanks
TIL that any valid assignment target is valid as a for-loop index
@languid hare :white_check_mark: Your eval job has completed with return code 0.
{0: 'H', 1: 'e', 2: 'l', 3: 'l', 4: 'o', 5: '!'}
Eso pure python render and source of platonic solid
Ok
!e print(len(''))
@patent pewter :white_check_mark: Your eval job has completed with return code 0.
10

logo for the code golf server
some cpython core devs are here so you might consider this one "official"
Hey. I am working on a declarative Python parser for binary
structures. here is a quick snippet of current syntax. https://pastebin.com/gK1thUtN
Thoughts?
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.
Interesting. The context manager temporarily patches __build_class__, I assume?
d,i={},0
for d[i]in"Hello!":i+=1
print(d)
yes
exactly what it does
Not super satisfied with the template argument specification syntax though
but << is the best looking operator I found
Next thing I wanna do is struct parenting. To extend a struct with another struct, should be fairly easy.
!e
print(dict(enumerate('hello', start=1)))
@wheat river :white_check_mark: Your eval job has completed with return code 0.
{1: 'h', 2: 'e', 3: 'l', 4: 'l', 5: 'o'}
!e ```py
print(dict(enumerate('Hello!')))
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
{0: 'H', 1: 'e', 2: 'l', 3: 'l', 4: 'o', 5: '!'}
@humble rune :white_check_mark: Your eval job has completed with return code 0.
{(2, 'l'), (3, 'l'), (0, 'H'), (1, 'e'), (5, '!'), (4, 'o')}
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
one liner quick sort
!e
from random import choices
qs=lambda a:[l:=[],g:=[],p:=a.pop(len(a)//2),[l.append(i)if i<=p else g.append(i)for i in a],qs(l)+[p]+qs(g)][-1] if len(a)>=1 else a
randlist = choices(range(10), k=10)
print(randlist)
print(qs(randlist))
@wheat river :white_check_mark: Your eval job has completed with return code 0.
001 | [7, 1, 4, 0, 4, 8, 9, 5, 4, 5]
002 | [0, 1, 4, 4, 4, 5, 5, 7, 8, 9]
!e ```py
from random import choices
q=lambda a:a and[l:=[],g:=[],p:=a.pop(len(a)//2),[[l,g][i>p].append(i)for i in a]]*0+q(l)+[p]+q(g)
randlist = choices(range(10), k=10)
print(randlist)
print(q(randlist))
hmm
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | [4, 6, 9, 7, 2, 8, 1, 8, 3, 9]
002 | [1, 2, 3, 4, 6, 7, 8, 8, 9, 9]
!e
make facebook website
@distant briar :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | make facebook website
003 | ^^^^^^^^
004 | SyntaxError: invalid syntax
why not work
!e
(l:='a')*0
print(l)
@wheat river :white_check_mark: Your eval job has completed with return code 0.
a
ah i c
sick
I would use %, because it's already a templating operator
Alternatively, the boring solution is using a method instead of an operator
Oh nice, I like that more
Thanks for the idea
how do i update a print without having to print it again
carriage return escape sequence
I don't know if this counts as esoteric or plain cursed
what language is that?
Kotlin :)
I first looked at it as Python and was trying to figure out what metaclass magic you employed to get this syntax running
I assume this is for interfacing Kotlin to Python
looks okay to me, can't call it cursed

Wait... python semicolons are a thing?
!eval while run := True: print("".join(import("random").choices(import("string").ascii_letters + import("string").digits + import("string").punctuation, k=int((i if (i := input("Password length: ")) and i.isdigit() else(i := 12))))))
@untold sphinx :x: Your eval job has completed with return code 1.
001 | Password length: Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | EOFError: EOF when reading a line
!eval while run := True: print("".join(__import__("random").choices(__import__("string").ascii_letters + __import__("string").digits + __import__("string").punctuation, k=int((i if (i := input("Password length: ")) and i.isdigit() else(i := 12))))))
@untold sphinx :x: Your eval job has completed with return code 1.
001 | Password length: Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | EOFError: EOF when reading a line
aha
!e
q=lambda l:q([x for x in l[1:] if x<=l[0]])+[l[0]]+q([x for x in l if x>l[0]]) if l else []
l = [1, 34, 37, 12, 7.2]
print(q(l))
(taken from Christian Mayer's Python One Liners)
@royal whale :white_check_mark: Your eval job has completed with return code 0.
[1, 7.2, 12, 34, 37]
oh.
Current thread 0x00007fb8696c0740 (most recent call first):
<no Python frame>
``` python hates my code i think lol
@earnest wing I got unlock to be way more stable https://paste.pythondiscord.com/ozaguyader
Ah that's cool
yikes 💀
still admirably esoteric, underappreciated code
or you could use or ...
!e
(lambda : print("hello") or (l := []) or l.append("Hello") or l.append("World") or print(', '.join(l)))()```
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | hello
002 | Hello, World
how did you just cause a fatal error
uhhhhh yes
i literally ran something that did requests
and did Ctrl+C
it threw that
@quartz wave
did you select something before you ctrl+c'd
ok idk probably caused by an unhandled KeyboardInterrupt
Very nice
like what's the full error you encountered
before the Current thread ... stuff there should be a Fatal error message or something
does it abort if there's a KeyboardInterrupt while an exception is pending ?
usually everything aborts when a KeyboardInterrupt happens
like terminate your program completely ?
java will do so if two exceptions are thrown at once , I think
the real cause could be a function returning a non-null value with an unhandled exception
or a function returning a null value with no raised exceptions
oh yeah, that is true
sometimes it tells you that, I'm not sure when it's able to raise a SystemError and when it isn't
I guess the test would be to return 0 from some function with an exception is set
does it help that i had threads
!e well this didn't have the intended effect but I thought it was funny anyway
import ctypes as c
@c.CFUNCTYPE(None, c.c_int, c.c_int)
def callback(a,b):
raise Exception()
c.pythonapi.PyObject_CallFinalizer(callback)```
@rapid sparrow :warning: Your eval job has completed with return code 135 (SIGBUS).
[No output]
for finding the error, maybe not... but for causing it? definitely
it isn't supposed to crash, though
odd..
if you can post your program that would help
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
i'm pretty sure it still says "current thread ..." even when you don't use threads
did anything else print out at all?
uhhh yeah but i didnt copy it
lemme replicate error
or try
doesnt wanna do it
yea
List Type: Full Alphabet
Thread Error (list index out of range)
Thread Error (list index out of range)
Thread Error (list index out of range)
Thread Error (list index out of range)
Thread Error (list index out of range) Thread Error (list index out of range)
Thread Error (list index out of range)
Thread Error (list index out of range)
Thread Error (list index out of range)
Thread Error (list index out of range)
Thread Error (list index out of range)
Thread Error (list index out of range)
[Thread: 0] aaaaa Taken
[Thread: 0] aaaab Taken
[Thread: 0] aaaac Taken```
it do that
idk how to make it work properly
keep pressing ctrl+c on that part
youll eventually get the error
i think
wonder why the KeyboardInterrupt isn't stopping it
it only worked at the end
well at the end i got Unknown Error [404] in the thread and a KeyboardInterrupt error in the REPL
