#esoteric-python

1 messages · Page 146 of 1

humble rune
#

so much code golfing

split salmon
#

@humble rune

humble rune
#

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 😔

rugged sparrow
#

!rules 2

night quarryBOT
rugged sparrow
#

@humble rune that breaks discord TOS

near gust
#

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

earnest wing
#

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

near gust
#

tp_getset or whatever it was

#

specifically changing it to a null pointer

#

or changing the __dict__'s entry in the table

rugged sparrow
#

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)```

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

42
rugged sparrow
near gust
#

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

swift trench
#

i wounder how can such code work...

rugged sparrow
near gust
#

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

swift trench
rugged sparrow
swift trench
#

Impressive!

night quarryBOT
#

Hey @wheat river!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

wheat river
simple plinth
#

help pls

earnest wing
#
@fishhook.hook_cls(object)
class Ingredients:
    ingredients = [...]*2**30
#

that would fix it

simple plinth
dark wharf
next flame
#

this channel is for cursed python

#

Not the best spot to find help

simple plinth
next flame
simple plinth
dark wharf
#

Who did, and did they give a reason?

simple plinth
dark wharf
#

Well that would be dormant ones

next flame
#

it tells you how to use the help channels

slim basalt
#

Hey. i could use some help getting my pygame to work properly

languid hare
#

you're still in esoteric python

vague cairn
#

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 ... 😄

languid hare
#

heh

#

nice way to put it

#

perform

wheat river
#

!e import fishhook

night quarryBOT
#

@wheat river :warning: Your eval job has completed with return code 0.

[No output]
wheat river
#

D:::

#

!e

import fishhook
@fishhook.hook_cls(object)
class Ingredients:
    ingredients = [...]*2**2

print(str.ingredients)
print(int.ingredients)
print(type.ingredients)
night quarryBOT
#

@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]
wheat river
#

owo

primal idol
#

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"
primal idol
#

Ah found it

#

__builtins__=type('', (dict,), {'__missing__': lambda *args: args[1]})(__builtins__.__dict__)

#

x)

finite blaze
#

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

sudden osprey
#

!e deque.rotate for lists:

import random
x = [1, 2, 3, 4, 5]
random.shuffle(x, lambda:0)
print(x)
night quarryBOT
#

@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]
sudden osprey
#

bonus points for deprecation warning?

restive void
finite blaze
wheat river
#
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

short crag
#
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.```
signal herald
#

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.

short crag
#

yeah..

#

thought r+/w+ supported read and write?

signal herald
#

sure, but stdout doesn't.

#

stdout is write-only.

short crag
#

how can I get input then?

signal herald
#

stdin

#

open(0, 'r')

short crag
#

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.
rapid sparrow
#

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

quartz wave
#

shouldn't you do malloc(sizeof(c_int) * 9 + sizeof(c_long) + sizeof(c_char_p))

rapid sparrow
#

oops, probably yeah

#

that far still works 🥳

#
>>> tm                                                                      <__main__.LP_c_int_Array_10 object at 0x5555cc3e40>```
quartz wave
#

also doesn't tm_zone have to have a value or something

rapid sparrow
#

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

#

?

quartz wave
#

or you can create a struct using Structure

rapid sparrow
#

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;```
rapid sparrow
#

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

rapid sparrow
night quarryBOT
#

: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).

rugged sparrow
#

!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)```

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

15 b'GMT'
rugged sparrow
#

@rapid sparrow ^

finite blaze
#

Hey, is there any writeup or something about how to one-line code?

#

Would love to learn it

rapid sparrow
#

so I needed to define .argtypes for it to work?

#

also didn't know byref was a thing

quartz wave
#

!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)

night quarryBOT
#

@quartz wave :white_check_mark: Your eval job has completed with return code 0.

18 b'GMT'
quartz wave
rapid sparrow
#

interesting

finite blaze
#
 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

wheat river
#
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)]]

quartz wave
finite blaze
#

yep it does

#

u are missing one space

quartz wave
wheat river
#

wait actually?

finite blaze
#

oh really?

#

thats so cool

#

i wish i knew it earlier

#

when i was golfing my code

finite blaze
quartz wave
quartz wave
finite blaze
#

yeah, thats looks more readable for me

#

whats this and None used for?

quartz wave
finite blaze
#

i see that you can't do y=0

#

why?

wheat river
#

u can't assign vars with = in a list comp

#

so u have to use the walrus operator, i.e :=

quartz wave
wheat river
#

yea

wheat river
#

welcome to estoric python

wheat river
#

!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))

night quarryBOT
#

@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

wheat river
#

!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')
night quarryBOT
#

@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

wheat river
#
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

wheat river
#
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)]
finite blaze
#

u can make it 3 chars shorter

#

by removing spaces

#

Not sure if golfing is your goal here

rugged sparrow
#

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

quartz wave
#

!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')

night quarryBOT
#

@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

quartz wave
#

@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')

night quarryBOT
#

@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

quartz wave
#

made 27 characters shorter
15 characters shorter from the last thing i did

wheat river
#

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

rapid sparrow
#

!e

import __future__
flags = ["foo", "single", __future__.CO_FUTURE_BARRY_AS_BDFL]

exec(compile(
    'print(f"{1 <> 0=}")',    
    *flags
))```
night quarryBOT
#

@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.

1 <> 0=True
finite blaze
#

What does the * do in print(*fizzshit(100))?

wheat river
#

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

finite blaze
#

Ooh

#

Thats super cool

#

Good for golfing

#

I don't have to use for loop to print my list

earnest wing
#

star unpacking is useful for all sorts of golfing

#

for example, [*iterable] is shorter than list(iterable)

earnest wing
#

oh no, poor goto

finite blaze
#

Gotta start making some notes about golfing

#

Can't remember it all

rugged sparrow
lusty sinew
#

heres a puzzle. pkgutils.iter_modules generates tuples (..., str, bool). i need to make 2 sets of these strs corresponding to their bool

earnest wing
#

so group by -1st element, map by the -2nd element in each bucket?

humble rune
lusty sinew
humble rune
#

anyone wanna show me some python code golfing moments?

#

🥺

primal idol
#

The more you know ¯_(ツ)_/¯

humble rune
#

did you put it in a file then run the file

#

im using python version 3 btw

primal idol
humble rune
#

xonsh wont tolerate my code golfing antics

#

any fellow code golfers who want to share golfed code?

#

i would be very happy

primal idol
#
for i in range(1,101):print("Fizz"*(i%3==0)+"Buzz"*(i%5==0)or i)
#

One char shorter xD

primal idol
#

You can go down to 59, but that is beyond me

pastel sparrow
#

or am i tripping

earnest wing
#

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
primal idol
humble rune
night quarryBOT
#

@primal idol :white_check_mark: Your eval job has completed with return code 0.

001 | Fizz
002 | FizzFizz
003 | 3
004 | Fizz
005 | FizzFizzBuzz
earnest wing
#

of course you can also turn ==0 to <1

humble rune
lusty sinew
#
for i in range(100):print(i%3//2*'Fizz'+i%5//4*'Buzz'or-~i)
humble rune
#

dayum we code golfing today

#

59 fucking chars

#

niceeee

humble rune
#

why does -~ add 1

#

my brain hurts

lusty sinew
#

for ints its the same as (-x) - 1

#

then invert it again with -

earnest wing
#

that should be the optimal

#

at least if I remember the cgcc submission correctly

humble rune
#

hm

#

why does it subtract 1 tho

#

im confused

#

eh

humble rune
#

it just works i guess

wheat river
#
for i in range(100):print('FizzBuzz'[i%~2&4:12&8+i%~4]or i)
pastel sparrow
#

59 chars too damn

#

wait no that doesn't work, it prints 0-99 instead of 1-100

fleet bridge
#

!e

print(*('FizzBuzz'[i%~2&4:12&8+i%~4]or i for i in range(1,101)),sep='\n')
night quarryBOT
#

@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

lusty sinew
#

does eval work for everyone here?

fleet bridge
#

yes

finite blaze
#

Hey, do you have any golfing tips?

#

Making a small note collecting them

west cipher
pastel sparrow
#

damn looks good

#

what does it do

west cipher
pastel sparrow
#

damn

west cipher
wheat river
#

text on windows is ugly af

west cipher
wheat river
#

nice

west cipher
#

Ubuntu mono as a 2ndary

west cipher
#

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)()))
finite blaze
#

whats λ?

west cipher
#

lambda shorthand

#

λ(x**2)(5) = 25

finite blaze
#

i see

west cipher
#

λt is for map
Δ[a:b:c] is for range

sick hound
#

bro, your avatar is epic .

lone sphinx
#

19 lines of code to make the parens around await request() optional.

lone sphinx
#
@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"
quartz wave
lone sphinx
#

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
astral rover
#

what about adding support for nested awaits await (await asyncio.sleep(0, result=asyncio.sleep(10)))?

lone sphinx
#

out of scope

#

this is just fluent async

spark abyss
#

Hello everyone! 🌻

lone sphinx
#

Hello.

sick hound
#

hey

long hamlet
#

Hi

humble rune
# finite blaze Hey, do you have any golfing tips?

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"
quartz wave
#
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

humble rune
#

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

wheat river
#
>>> λ = 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

finite blaze
#

Thanks @humble rune @quartz wave ! So many cool techniques

humble rune
#

👍

lunar moon
# humble rune ima list common things and list golfed solutions under it ```py if not condition...

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:
quartz wave
lunar moon
#

oh yeah ur correct my mistake ~-condition shud work, but welp it doesn't reduce the characters

icy frigate
#

like print for example

finite blaze
#

p=print

#

You mean something like this?

#

Then you can do
p("1")
For example

formal sandal
#

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())
night quarryBOT
#

@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
formal sandal
hard spoke
formal sandal
#

well, not all awaitables are coroutines

hard spoke
#

ah

wheat river
#

github copilot knows whatsup

quartz wave
night quarryBOT
#

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.

formal sandal
quartz wave
#

but others have innaccurate greek letter nicknames that are supposed to be read like their latin lookalikes so 🤷

#

actually i think that has disappeared

wheat river
#

!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

night quarryBOT
#

@wheat river :white_check_mark: Your eval job has completed with return code 0.

f=lambda v,v:v+v
wheat river
#

!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))
night quarryBOT
#

@wheat river :white_check_mark: Your eval job has completed with return code 0.

f=lambda v,v1:v+v1
wheat river
#

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))
night quarryBOT
#

@wheat river :white_check_mark: Your eval job has completed with return code 0.

f=lambda v1,v2,v3,v4:v1+v2+v3+v4
vestal vector
#

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

finite blaze
#

regex :v

vestal vector
#

how??

wheat river
#

!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)
night quarryBOT
#

@wheat river :white_check_mark: Your eval job has completed with return code 0.

(((4,),),)
wheat river
#

@vestal vector

vestal vector
#

ooooo

#

that is awesome

#

never thought of it like that

humble rune
#
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)

pastel sparrow
#
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))
wheat river
wheat river
humble rune
pastel sparrow
humble rune
#

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

pastel sparrow
humble rune
pastel sparrow
#

what

humble rune
#

when i try to do XOR("TEST","BEST")

#

it outputs bytes

pastel sparrow
#

what do you want it to output-

humble rune
#

a string?

pastel sparrow
#

how would you represent a null byte as a string

humble rune
pastel sparrow
#

yeah idk how you get that-

pastel sparrow
unreal echo
#

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!'))))))))```
pastel sparrow
#

yes

#

what does that do

unreal echo
#

print hello world

humble rune
vestal vector
humble rune
#

get that heretic garbage out of here

#

that wouldnt even work you typed prinft("hi");

vestal vector
#

True lang

defmodule Hello
  def main do
    IO.putline "hi"
  end
end
humble rune
#

🤢🤢🤢🤢🤢🤢🤢🤢

vestal vector
humble rune
#

cringe

#

you use languages other than python

#

you cheated on python

vestal vector
#

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

wheat river
#

!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')])
night quarryBOT
#

@wheat river :white_check_mark: Your eval job has completed with return code 0.

001 | [13, 28, 10, 13]
002 | [13, 28, 10, 13]
humble rune
#

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

wheat river
#

ah i just pprinted [o:=o+chr(ord(c)^ord(l))for c in t for l in k] and analyzed the output

pastel sparrow
finite blaze
#

Witaj świecie!
^ true lang

vague cairn
quartz wave
# wheat river 👀 never uses ast b4

!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))

night quarryBOT
#

@quartz wave :white_check_mark: Your eval job has completed with return code 0.

function = lambda a, b: (a + b) * 8
quartz wave
#

thanks @pastel sparrow for the node transformer idea

sick hound
#

remembering when i made a 20k character line to just print hello world

prisma coral
#

!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))
night quarryBOT
#

@prisma coral :white_check_mark: Your eval job has completed with return code 0.

13.0
quartz wave
sick hound
#

!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"))

night quarryBOT
#

@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
sick hound
#

!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")))

night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

1762
sick hound
#

ohh

#

im stupid

sick hound
#

i did it but its too long

shell brook
#

I hate this

sick hound
#

i could make it better but dont want to

sturdy rune
#

looks like base64 at first

sick hound
# sturdy rune 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

pastel sparrow
#

!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))

night quarryBOT
#

@pastel sparrow :white_check_mark: Your eval job has completed with return code 0.

function = lambda bb, aa: (bb + aa) * 8
pastel sparrow
#

ah, just realised you shortened the variable names

long hamlet
sleek sphinx
#

someone should rewrite pillow or something but its code bowled

long hamlet
#

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

quartz wave
#
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
wheat river
#

damn, i need to learn some ast

quartz wave
quartz wave
#

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

wheat river
#

wow

severe canyon
fleet bridge
wispy wedge
#

Maybe there's some background thread whose behavior heavily depends on the execution speed of this function 🤔

finite blaze
#

Anyone here ever tried writing terminal chess

#

and then golfing/one-lineing it?

pastel sparrow
rugged sparrow
#

it calls aa.__iter__

#

you could theoretically pass an object that mutates itself when __iter__ is called

dark wharf
#

Even in the example, if you'd used fishhook and modified list iter you wouldn't get the same result from your new lambda

earnest wing
#

Code analysis should not have to assume builtin immutable types are mutable, so that's a little moot.

finite blaze
#

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?

next flame
wheat river
#

!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

night quarryBOT
#

@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]]]
wheat river
#

!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

night quarryBOT
#

@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
quartz wave
#

oh wait i just realized a bug in HasChanging

sly flume
#

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 🙏🏻

quartz wave
# quartz wave https://paste.pythondiscord.com/axuxavehok function-to-lambda v7 ```py def funct...

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})

quartz wave
thorny tapir
#
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")

thorny tapir
#

oh wait it used to be for f string

#

i removed them unless i'm blind

quartz wave
#
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
quartz wave
#

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

quartz wave
#

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

quartz wave
#

didn't remove spaces for this part ```py
[y for x in[range(10)]*5 for y in x]
^

quartz wave
#

have we maxed out yet or should we do more

finite blaze
#
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

vestal cedar
#

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)

quartz wave
#

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)

wheat river
#

:0

vestal cedar
# quartz wave https://paste.pythondiscord.com/ovucejosol.py function-to-lambda v1.1 ```py def ...

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'

quartz wave
#

but for the sake of side effects i won't do that

vestal cedar
#

Ah, I see

quartz wave
#

for example the left side and the right side can be a call

vestal cedar
#

Oh, okay, okay. Then fair enough :P

quartz wave
#

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))])

quartz wave
humble rune
#

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

wheat river
#
    nt,nk=[*map(ord,t)],[*map(ord,k)]
humble rune
#

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

prisma coral
humble rune
#

list formating will forever be black magic voodoo to me

prisma coral
humble rune
#

yeah lol

prisma coral
humble rune
wheat river
#
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]


sly root
#

does the same thing

quartz wave
lethal cradle
#
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

viral rose
#

this channel just made my brain explode

severe canyon
lethal cradle
#

i didn't know you could use or in that way in python

severe canyon
#

if the string is empty, use the integer value

next flame
#
xor=lambda t,k:"".join(chr(ord(a)^ord(b))for a,b in zip(t,k*len(t)))
next flame
granite flax
#

What the fuck is this

sick hound
sly root
# next flame that only works if strs are same length

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"))
quartz wave
#

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)

wheat river
#

OwO

long hamlet
humble rune
#

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?

pastel sparrow
#

uh

#
xor=lambda a,b:"".join(chr(ord(c)^ord(d))for c,d in zip(a,b))
#

no?

finite blaze
#

Remove space before for

pastel sparrow
#

did not know that works

finite blaze
#

It looks like it should work

pastel sparrow
#

!e ```py
xor=lambda a,b:"".join(chr(ord(c)^ord(d))for c,d in zip(a,b))

print(xor("test", "longerstring"))

night quarryBOT
#

@pastel sparrow :white_check_mark: Your eval job has completed with return code 0.

001 | 
002 | 
pastel sparrow
#

4 bytes fair enough

rare jay
#

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.

humble rune
#

@rare jay

wheat river
humble rune
#

i do believe im being baited

#

people cant really believe this

wheat river
#

maybe they do

humble rune
#

if it isnt bait im gonna lose my mind

wheat river
#

what if there is a secret cult which spawns ghosts with python scripts

humble rune
#

world(x,y).append(entity["ghost"])

night quarryBOT
#

Hey @humble rune!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

humble rune
sick hound
humble rune
#

💀

sick hound
#

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

restive void
carmine sun
#
def fn_to_lambda(fn: function) -> lambda:
    return lambda *args, **kwargs: fn(*args, **kwargs)
restive void
carmine sun
#

you could add some boilerplate

quartz wave
#

update it doesn't crash anymore in 3.11.0a7

next flame
quartz wave
coarse cave
#

it’s supposed to count and print all ints from x to y

sick hound
#

!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)

night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

01234567
sick hound
#

!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))```

night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

69
sick hound
#

might make a string encryptor with this

#

@coarse cave thanks for the idea

primal crag
#

Lmao

dusty inlet
#

what is this channel

runic mirage
night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

1
sick hound
#

cool

#

thatll make it longer

night quarryBOT
#

@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
sick hound
#

!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])))```

night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

69
rich hound
#

nice

stark dirge
#

nice

quartz wave
#

nice

sick hound
#
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
quartz wave
#

are you in 3.6+

sick hound
#

newest version 3.10.4

quartz wave
#

oh

#

hmm

fleet bridge
sick hound
fleet bridge
#
s = '...'
while s:
    print(s[:100], end='')
    s = s[100:]
quartz wave
sick hound
#

or its gonna put + at the end where i dont need it

#

and its too hard to manually remove on every single letter

quartz wave
fleet bridge
#

plus = '+' * (_ == i - 1)

quartz wave
fleet bridge
#

!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')
night quarryBOT
#

@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"))
fleet bridge
#

!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')
night quarryBOT
#

@fleet bridge :white_check_mark: Your eval job has completed with return code 0.

print(().to_bytes(1, byteorder="big"))
quartz wave
#

@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='')
sick hound
#

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
night quarryBOT
#

Hey @sick hound!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

#
Missing required argument

code

#
Command Help

!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!*

sick hound
#

bruhh i cant send the code its too long

#

is 30k char long enough? or does it need to be longer

coarse cave
humble rune
humble rune
pastel sparrow
#

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

umbral prism
#

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

pastel sparrow
#

that's the point

umbral prism
#

i meant

#

deobfuscated one from obfuscated one

pastel sparrow
#

yeah just run it like normal python code

umbral prism
#

yeah i just did

long hamlet
#

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)

quartz wave
#

!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)))

night quarryBOT
#

@quartz wave :white_check_mark: Your eval job has completed with return code 0.

1
quartz wave
#

!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))

night quarryBOT
#

@quartz wave :white_check_mark: Your eval job has completed with return code 0.

2
quartz wave
#

🤔

rugged sparrow
#

@quartz wave questions?

quartz wave
rugged sparrow
#

where does it crash?

quartz wave
#

wait

#

oh it doesn't for 3.11

#

it still works for 3.10

rugged sparrow
#

3.11 makes sense cause of all the frame and bytecode changes

quartz wave
#

3.11 broke creating custom code objects

rugged sparrow
#

it broke them entirely?

rapid sparrow
#

oh yay

#

my fork of unpyc37

#

successfully decompiled a small .pyc file

bronze merlin
#
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?

quartz wave
bronze merlin
#

why's greyblue in esoteric python

quartz wave
bronze merlin
quartz wave
bronze merlin
#

akward

rapid sparrow
bronze merlin
#

because your personality

gentle bluff
#

hello, what's the topic of this specific channel?

long hamlet
#

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

wheat river
earnest wing
#

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.

languid hare
#

did it once or twice during ctfs, though always with a library

magic wraith
long hamlet
jovial monolith
long hamlet
#

Mua hahahaha

jovial monolith
#

someone's done it

cloud fossil
#

Damn, even an arrow pointing left

quartz wave
#
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;
}
humble rune
long hamlet
humble rune
#
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}]")
humble rune
#
"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

wheat river
#
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)
humble rune
#

i just got banned from a python server i was in

humble rune
#

😔

wheat river
#

😔

humble rune
restive void
#

onto your PC

Joke's on you, I ran it on my phone

icy wing
#

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

rugged sparrow
#

!e py x = [1,2,3] print(repr(str(x)[1:-1]))

icy wing
#

yo

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

'1, 2, 3'
rugged sparrow
#

assuming you don't have nested lists that'll work

wheat river
#

u can use regex for nested lists

runic mirage
#

!e

print("[1, 2, [3, 4], 5]".translate(str.maketrans("","","[]")))```
night quarryBOT
#

@runic mirage :white_check_mark: Your eval job has completed with return code 0.

1, 2, 3, 4, 5
icy wing
humble rune
#
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}]")
rugged sparrow
#

!e ```py
print("[1,2, [3, 4], 5]".translate({91:0,93:0}))

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

�1,2, �3, 4�, 5�
rugged sparrow
#

^ just removes the str.maketrans call

humble rune
#

!e
f=lambda l:", ".join(f(x) if isinstance(x,list) else repr(x) for x in l)

print("[1, 2, [3, 4], 5]")

runic mirage
#

Huh

rugged sparrow
#

!e ```py
print("".join(c for c in "[1,2,3,[4]]"if c not in "[]"))

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

1,2,3,4
humble rune
#
f=lambda l:", ".join(f(x)if isinstance(x,list)else repr(x)for x in l)
print("[1, 2, [3, 4], 5]")
#

!

night quarryBOT
#
Missing required argument

code

night quarryBOT
#
Missing required argument

code

#

@humble rune :white_check_mark: Your eval job has completed with return code 0.

[1, 2, [3, 4], 5]
humble rune
runic mirage
#

Is there a built-in filterfalse

#

without itertools

#

Or a negator func

wheat river
#

!e

print(', '.join(getattr(__import__('re'), 'findall')('\d', "[1,2,3,[4]]")))
night quarryBOT
#

@wheat river :white_check_mark: Your eval job has completed with return code 0.

1, 2, 3, 4
wheat river
# humble rune why?
a = choices(iterable, k=n)
================================================
a = []
for i in range(n):
  a.append(choice(iterable))
rugged sparrow
#

!e ```py
import fishhook
@fishhook.hook(list)
def repr(self):
return fishhook.orig(self)[1:-1]

print([1,2,3, [4, 5]])```

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

1, 2, 3, 4, 5
icy wing
#

There’s strings in it too and I have to remove the chars

#

What are the translate codes for that?

runic mirage
#

you can do ord(char)

rugged sparrow
#

!e ```py
print("".join(c for c in "[1,2,3,[4], 'abc']"if c not in "[]'"))

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

1,2,3,4, abc
rugged sparrow
#

!e py print("[1,2, [3, 4], 5, 'abc']".translate({91:0,93:0,39:0}))

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

�1,2, �3, 4�, 5, �abc��
wheat river
#

!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'])
night quarryBOT
#

@wheat river :white_check_mark: Your eval job has completed with return code 0.

1, 2, 3, 4, 5, a
night quarryBOT
#

Hey @final cedar!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

final cedar
#

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.

royal whale
#

I've seen that error many times (namely while trying to install the esoterrible module)

#

I don't know how to fix it

cyan nova
#

!e py x = [1,2,3] print(str(x)[1:-1]))

night quarryBOT
#

@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
#

e

#

!e

x = [1,2,3]
print(str(x)[1:-1])
night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

1, 2, 3
sick hound
#

@cyan nova

cyan nova
sick hound
#

!e

x = [1,2,3,6,7,9]
print(str(x)[1:-1])
night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

1, 2, 3, 6, 7, 9
cyan nova
sick hound
#

all good,

cyan nova
#

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

sick hound
#

yeah it wouldn't be right because of the last )

#

wait nvm

#

repr is just return value

cyan nova
#

Okay

sick hound
#

it just adds ' '

cyan nova
#

Ooh, did not realize that

sick hound
#

!e

x = [1,2,3]
print(repr(str(x)[1:-1]))
night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

'1, 2, 3'
sick hound
#

See

cyan nova
#

Aha

sick hound
#

👍

icy wing
#

quickest way to test if variable is a list stdlib only?

thorny tapir
icy wing
#

I was using is

#

dumb

pastel sparrow
#

you can use isinstance too

thorny tapir
#

oh right

v = [1, 2, 3]  # variable
print(isinstance(v, list))
rugged sparrow
#

Technically you could do py print(type([]) is list)

fleet bridge
#

[].__class__ is list

icy wing
#

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)

icy wing
#

nvm, got it

magic wraith
night quarryBOT
#

: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).

magic wraith
#

i know about that but looking at the past challenges it is nowhere near what is going on at codegolf today

magic wraith
#

Im glad that this channel exists anyway

finite blaze
#

What a cool place

rapid sparrow
#

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 👀

pastel sparrow
#

damn

#
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: call stack is not deep enough

first time seeing this error

prisma coral
#

And they want to support multiple Python versions with the same code

sick hound
restive void
#

!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)
night quarryBOT
#

@restive void :white_check_mark: Your eval job has completed with return code 0.

help!
humble rune
#

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

finite blaze
#

Don't host it on your pc

restive void
humble rune
long hamlet
#

Cone rendered with pure Python

glass crest
#

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

next flame
languid hare
#

indeed

#

!e

d = {}
i = 0
for d[i] in "Hello!":
  i += 1
print(d)
night quarryBOT
#

@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: '!'}
royal whale
#

cool

#

Yeah a code-golfing server would be neat I wish python had an official one

long hamlet
#

Eso pure python render and source of platonic solid

sick hound
#

Ok

patent pewter
#

!e print(len('­­­­­­­­­­'))

night quarryBOT
#

@patent pewter :white_check_mark: Your eval job has completed with return code 0.

10
wheat river
humble rune
#

logo for the code golf server

quartz wave
strong meadow
restive void
humble rune
strong meadow
#

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.

wheat river
#

!e

print(dict(enumerate('hello', start=1)))
night quarryBOT
#

@wheat river :white_check_mark: Your eval job has completed with return code 0.

{1: 'h', 2: 'e', 3: 'l', 4: 'l', 5: 'o'}
quartz wave
#

!e ```py
print(dict(enumerate('Hello!')))

night quarryBOT
#

@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
#

!e

print({(enumerate('Hello!')})
#

!e

print({*enumerate('Hello!')})
night quarryBOT
#

@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')}
crimson plover
#

!ytdl

night quarryBOT
#

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)
wheat river
#

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))
night quarryBOT
#

@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]
quartz wave
#

!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

night quarryBOT
#

@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]
distant briar
#

!e

make facebook website
night quarryBOT
#

@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
distant briar
#

why not work

wheat river
#

!e

(l:='a')*0
print(l)
night quarryBOT
#

@wheat river :white_check_mark: Your eval job has completed with return code 0.

a
wheat river
#

ah i c

restive void
#

Alternatively, the boring solution is using a method instead of an operator

strong meadow
#

Thanks for the idea

sick hound
#

how do i update a print without having to print it again

strong meadow
grave rover
#

I don't know if this counts as esoteric or plain cursed

strong meadow
grave rover
#

Kotlin :)

strong meadow
# grave rover 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

grave rover
silent notch
#

Wait... python semicolons are a thing?

languid hare
#

you can use them to split a statement without using a newline

#

not required though

untold sphinx
#

!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))))))

night quarryBOT
#

@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
untold sphinx
#

!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))))))

night quarryBOT
#

@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
untold sphinx
#

aha

royal whale
# wheat river one liner quick sort

!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)

night quarryBOT
#

@royal whale :white_check_mark: Your eval job has completed with return code 0.

[1, 7.2, 12, 34, 37]
rich hound
#

oh.

Current thread 0x00007fb8696c0740 (most recent call first):
<no Python frame>

``` python hates my code i think lol
rugged sparrow
rapid sparrow
#

still admirably esoteric, underappreciated code

rapid sparrow
#

!e

(lambda : print("hello") or (l := []) or l.append("Hello") or l.append("World") or print(', '.join(l)))()```
night quarryBOT
#

@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.

001 | hello
002 | Hello, World
silent notch
#

whaaaaa

#

t

quartz wave
rich hound
#

uhhhhh yes

#

i literally ran something that did requests

#

and did Ctrl+C

#

it threw that

#

@quartz wave

quartz wave
#

did you select something before you ctrl+c'd

rich hound
#

no

#

its automated

potent jolt
#

advice for a simple input gui? (xcoord, ycoord)

#

oops wrong channel

quartz wave
#

ok idk probably caused by an unhandled KeyboardInterrupt

rich hound
#

uhh

#

i have try/excepts tho

quartz wave
#

before the Current thread ... stuff there should be a Fatal error message or something

rapid sparrow
quartz wave
rapid sparrow
#

like terminate your program completely ?

quartz wave
#

not really

#

python probably just comes out with a KeyboardInterrupt message

rapid sparrow
#

java will do so if two exceptions are thrown at once , I think

quartz wave
#

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

rapid sparrow
#

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

rich hound
#

does it help that i had threads

rapid sparrow
#

!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)```
night quarryBOT
#

@rapid sparrow :warning: Your eval job has completed with return code 135 (SIGBUS).

[No output]
rapid sparrow
rich hound
#

yeah

#

it was threaded

#

so that might be it

rapid sparrow
#

it isn't supposed to crash, though

rich hound
#

odd..

rapid sparrow
#

if you can post your program that would help

rich hound
#

uh

#

!paste

night quarryBOT
#

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.

quartz wave
rapid sparrow
#

did anything else print out at all?

rich hound
#

lemme replicate error

#

or try

#

doesnt wanna do it

rapid sparrow
#

hmm

#

it doesn't seem to be taking advantage of the multiple threads

rich hound
#

yea

rapid sparrow
#
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```
rich hound
#

it do that

#

idk how to make it work properly

#

keep pressing ctrl+c on that part

#

youll eventually get the error

#

i think

rapid sparrow
#

wonder why the KeyboardInterrupt isn't stopping it

quartz wave
#

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