#esoteric-python

1 messages · Page 93 of 1

fiery hare
#

in a class, if you always wanted the instances to be falsy for some reason, you could just have __bool__ = False

#

!e

True()
night quarryBOT
#

@fiery hare :x: Your eval job has completed with return code 1.

001 | <string>:1: SyntaxWarning: 'bool' object is not callable; perhaps you missed a comma?
002 | Traceback (most recent call last):
003 |   File "<string>", line 1, in <module>
004 | TypeError: 'bool' object is not callable
fiery hare
#

wow triggered

runic ruin
#

!e print(True+True)

night quarryBOT
#

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

2
runic ruin
#

!e print((True+True)**((True+True)*(True+True)))

night quarryBOT
#

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

16
runic ruin
#

!e print(((True+True)**((True+True)*(True+True)))**((True+True)**((True+True)*(True+True))))

night quarryBOT
#

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

18446744073709551616
runic ruin
#

!e print(16**16)

night quarryBOT
#

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

18446744073709551616
runic ruin
#

I should probably move to #bot-commands, sorry

thin trout
#

Ah yes, the gzipped code

boreal slate
#
def m(mat) : 
    row_flag, col_flag = False, False    
    for i in range(0, len(mat)) :   
        for j in range(0, len(mat)) : 
            if (i == 0 and mat[i][j] == 1) : row_flag = True       
            if (j == 0 and mat[i][j] == 1) : col_flag = True 
            if (mat[i][j] == 1) : mat[0][j],mat[i][0] = 1,1
    for i in range(1, len(mat)) : 
        for j in range(1, len(mat) + 1) : 
            if (mat[0][j] == 1 or mat[i][0] == 1):mat[i][j] = 1
    if (row_flag == True) : 
        for i in range(0, len(mat)) : mat[0][i] = 1
    if (col_flag == True) : 
        for i in range(0, len(mat)) : mat[i][0] = 1
def prt(mat) : 
    for i in range(0, len(mat)) : 
        for j in range(0, len(mat) + 1) : print( mat[i][j], end = "" ) 
        print() 
#Test Case
mat = [ [1, 0, 0, 1], 
        [0, 0, 1, 0], 
        [0, 0, 0, 0] ]               
m(mat) 
prt(mat) ``` how can i reduce this function.
vestal solstice
#

what should it do?

formal sandal
#

Q: how do you shuffle a list?

#

A:

#

!e

import random

class Holder:
    def __init__(self, x):
        self.x = x

    def __lt__(self, other):
        return random.choice((True, False))

    def unhold(self):
        return self.x

def shuffle(iterable):
    return list(map(Holder.unhold, sorted(map(Holder, iterable))))

print(shuffle([1, 2, 3, 4, 5]))
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

[1, 4, 2, 5, 3]
vestal solstice
#

@boreal slate this or something more?

def m(mat) : 
    rows = [any(x) for x in mat]
    cols = [any(x) for x in zip(*mat)]
    mat[:] = [[int(j or i) for j in cols] for i in rows]
boreal slate
#

ye i tried that, got it happened

#

now i am compressing more

formal sandal
#

!e

from contextlib import contextmanager

class Config:
    def __init__(self, data=()):
        self.data = dict(data)

    def __getitem__(self, key):
        return self.data.get(key)

    def __setitem__(self, key, value):
        if value is None:
            del self.data[key]
        else:
            self.data[key] = value

    def using(self, key, value):
        @contextmanager
        def manager():
            try:
                old = self[key]
                self[key] = value
                yield
            finally:
                self[key] = old
        return manager()

    def __getattr__(self, attr):
        if not attr.endswith("_being"):
            raise AttributeError(Attr)
        key = attr[:-6]
        return lambda v: self.using(key, v)

    def __repr__(self):
        return f"Config({self.data})"


config = Config()


def inject_pi(fn):
    def new_fn(*args, **kwargs):
        with config.pi_being(3.14):
            return fn(*args, **kwargs)
    return new_fn


@inject_pi
def circumference(r):
    return config["pi"] * r

print(circumference(10))
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

31.400000000000002
formal sandal
sonic ginkgo
#

@formal sandal GWcmeisterPeepoE

formal sandal
#

see, it reads like plain English

        with config.pi_being(3.14):

"with config.pi being 3.14..."
just like SQL, right

tight hedge
#

Looks like most of the mock/monkeypatch context managers.

from unittest.mock import patch

with patch.dict(config.data, {'pi': 3.14}):
  ...
formal sandal
#

We need to build scalable ™️ , extensible ™️ , flexible ™️ software, so we will take pi from a configuration file!

stark fable
#

well we can't have our software breaking if the laws of mathematics change so pi becomes something different

steep crest
#

lmao

sick hound
#

this channel scares me

#

yall are some wizards

snow beacon
#

Any technology, sufficiently advanced...

formal sandal
#

rather "I have yet to see any problem, however complicated, which, when looked at in the right way did not become still more complicated."

high garnet
#

rather "I have yet to see any problem, however complicated, which, when looked at in the right way did not become still more complicated."
@formal sandal "Why solve today's problems when we can create some for tomorrow?"

formal sandal
#

Anthem of regex

snow beacon
#

print(*(s[i^1]for i in range(len(s))),sep='')

#

That could perhaps be shrunk by reusing the len somehow.

formal sandal
#
print(*(s[i^1]for i in range(len(s))),sep='')
print(''.join(s[i^1]for i in range(len(s))))

not actually shorter, right?

snow beacon
#

That's better.

#

print(''.join(a[(i-b)^1]for i in range(len(a)))) to skip on creating s.

boreal slate
#

that doesn't work

snow beacon
#

That's what I mean, yes.

#

It works for me.

boreal slate
#

well it doesn't lemme test it again

boreal slate
#

i think it doesn't work cuz it has a newline at the end

#

@snow beacon doesn't work with longer and different inputs

snow beacon
#

Do you have an example of an input that fails, and the differing outputs you get for it?

boreal slate
#

MPORQTSVUXWZYBADCFEHGJILKN @snow beacon

snow beacon
#

Is it the M and the N?

boreal slate
#

YDAFCHEJGLINKPMROTQVSXUZWB this is the output

snow beacon
#

Which one is the intended output?

boreal slate
#

well i dunno that yet

#

lemme test

#

ABCDEFGHIJKLMNOPQRSTUVWXYZ

#

this @snow beacon

snow beacon
#

I'm a little lost. Which bits are inputs and which are outputs?

boreal slate
#

MPORQTSVUXWZYBADCFEHGJILKN the input

#

YDAFCHEJGLINKPMROTQVSXUZWB the output got

#

ABCDEFGHIJKLMNOPQRSTUVWXYZ the correct output @snow beacon

snow beacon
#

Thank you. I'll look into it when I get back to my computer.

snow beacon
#

Oh, I see where you got the question from.

#

Or maybe where you put it after putting it here?

cedar inlet
#

can i ask you some more questions about the code you just gave @sonic ginkgo

sonic ginkgo
#

@cedar inlet sure but maybe this isnt the best place? i guess general is too busy..

#

i wouldnt consider what i wrote esoteric

cedar inlet
#

neither i

#

but i didnt know where else to go as general is usually swampped

sonic ginkgo
#

same

#

this is fine

#

you can also open another help channel and tag me

cedar inlet
#

ill do that

sonic ginkgo
#

👍

stark fable
#
is_prime = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997}.__contains__``` i made an optimized prime checking algorithm for numbers below 1000
snow beacon
#

I made a primality checker for <100 by encoding them as the bits of an integer.

formal sandal
#
is_prime = __import__("sympy").isprime

i made an optimized prime checking algorithm

high garnet
#

don't do it...

#

optimised for what?

#

minimum readability?

formal sandal
#

oh wait, it can be even shorter

#
from sympy import isprime as is_prime
#

nevermind, this is still shorter:

is_prime=__import__("sympy").isprime
#

optimised for what?
minimum readability?
I think it's implied in this channel 🙂

formal sandal
#

!e

import sys


class Builder: 
    def __init__(self, elements=None): 
        if elements is None: 
            self.elements = [] 
        else: 
            self.elements = elements 
     
    def add(self, element): 
        if (rc := sys.getrefcount(self)) <= 3: 
            print(f"Psst, nobody knows you're mutating me! refcount: {rc}") 
            self.elements.append(element) 
            return self 
        else: 
            return Builder(self.elements + [element]) 
     
    def __repr__(self): 
        return f"Builder({self.elements})" 


b = Builder().add(1).add(2).add(3)
print(b)
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

001 | Psst, nobody knows you're mutating me! refcount: 3
002 | Psst, nobody knows you're mutating me! refcount: 3
003 | Psst, nobody knows you're mutating me! refcount: 3
004 | Builder([1, 2, 3])
formal sandal
#

Optimization for the Builder pattern thingy 😄

stark fable
#

!e ```py
import sys

class Builder:
def init(self, elements=None):
if elements is None:
self.elements = []
else:
self.elements = elements

def add(self, element): 
    if (rc := sys.getrefcount(self)) <= 3: 
        print(f"Psst, nobody knows you're mutating me! refcount: {rc}") 
        self.elements.append(element) 
        return self 
    else: 
        return Builder(self.elements + [element]) 
 
def __repr__(self): 
    return f"Builder({self.elements})" 

b = Builder()
x = b.elements
print(b.add(1))
print(x)```

night quarryBOT
#

@stark fable :white_check_mark: Your eval job has completed with return code 0.

001 | Builder([1])
002 | []
stark fable
#

...huh

formal sandal
#

that's because there's an extra reference to Builder() -- the variable b

#

😛

stark fable
#

oh

#

right, yeah, that makes sense

formal sandal
#

well, you could do del b, then there'll be a bug

stark fable
#

hmm

#

well how can you do del b and then continue to access the builder afterwards

formal sandal
#

uhh

#

yeah, I'm dumb

#

that's how 🙂

stark fable
#

!e ```py
import sys

class Builder:
def init(self, elements=None):
if elements is None:
self.elements = []
else:
self.elements = elements

def add(self, element): 
    if (rc := sys.getrefcount(self)) <= 3: 
        print(f"Psst, nobody knows you're mutating me! refcount: {rc}") 
        self.elements.append(element) 
        return self 
    else: 
        return Builder(self.elements + [element]) 
 
def __repr__(self): 
    return f"Builder({self.elements})" 

b = Builder()
x = b.elements
a = b.add
del b
print(a(1))
print(x)```

night quarryBOT
#

@stark fable :white_check_mark: Your eval job has completed with return code 0.

001 | Psst, nobody knows you're mutating me! refcount: 3
002 | Builder([1])
003 | [1]
stark fable
#

there

formal sandal
#

ahh

#

well, let's hope nobody will do that

steep crest
#

please stop hurting my brain guys

#

jk, y'all are awesome

sick hound
#

lol

stray rampart
#

converts dict of lists into list of dicts:

#
list(map(dict, map(functools.partial(zip, mapping.keys()), zip(*mapping.values()))))
#

mapping = {"a": [1, 2], "b": [3, 4]} -> [{"a": 1, "b": 2"}, {"a": 3, "b": 4}]

fallen roost
#

good

sick hound
#

does this channel follow pep

proper vault
#

a pep probably

sick hound
#

xd

sick hound
#

@stray rampart you are truly the special one

vestal solstice
#

a pep demands worship

rugged sparrow
#

@sick hound we sometimes implement rejected PEPs in pure python

formal sandal
#

I think some people also get the impression that PEP is interchangeable with "PEP 8"

stray rampart
#

i never understood pep numbering

#

i thought pep 8 was pep 8 cause it happened pretty early in python

#

so r they just random numbers?

rugged sparrow
#

!e ```py
from ctypes import *
c_void_p.from_address(id(int)+(27*8)).value = cast(CFUNCTYPE(py_object, py_object)(lambda s:(yield from range(s))),c_void_p).value
print([*10])

night quarryBOT
#

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

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
rugged sparrow
#

^ PEP 276

formal sandal
#

lmao

#

can you also make 10(5) == 10 * 5?

elfin pilot
#

maybe by altering field of static structure of int type with ctypes

rugged sparrow
#

!e ```py
from ctypes import *
c_void_p.from_address(id(int)+(168)).value = cast(CFUNCTYPE(py_object,py_object,py_object)(lambda s,o:so[0]), c_void_p).value
print(10(5))

night quarryBOT
#

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

001 | <string>:3: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
002 | 50
rugged sparrow
#

@formal sandal there

#

just a dif offset

formal sandal
#

'int' object is not callable;
Yeah, exactly, you smart ass interpreter!

gentle pagoda
#

how can i overwrite dunder methods of functions? (specifically __mul__) ive been reading the PyFunction struct but im not sure what im looking for

hard spoke
#

Hmm, not sure it's possible to override __mul__ on functions - they don't have it, and it looks like adding it doesn't make them use it. Can't you use a callable class instead?

gentle pagoda
#

i wanted to implement composition. i know i can do it with a class but thats not so much like a function any more

#

i know its possible to do it with __matmul__ using BRM

stark fable
#

you'd need to edit the struct for the function type

next flame
#

@stray rampart they're mostly ascending numbers

#

anything starting with 3000 means for python3

gentle pagoda
#

@stark fable do you mean ctypes fuckery, or recompiling cpython with a different struct? if you mean the former, i couldnt see a way to from looking at the struct

stark fable
#

ctypes fuckery

gentle pagoda
#

ah. how?

#

im guessing by changing its __dict__?

stark fable
#

nope

gentle pagoda
stark fable
gentle pagoda
#

oh okay

#

how would i go about editing that?

rugged sparrow
#

!e ```py
from ctypes import *

def func_mult(self, other):
for _ in range(other):
self()

num_methods = (c_void_p36)()
num_methods[2] = cast(CFUNCTYPE(
[py_object]*3)(func_mult),c_void_p)
ptr = cast(pointer(num_methods), c_void_p)
c_void_p.from_address(id(type(lambda:0)) + (12 * 8)).value = ptr.value

(lambda:print(1)) * 5```

night quarryBOT
#

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

001 | 1
002 | 1
003 | 1
004 | 1
005 | 1
rugged sparrow
#

@gentle pagoda ^ theres an example

gentle pagoda
#

@rugged sparrow wow thats so cool, ill need to check the source again to understand how it works lol. thanks! :)

rugged sparrow
#

ping me if you want me to explain any of it

gentle pagoda
#

yeah im pretty lost actually 😅 what does multiplying a voidptr do? py num_methods = (c_void_p * 36)()

rugged sparrow
#

ok so c_void_p * 36 creates a class for a 36 item array of c_void_p

#

then i instantiate it, creating an empty 36 item array that i can use

#

(the 36 items is because internally the PyNumberMethods struct can be interpreted as an array of func pointers)

gentle pagoda
#

right

#

what about structure packing?

rugged sparrow
#

func pointers are all 8 bytes

gentle pagoda
#

could that lead to issues or not? i dont know much about C implementation details

rugged sparrow
#

and thus can be used as an array

gentle pagoda
#

ah okay

rugged sparrow
#

yah c typedef struct { long a; long b; long c; } is the same as ```c
long arr[3];

gentle pagoda
#

im pretty sure the compiler can add arbitrary padding around the struct fields

#

and the array elements

rugged sparrow
#

well an instance of that struct would be

#

they will to the nearest alignment

#

not as much in arrays tho afaik

#

and in python 9 times out of 10 things will be aligned to 8

gentle pagoda
#

right, ok

#

thanks :)

rugged sparrow
#

no prob

gentle pagoda
#

so then we index the second element which is nb_multiply

rugged sparrow
#

yup

gentle pagoda
#

make a CFUNCTYPE from the mul function, cast it to a fuction pointer

rugged sparrow
#

CFUNCTYPE(*[py_object]*3) is actually CFUNCTYPE(py_object, py_object, py_object)

gentle pagoda
#

yep

rugged sparrow
#

(rettype, arg1type, arg2type)

#

yea

#

then we get a pointer to num_methods

#

cast it to c_void_p to make it easier use the address

#

(12 * 8) is the offset on the PyType struct that has the pointer to PyNumberMethods

#

so we insert the pointer to our array there

#

c_void_p.from_address(id(type) + (12 * 8)) lets us access those 8 bytes as a c_void_p (which will be null if the type has no number methods)

gentle pagoda
#

if a function pointer in num_methods is NULL does that trigger TypeError: unsupported operand type(s) for +: 'function' and 'int'?

rugged sparrow
#

yup

#

acc that might first cause a lookup on the base class before it fails

#

prob does

gentle pagoda
#

thanks! that makes sense now :)

rugged sparrow
#

no problem

#

thatll help you start messing with other classes

gentle pagoda
#

yeah thats super helpful, ill try some other stuff

#

:D

#

this is just so neat ```py

test = (lambda x: x + 1) * (lambda x: x * 2)

test(3)
7```

rugged sparrow
#

noice

formal sandal
#

Is there a way to hook into getting a global variable (with ctypes or something)? For example, if the variable is not found, it would be looked up in some specific dict.

rugged sparrow
#

you could subclass the globals() dict

#

by shunting a subclass in

formal sandal
#

hm, yes, so just change the type pointer to my subclass of dict

#

Does global lookup actually looks up stuff in the globals()?

rugged sparrow
#

!e ```py
from ctypes import *

class Dict(dict):
singleton = object()
def getitem(self, item):
if self.get(item, singleton) == singleton:
return 'a'
else:
return self.get(item)

py_object.from_address(id(globals()) + 8).value = Dict
print(abc)```

night quarryBOT
#

@rugged sparrow :x: Your eval job has completed with return code 139 (SIGSEGV).

001 | Traceback (most recent call last):
002 |   File "<string>", line 12, in <module>
003 |   File "<string>", line 6, in __getitem__
004 | SystemError: Objects/dictobject.c:1434: bad argument to internal function
rugged sparrow
#

oh it didnt like that lol

formal sandal
#

don't touch me there! -- python internals

rugged sparrow
#

eh gimme a sec

#

@formal sandal its def possible but would take some weird logic

formal sandal
#
def __getitem__(self, key):
    try:
        return dict.__getitem__(self, key)
    except KeyError:
        raise

maybe like this? thinkmon

rugged sparrow
#

try it

formal sandal
#

doesn't work 😦

rugged sparrow
#

could always hook dict.__getitem__ directly

formal sandal
#

mwahahahaha

#

Well, that __getitem__ broke my IPython session 😦

#

nuuu

#

I tried to exit and got a segmentation fault

#

classic

rugged sparrow
#

the problem is that globals is checked before __builtins__

formal sandal
#

hm...

#

so... hook into __builtins__?

rugged sparrow
#

thats dangerous too

#

you could always just add your value to builtins

gentle pagoda
#

@rugged sparrow well i tried replacing tp_new but im not entirely sure i have the index right. i think its 42, but its not calling my function

rugged sparrow
#

for what class?

gentle pagoda
#

functions

rugged sparrow
#

its index 40 afaik

#

so 40 * 8

gentle pagoda
#

that doesnt seem to work

#

oddly, neither does tp_call at index 16

rugged sparrow
#

afaik function doesnt really use those the normally

#

special handling

gentle pagoda
#

oh ok, rip

rugged sparrow
#

!e ```py
from ctypes import *

c_void_p.from_address(id(type(lambda:0)) + (40 * 8)).value = None
(lambda:0)```

night quarryBOT
#

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

[No output]
gentle pagoda
#

i wanted to implement currying, so that would need to hook function creation or calling

#

would any of the accessible functions allow me to hook into that behavior?

rugged sparrow
#

you'd need to go thru the source code

gentle pagoda
#

could i replace the function type entirely with a wrapper class?

rugged sparrow
#

Definitely not safely

gentle pagoda
#

could i change the baseclass to have different behavior?

rugged sparrow
#

Try it

distant wave
#

!e ```py
print(0==type('',(object,),{"eq":(lambda*x:True)})())

night quarryBOT
#

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

True
boreal slate
#
def jumping_frog(a,b):
    i=0
    ans=1
    while i<a:
        if(b[i]==0):
            return ("no chance :-(")
        elif b[i-1]>b[i] and i>0:
            ans+=1
            i-=1
        else:
            i+=b[i]
            ans+=1
    return ans``` how can i reduce this code?
snow beacon
#

What is the code meant to do? It's hard to conceptualise everything without comments.

sick hound
#

Hey, is it possible to write this in one list comp?
walk_commands() is an object with the name and aliases attribute
[c.name for c in self.bot.walk_commands()] + [' '.join(c.aliases) for c in self.bot.walk_commands() if c.aliases]

#

without it becoming a list of tuples

#

as aliases could be ['']

copper thunder
#

Maybe something like : ```py
[x for x in (c.name, " ".join(c.aliases)) for c in self.bot.walk_commands() if x]

sick hound
#

Wow, let me try

#

Saying c is undefined 🤔

copper thunder
#

oh I always put it in the wrong order

#
[x for c in self.bot.walk_commands() for x in (c.name, " ".join(c.aliases)) if x]
#

I think

sick hound
#

Yep that works, thanks a lot :)

copper thunder
#

don't know if it is more clear though 😛 But this channel is often about clean code ^^

thin trout
#

But this channel is often about clean code
Did you mean about unclear code, though? lemon_pleased

copper thunder
#

oh yeah a negation is clearly missing here ×)

boreal slate
#
solution=lambda n:all(k%i for i in range(2,int(k**.5)+1))if(k:=n**.5)==k//1<n else 0``` how can i make this code faster it returns True if the number has 3 factors and false if it has less than 3 factors
snow beacon
#

Why do you square-root k, when it's already a square root?

boreal slate
#

i had got this formula from a math website on google, don't remember exactly

vestal solstice
#

the goal is to see if squre root is prime

#

or is this one different

#

the way you described it, you want to check for 2 factors, not 3 factors

#

exactly 2 factors → n is prime
exactly 3 factors → n is prime squared

boreal slate
#

i want to check if they have 3 factors , return true or false accordingly

vestal solstice
#

it would take fewer steps to check the former

#

so 4 factors is false?

boreal slate
#

yes

vestal solstice
#

right

#

i don;t know how to make it faster

#
from bisect import bisect_left
# sqrt(1000000000) = 31622
__primes = sieve(31622)
def is_prime(n):
    # if prime is already in the list, just pick it
    if n <= 31622:
        i = bisect_left(__primes, n)
        return i != len(__primes) and __primes[i] == n
    # Divide by each known prime
    limit = int(n ** .5)
    for p in __primes:
        if p > limit: return True
        if n % p == 0: return False
    # fall back on trial division if n > 1 billion
    for f in range(31627, limit, 6): # 31627 is the next prime
        if n % f == 0 or n % (f + 4) == 0:
            return False
    return True
```first result for primality test
boreal slate
#

i can't use modules i am trying without them

#

should i give me a test case i have made one

vestal solstice
#

yeah sure

#

it's kinda offtopic

boreal slate
#

i just have a json file let me share that in a while, i am away from pc now, will share in a while

vestal solstice
#

totally

boreal slate
vestal solstice
#

unlucky

elfin onyx
#

hey

vestal solstice
#

or I should say lucky that you included it, or I would think it's a good solution

boreal slate
#

it should be without any modules

#

that is the only problem 😦

vestal solstice
#

how much faster do you need it?

boreal slate
#

the whole thing under 10 seconds?

vestal solstice
#

yes the entire thing

#

it doesn't really work though

#

yours takes 1 second for everything and works x)

boreal slate
#

well it is little complicated

#

and i don't want tat

vestal solstice
#

wait yours is complicated?

boreal slate
#

yes i think

#

my friends couldn't understand it

#

want to create it fast but readable

vestal solstice
#

it's 3 times faster

#

0.5 instead of 1.6 for all tests

#

pm me for code

snow beacon
#

If it has three factors, it must be a prime number squared. I don't know what to do with that information.

formal sandal
#

!e

do=lambda x:x

@do
def f():
    x <- getLine
    y <- getLine
    putStrLn (show(x) ++ ", " ++ show(y))
night quarryBOT
#

@formal sandal :warning: Your eval job has completed with return code 0.

[No output]
formal sandal
#

finally 🧪🥼

formal sandal
#

now the challenge is to transform it into

def f():
    return getLine.__bind__(lambda x: getLine.__bind__(lambda y: putStrLn(show(x) + ", " + show(y))))
zealous widget
#
In [9]: class Test:
   ...:     def __neg__(self):
   ...:         return self
   ...:     def __gt__(self, other):
   ...:         print(f'binding {other}')
   ...:
   ...: class Var:
   ...:     def __init__(self, name):
   ...:         self.name = name
   ...:     def __repr__(self):
   ...:         return self.name
   ...:
   ...: x = Var('x')
   ...: getLine = Test()
   ...: x <- getLine
binding x
#

well, that's the obvious part

#

oh, if you just want to transform it with the decorator i suppose you can just do some ast hack

#

In [12]: from prettiest_ast import ppast
    ...: from inspect import getsource
    ...:
    ...: def do(func):
    ...:     ppast(getsource(func))
    ...:     return func
    ...:
    ...: @do
    ...: def f():
    ...:     x <- getLine
    ...:     y <- getLine
    ...:     putStrLn (show(x) ++ ", " ++ show(y))
    ...:
FunctionDef
├──f
├──arguments
├──Expr
│  ╰──Compare
│     ├──Name
│     │  ├──x
│     │  ╰──Load
│     ├──Lt
│     ╰──UnaryOp
│        ├──USub
│        ╰──Name
│           ├──getLine
│           ╰──Load
├──Expr
│  ╰──Compare
│     ├──Name
│     │  ├──y
│     │  ╰──Load
│     ├──Lt
│     ╰──UnaryOp
│        ├──USub
│        ╰──Name
│           ├──getLine
│           ╰──Load
...

this was a bigger ast than i expected

formal sandal
#

that's what she said

hasty ferry
#

that's what she said

formal sandal
#

!e

from functools import lru_cache

def LruSet(max_depth):
    _HACK = False

    @lru_cache(maxsize=max_depth)
    def has(element):
        return _HACK
        
    def push(element):
        nonlocal _HACK
        _HACK = True
        has(element)
        _HACK = False

    return (has, push)

has, push = LruSet(3)
push(1)
push(2)
push(3)
push(4)
push(5)
print(has(5), has(4), has(3), has(2), has(1))
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

True True True False False
sick hound
#

why is everything here so weird

snow beacon
#

It's in the channel description.

#

"Weirdness".

twilit grotto
#

if it's not weird, it doesn't belong here lol

formal sandal
#

Yeah

#

You're not weird @twilit grotto, get out!

twilit grotto
#

oh..

fiery hare
#

!e

import string; print(''.join((z := ' ' + string.ascii_lowercase + '.,')[z.index(i)-2] for i in 'yj.bkubgxgt.vjkpibjgtgbuqbygktf'))
night quarryBOT
#

@fiery hare :white_check_mark: Your eval job has completed with return code 0.

why is everything here so weird
fiery hare
#

@sick hound

snow beacon
#

!e

t = (lambda data,encode=True:(lambda f,*args:f(f,*args))((lambda self,b64,iters,quine:(bytes.decode,lambda string:f"{quine}{ascii(quine)}))(\'{b64.b64encode(string).decode()}\',False)")[encode](bytes(map(lambda base,key:(base+(encode or~encode)*key)%256,(b64.b64decode,str.encode)[encode](data),iters.cycle(self.__code__.co_code))))),*map(__import__,('base64','itertools')),'(lambda data,encode=True:(lambda f,*args:f(f,*args))((lambda self,b64,iters,quine:(bytes.decode,lambda string:f"{quine}{ascii(quine)}))(\\\'{b64.b64encode(string).decode()}\\\',False)")[encode](bytes(map(lambda base,key:(base+(encode or~encode)*key)%256,(b64.b64decode,str.encode)[encode](data),iters.cycle(self.__code__.co_code))))),*map(__import__,(\'base64\',\'itertools\')),'))('62jjIfBzp2bcZ9Z62Grtds0i8GiLZZRz4yL+aM9zyA==',False)
print(t)
night quarryBOT
#

@snow beacon :white_check_mark: Your eval job has completed with return code 0.

why is everything here so weird
snow beacon
#

(From my obfuscator for the challenge a while ago.)

fiery hare
#

wow

#

I had to encode and decode all of that manually

#

and here you are

snow beacon
#

The code just appends the last set of brackets (('62jjIfBzp2bcZ9Z62Grtds0i8GiLZZRz4yL+aM9zyA==',False)) to its own source code.

fiery hare
#

ah

snow beacon
#

I think this might break on different Python versions, because it depends on the exact bytecode the code gets compiled to. By break, I mean code generated in one version won't be compatible with other Python versions.

sick hound
#

!e ```py
t = (lambda data,encode=True:(lambda f,*args:f(f,*args))((lambda self,b64,iters,quine:(bytes.decode,lambda string:f"{quine}{ascii(quine)}))('{b64.b64encode(string).decode()}',False)")[encode](bytes(map(lambda base,key:(base+(encode or~encode)*key)%256,(b64.b64decode,str.encode)encode,iters.cycle(self.code.co_code))))),*map(import,('base64','itertools')),'(lambda data,encode=True:(lambda f,*args:f(f,*args))((lambda self,b64,iters,quine:(bytes.decode,lambda string:f"{quine}{ascii(quine)}))(\'{b64.b64encode(string).decode()}\',False)")[encode](bytes(map(lambda base,key:(base+(encode or~encode)*key)%256,(b64.b64decode,str.encode)encode,iters.cycle(self.code.co_code))))),*map(import,('base64','itertools')),'))('62jjIfBzp2bcZ9Z62Grtds0i8GiLZZRz4yL+aM9zyA==',False)
print(t)````

night quarryBOT
#

@sick hound :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 2
002 |     print(t)`
003 |             ^
004 | SyntaxError: invalid syntax
sick hound
#

!e
t = (lambda data,encode=True:(lambda f,*args:f(f,*args))((lambda self,b64,iters,quine:(bytes.decode,lambda string:f"{quine}{ascii(quine)}))('{b64.b64encode(string).decode()}',False)")[encode](bytes(map(lambda base,key:(base+(encode or~encode)*key)%256,(b64.b64decode,str.encode)encode,iters.cycle(self.code.co_code))))),*map(import,('base64','itertools')),'(lambda data,encode=True:(lambda f,*args:f(f,*args))((lambda self,b64,iters,quine:(bytes.decode,lambda string:f"{quine}{ascii(quine)}))(\'{b64.b64encode(string).decode()}\',False)")[encode](bytes(map(lambda base,key:(base+(encode or~encode)*key)%256,(b64.b64decode,str.encode)encode,iters.cycle(self.code.co_code))))),*map(import,('base64','itertools')),'))('62jjIfBzp2bcZ9Z62Grtds0i8GiLZZRz4yL+aM9zyA==',False)
print(t)

night quarryBOT
#

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

why is everything here so weird
snow beacon
#

You had an extra ` at the end of the message that had the error.

#

Also, you can click the trashemoji to remove the clutter of the syntax error.

#

It's calling the function with data = the base64 encoded ciphertext and encode = False. That means it calls bytes.decode on the result of performing some code-related manipulations with the bytes of decoding the data. The encoding means taking the bytecode of the function itself, and using it as the key of an adapted Vigenère cipher. The decoder's code includes the encoder: you just replace the last call with a string, rather than a string and a False. It will print out code like the above, which you can slot into anywhere Python would expect a string.

#

That's why it has a quine in it.

sick hound
#

how to build a binary tree

snow beacon
#

!e

Node=lambda x,y:type("BinaryTree",(),{"left":x,"right":y,"__repr__":lambda s:f"<{s.left}>-<{s.right}>"})()
Leaf=lambda x:type("BinaryTree",(),{"__repr__":lambda s:f"<{s}>","contents":x})()
print(Node(Node(0, 1), Leaf(2)))# // <!-- Builds a binary tree containing ((0,1), 2) --!>
night quarryBOT
#

@snow beacon :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 |   File "<string>", line 1, in <lambda>
004 |   File "<string>", line 2, in <lambda>
005 |   File "<string>", line 2, in <lambda>
006 |   File "<string>", line 2, in <lambda>
007 |   [Previous line repeated 329 more times]
008 | RecursionError: maximum recursion depth exceeded while calling a Python object
snow beacon
#

That's not meant to happen...

#

!e

Node=lambda x,y:type("BinaryTree",(),{"left":x,"right":y,"__repr__":lambda s:f"<{s.left}>-<{s.right}>"})()
Leaf=lambda x:type("BinaryTree",(),{"__repr__":lambda s:f"<{s.contents}>","contents":x})()
print(Node(Node(Leaf(0), Leaf(1)), Leaf(2)))# // <!-- Builds a binary tree containing ((0,1), 2) --!>
night quarryBOT
#

@snow beacon :white_check_mark: Your eval job has completed with return code 0.

<<<0>>-<<1>>>-<<2>>
snow beacon
#

Much better.

sick hound
#

wh-

#

Now explain what are binary trees again

#

ty tho

snow beacon
#

Oh, maybe you'd be better served in one of the help channels.

#

Try posting your question in one of the available ones.

#

This channel is for doing things in the weirdest way possible.

sick hound
#

Oh oki

snow beacon
#

Please do not learn any lessons from what I wrote above.

twilit grotto
sick hound
#

Idk what are binary trees for tho

#

I watched a few videos and they talked about weights, so that means that u have to balance ur binary tree for some reason?

#

But I'm thinking of making a perfect binary tree if that matters

cloud garden
#
ILikePython:abs;olutely="!"

This is valid syntax

copper thunder
#

funny ^^

waxen vine
#

^^^

heavy creek
#

huh, I don't get why the ILikePython:abs works. I get the rest, and using anything but a predefined name, like the built-in "abs" here won't work. Is it some unusual side effect of the parser?

rugged sparrow
#

It's an annotation

#

!e var:1

night quarryBOT
#

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

[No output]
heavy creek
#

oh damn, I forgot you can do that on module level

fiery hare
#

(s := []).append(s)
could you do this in one line before the walrus operator?

vestal solstice
#

locals().setdefault('s', []).append(s)

snow beacon
#

That doesn't work inside a function, unfortunately.

vestal solstice
#

can you explain why?

#

I don't know this side of things

snow beacon
#

locals outside a function is basically globals, which is mutable.

#

Inside a function, the locals dict is read-only.

vestal solstice
#

thanks

snow beacon
#

Oh hey, it works in a function if you make it globals instead, although it of course sets a global variable rather than a local one.

vestal solstice
#

so not really

snow beacon
#

There's alwayspy s = (lambda x:x.append(x) or x)([])which is — alas! — not an expression.

snow beacon
#
s = [s.append(s) or s for s in [[]]][0]```
rugged sparrow
#

s,=[s.append(s)or s for s in [[]]] a bit shorter

snow beacon
#

It does have less square brackets in a row though.

worldly flint
#

does python have tco?

snow beacon
#

No.

#

I think Guido chose not to for better stack traces.

thin trout
#

I have a new challenge for you guys, parser overflows with the least characters possible

#

Here’s my submission

#

!e exec('('*999)

night quarryBOT
#

@thin trout :x: Your eval job has completed with return code 1.

001 | s_push: parser stack overflow
002 | Traceback (most recent call last):
003 |   File "<string>", line 1, in <module>
004 | MemoryError
snow beacon
#

I can't top that.

cedar thicket
#

hey , I should reduce this code from 7 lines to only 2 , can someone help me :
def fac(*x):
for a in range(len(x)):
r = 1
for i in range(list(x).pop(a)):
r+= r * i
print("\nLa factorielle de",x[a],"est :",r)
fac(x-1,y-1)

full nest
#

@cedar thicket use the included factorial operator

rugged sparrow
#
f=lambda n,o=1:[(o:=o*i)for i in range(1,n+1)][-1]
vernal dove
#

this probably isn't esoteric enough but I always liked it

a = 256
b = 256
c = 257
d = 257
#Guess the answers before running
a == b
a is b
c == d
c is d```
rugged sparrow
#

True, True, True, False

#

-256 thru 256 are interned integers

cursive plover
#

could we golf this further?

from turtle import*
getscreen()
Turtle()
[(forward(30),right(x))for x in[270,90,90]*3]
#

obv a one liner is
[__import__("turtle").getscreen(),__import__("turtle").Turtle(),[(__import__("turtle").forward(30), __import__("turtle").right(angle)) for angle in [270,90,90]*3]]

#

but eh, that only increases the char count

proper vault
#

I am pretty sure you can omit getscreen()
Turtle()

stark fable
#

@rugged sparrow it's -5 to 256, not -256 to 256

#
>>> x = -5
>>> y = -5
>>> x is y
True
>>> x = -6
>>> y = -6
>>> x is y
False```
rugged sparrow
#

oh i thought it was -256 for some reason

#

@cursive plover py (lambda t:[(t.forward(30),t.right(x))for x in[270,90,90]*4])(__import__('turtle'))

cursive plover
#

that's

#

actually longer

#

but cool

proper vault
#

if all we want is short,

from turtle import*
for x in[270,90,90]*4:forward(30);right(x)
cursive plover
#

ah

#

that's 3 letters shorter

#

that's nice, didn't think of that thanks

proper vault
#

list comps are not shorter than real loops

cursive plover
#

yeah the realisation

#

1 letter shorter

#
from turtle import*
for x in[3,1,1]*3:forward(30);right(x*90)
stark fable
#

this is 14 letters instead of 35 so it's 21 letters shorter py exec(''.join(map(chr,[102, 114, 111, 109, 32, 116, 117, 114, 116, 108, 101, 32, 105, 109, 112, 111, 114, 116, 42, 10, 102, 111, 114, 32, 120, 32, 105, 110, 91, 51, 44, 49, 44, 49, 93, 42, 51, 58, 102, 111, 114, 119, 97, 114, 100, 40, 51, 48, 41, 59, 114, 105, 103, 104, 116, 40, 120, 42, 57, 48, 41])))

cursive plover
#

@stark fable how even did you get that

stark fable
#
>>> ''.join(map(chr,[102, 114, 111, 109, 32, 116, 117, 114, 116, 108, 101, 32, 105, 109, 112, 111, 114, 116, 42, 10, 102, 111, 114, 32, 120, 32, 105, 110, 91, 51, 44, 49, 44, 49, 93, 42, 51, 58, 102, 111, 114, 119, 97, 114, 100, 40, 51, 48, 41, 59, 114, 105, 103, 104, 116, 40, 120, 42, 57, 48, 41]))
'from turtle import*\nfor x in[3,1,1]*3:forward(30);right(x*90)'```
cursive plover
#

what?

stark fable
#

it's just this code py from turtle import* for x in[3,1,1]*3:forward(30);right(x*90)

#

it execs that code

cursive plover
#

yeah but how'd ya get the numbers

stark fable
#
>>> list(map(ord, '''from turtle import*
... for x in[3,1,1]*3:forward(30);right(x*90)'''))
[102, 114, 111, 109, 32, 116, 117, 114, 116, 108, 101, 32, 105, 109, 112, 111, 114, 116, 42, 10, 102, 111, 114, 32, 120, 32, 105, 110, 91, 51, 44, 49, 44, 49, 93, 42, 51, 58, 102, 111, 114, 119, 97, 114, 100, 40, 51, 48, 41, 59, 114, 105, 103, 104, 116, 40, 120, 42, 57, 48, 41]```
cursive plover
#

ah, I see

cedar thicket
#

plz , a script which can calculate the factorial of a number in 1 line (without using math.factorial)

cursive plover
#

hm,

print(__import__('functools').reduce(lambda a,b:a*b,range(1,int(input())+1)))
rugged sparrow
#

@cedar thicket f=lambda n,o=1:[(o:=o*i)for i in range(1,n+1)][-1]

proper vault
#
f = lambda n: (lambda f, n=n: f(f, n))(lambda f, n: f(f, n-1)*n if n > 1 else n)
cedar thicket
#

@cedar thicket f=lambda n,o=1:[(o:=o*i)for i in range(1,n+1)][-1]
@rugged sparrow Sorry !! but it should take a tuple as arg 😩

grizzled cloak
#

how about a little contest for generating a 100 thousand long password? only speed matters, using chars a-z.

#

i suggest using this snippet to test the code using the python bot so your pc doesnt influence the runtime

#
from timeit import timeit
n = 1000

# write a function f
def f():
    return -1

_runtime = timeit(f, number=n)
print(_runtime / n)
edgy kelp
#

f = lambda: "b"*100000

grizzled cloak
#

lol

#

*a random password

copper thunder
#

That's exactly what I wanted to do 😛

rugged sparrow
#

@cedar thicket a tuple of what?

edgy kelp
#

What do you consider random?

copper thunder
#

And how long should they be ?

proper vault
#

I would argue that since random distribution is not rated, that solution is valid

cedar thicket
#

@cedar thicket a tuple of what?
@rugged sparrow of int !!

rugged sparrow
#

ok i wrote you a factorial function you can implement it

copper thunder
#

!e ```py
from timeit import timeit
from time import time_ns
n = 1000

write a function f

def f():
t = time_ns()
letters = "qwertyuiopasdfghjklzxcvbnm"
password = ''.join([letters[((i*t) ^ t + t) % 26] for i in range(100)])
return password

_runtime = timeit(f, number=n)
print(_runtime / n)

night quarryBOT
#

@copper thunder :white_check_mark: Your eval job has completed with return code 0.

5.273654405027628e-05
cedar thicket
#

ok i wrote you a factorial function you can implement it
@rugged sparrow this one is with the math.factorial methode : fac=lambda*x:[print("La factorielle de",i,"est:",m.factorial(i)) for i in list(x)]

#

I need it without any predefined methode

rugged sparrow
#

so use the one i sent

terse yew
#

woah

#

hey @rugged sparrow

rugged sparrow
#

howdy

grizzled cloak
#

100_000 long

#

My og message got scrolled up

cursive plover
#

how much random is random? 🤔
What's the measure of randomness here?

grizzled cloak
#

Equal distribution, randomly sampled

stark fable
#

what kind of randomness?

#

computers generally don't produce or have access to proper random randomness which afaik you can only really get from quantum mechanics

#

is random random enough? what about implementing your own PRNG?

#

should it use an external source like urandom or random.org or generate the "randomness" internally with algorithms that just kind of look random?

grizzled cloak
#

What ever works for you

#

Pseudo random is good enough

#

If a human can recognize the pattern then it's not random enough

stark fable
#

If a human can recognize the pattern then it's not random enough
well whether the human can recognize it depends on who the human is and how much experience they have with identifying patterns in a string of 100,000 characters

grizzled cloak
#

Lol

stark fable
#

if you use an algorithm that is definitely pseudo-random but is also simple enough that someone comes along who can compute it in their head well enough to recognize the pattern in the password...

grizzled cloak
#

It was just meant as a fun exercise :(

#

But yes, if you find out that some other pseudo random algo is faster, go for it

#

For instance on the gpu this one is pretty popular for it's simplicity: glsl frac(sin(dot(uv,float2(12.9898,78.233)))*43758.5453123);

#

In this case for 2d inputs

copper thunder
#

!e ```py
from timeit import timeit
from time import time_ns
n = 1000

write a function f

def f():
t = time_ns()
letters = "qwertyuiopasdfghjklzxcvbnm"
password = ''.join([letters[((i*t) ^ t + t) % 26] for i in range(100000)])
return password

_runtime = timeit(f, number=n)
print(_runtime / n)

night quarryBOT
#

@copper thunder :warning: Your eval job timed out or ran out of memory.

[No output]
copper thunder
#

It really can be any of the two 🤔 Anyone has a guess without trying the code with a generator instead of a list ?

tidal mica
#

help?

formal sandal
#

that's what people usually scream when they scroll through this channel 🙂

sick hound
#

it is scary

#

this channel hurts my head

formal sandal
#

@sick hound yes, that's the general idea 🙂

sick hound
#

lmao

thin trout
#

That’s the goal haha

#

Hmm

#

!e __builtins__ = None

night quarryBOT
#

@thin trout :warning: Your eval job has completed with return code 0.

[No output]
thin trout
#

Oh god

#

You can reassign it

#

Can you use a default dict on it?

proper vault
#

yes

thin trout
#

So if a name isn’t found, it will default to it?

#

Or builtins have the priority over the current scopes

proper vault
#
In [12]: (__builtins__ := defaultdict(lambda: 'Hello')).update(vars(__import__('builtins')))

In [13]: test
Out[13]: 'Hello'

In [14]: int
Out[14]: int
thin trout
#

I mean, if you do foo = 'bar', will foo still point to 'bar'?

proper vault
#

yeah

#

it checks scope, then builtins

thin trout
#

Noice

sick hound
#
__builtins__ = None```
snow beacon
#

We worked out you can recover a few of the important things if you delete all builtins.

stark fable
#
__builtins__ = ().__class__.__base__.__subclasses__()[80].acquire.__globals__['sys'].modules['builtins']``` :P
rugged sparrow
#
del __builtins__
del ().__class__.__base__.__subclasses__()[80].acquire.__globals__['sys'].modules['builtins']``` what about now?
sick hound
#

what the fuck

#

oh shit that completely fucks it

#
>>> del __builtins__
>>> del ().__class__.__base__.__subclasses__()[80].acquire.__globals__['sys'].modules['builtins']
>>> print
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: lost builtins module
>>> 
snow beacon
#

Where is that RuntimeError coming from?

#
Python 3.8.5 (default, Sep  5 2020, 10:50:12)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.18.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: del __builtins__

In [2]: del ().__class__.__base__.__subclasses__()[80].acquire.__globals__['sys'].modules['builtins']

In [3]: print
Out[3]: <function print>```Seems to work for me.
#

Probably an IPython thing.

next flame
#
>>> del __builtins__
>>> del ().__class__.__base__.__subclasses__()[80].acquire.__globals__['sys'].modules['builtins']
>>> print
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: lost builtins module
>>> print
<built-in function print>
#

@sick hound

snow beacon
#
del __builtins__
globals()["__builtins__"].clear()
sick hound
#

@next flame does it automatically recover from that?

next flame
#

yeah

snow beacon
#

We might need to keep the module around, just delete its contents.

#

I think that's what the globals()["__builtins__"].clear() thing does.

#

The problem is that most of the important classes are still in memory.

candid wraith
#
def z(s, y):
  return ''.join([chr(ord(x) + y) for x in s])

def g(s):
  return getattr(__builtins__, z(s, 1), 2)

def a(j, f):
  return g("fds`ssq")(j, f)

def d(o):
  return a(__import__(z("a`rd53", 1)), z("^20`a_k`a", 4))(o).decode("utf-8")

x = (g("hmots")(d("SG93IG11Y2ggd291bGQgeW91IGxpa2UgbWUgdG8gY291bnQgdXAgdG8/IA==")))
g(d("b3FobXM="))(a(', ', 'join')([g("rsq")(x) for x in g('q`mfd')(g("hms")(x))]))```
#

as you can see, I write only the cleanest of code

formal sandal
#

I didn't give much thought to that, but might be a good idea to run code from esoteric-python in some isolated environment because you don't always know what is actually executed 😛

cloud garden
#

!e

А = 0
print(A)
night quarryBOT
#

@cloud garden :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | NameError: name 'A' is not defined
snow beacon
#

Unicode shenanigans, I presume?

twilit grotto
#

!charinfo А

night quarryBOT
twilit grotto
#

!charinfo A

night quarryBOT
twilit grotto
#

hmmmmmmmmmm

formal sandal
#

!e

Truе = False
print(Truе)
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

False
formal sandal
#

@twilit grotto yes, this joke is literally a billion years old

twilit grotto
#

I guess I'm not cool enough

sick hound
#

wait

#

you can reassign built in shit like that

#

nasty

formal sandal
#

@twilit grotto all the cool kids already know the cyrillic alphabet by heart lemon_unamused

#

@sick hound nah, you can't redefine

True
False
None
sick hound
#

ah

formal sandal
#

I just replaced one letter with a cyrillic one

sick hound
#
>>> import random
>>> 
>>> def true():
...     if random.randint(0, 1) == 1:
...             return True
...     return False
... 
>>> true()
True
>>> true()
False
>>> 
#

if only that could be capitalized

#

and you defenitly could make that smaller

formal sandal
#

Well, I'm afraid you can't overwrite True's data because it's in a read-only memory section

sick hound
#

big sad

rugged sparrow
#

@formal sandal not if you use memprotect to change that

formal sandal
#

huh?

#

ohhhh

#

huhhh

#

you mean mprotect it seems

#

never heard of it

rugged sparrow
#

the mprotect Linux syscall and the virtualprotect func on windows

#

I just call both memprotect

formal sandal
#

oh, well, sorry for nitpicking, that's just what google showed me

rugged sparrow
#

Nah you're good

#

I might write code tonight that just sets pythons entire address space to rwx to allow for shenanigans

formal sandal
#

So you'll have to write a C extension, right?

rugged sparrow
#

Nope

#

Ctypes will do it

#

Cause I can just get a handle to libc for Linux then call mprotect

#

On windows I can just use windll

formal sandal
#

right

#

BuT cHiLaXaN tHaT'S iMpLeMeNtAtIoN-sPeCiFiC iT wOnT wOrK oN pYpY

rugged sparrow
#

Pypy doesn't expose any Internal C?

#

Even indirectly?

formal sandal
#

idk

#

anyway, that wasn't a serious objects, of course

jovial lynx
#

print('hi guys')

rugged sparrow
#

@formal sandal True isnt a protected memory region

formal sandal
#

huh?

#

It's at 0xaf9560 for me, isn't that protected?

rugged sparrow
#

!e py from ctypes import * import sys (c_char*sys.getsizeof(True)).from_address(id(True))[:] = b'\x00' * sys.getsizeof(True) #wipe the memory of the object print(True) #segfault

night quarryBOT
#

@rugged sparrow :warning: Your eval job has completed with return code 139 (SIGSEGV).

[No output]
formal sandal
#

welp

rugged sparrow
#

¯_(ツ)_/¯

#

maybe it is on windows

formal sandal
#

I'm pretty sure snekbox is on linux

rugged sparrow
#

!e print(hex(id(True)))

night quarryBOT
#

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

0x7f90fe271540
formal sandal
#

wtf

rugged sparrow
#

!e import ctypes;print(ctypes.sizeof(ctypes.c_ssize_t()))

night quarryBOT
#

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

8
half sigil
#
def solution(a, b, k):
    if a == b: return 1
    y = (int(i,35) % 2 for i in(a,b))
    if len(set(y)) < 2:
        l = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
        d = 1 if abs(int(a[1]) - int(b[1])) == abs(l.index(a[0]) - l.index(b[0])) else 2
        return d <= k
    return 0

anybody know if i can make my code faster? i'm trying to see if a bishop in position a can reach to position b in k moves. the input for a and b will be in this format "a1" (so basically column letter and then the number of the square the bishop is in). and k will be an int

formal sandal
snow beacon
#

& 1 is almost always going to be faster than % 2.

#

Also, you may want to use a dictionary rather than using .index so much.

#

You can also split y into two parts and do y1 != y2 rather than converting to a set and taking the length.

wind karma
#

The bot uses Linux

half sigil
#

@snow beacon thanks dude!

sick hound
restive void
#

I recently discovered the unpack-single-element-in-sequence "operator" ,= (foo ,= [23]; assert foo == 23 ). Are there any other things in this category? (things that look like seperate operators or similar concepts, but are just quirks, or based on intentional misformatting, etc.)

formal sandal
#

😄

#

yes, it's the "pistol operator"

#

I don't know anything like that, but I could search

#

There's also "custom operator" syntax:

#
hello <div> world

this is parsed as hello < div > world and will be evaluated as hello < div and div > world

#

but this will break down because of chained comparison stuff

#

So hello @div@ world or hello +div+ world also work

#

Also this:

def f():
    x <- getLine
    y <- getLine
    putStrLn (x ++ ", " ++ y)
    return ()

^ valid Python syntax (although... might be hard to implement, definitely would require screwing with ctypes)

main = do
    x <- getLine
    y <- getLine
    putStrLn (x ++ ", " ++ y)
    return ()

^ valid Haskell, actually works

#

@restive void

#

so I guess <-, ++ and -- count.

earnest wing
#

call @me

#

You can also do some interesting "operator" mashing with _

#

<=_=>, -_._-, ++_++

formal sandal
#

I wrote an entire story in a different channel

earnest wing
#

Don't forget the dumbbell clear operator:

x = [a for a in range(10)]
x [:]=[]
assert x == []
formal sandal
#

maybe I can find it

#
letter ,= xs  
"you better give me your element, xs"
"or else..."


ys ;x//=         H==i, xs
                 "return my element. right now."
ys ;x//=          H==i,   xs
ys ;x//=K<        H==i,   xs
ys ;x//= -        H==i,   xs
ys ;x//=   -      H==i,   xs
ys ;x//=      -   H==i,   xs
ys ;x//=          H==i,   xs
ys ;x//=          H==i, - xs
ys ;x//=          H==i,   # xs


ys ;x//=          H==i,   # xs
"never"


ys**(z,)
ys**(z, z)
ys**(z, z, z)
ys**(z,)
ys**(z, z)                  ,Xs 
ys**(z, z, z)       ,Xs 
ys**(z,)       ,Xs 
ys**(z, z,)  ,Xs 
ys**(z, z, z),X . s 
ys           ,t- Xs
ys   ,t- Xs 
ys ,t-Xs 
t<ys<---Xs
   t<ys<Xs 
        Xs -t, # ys
        Xs -t,    # ys
        Xs -t,       # ys

        Xs -t,       # ys
    "that's for my brother"
#

all valid python syntax

#

except for some indents

wanton tundra
#

is that assembly but in python

sick hound
#

@wanton tundra

formal sandal
#

@wanton tundra Nah, you can do "assembly but in python" by writing directly in CPython bytecode

wanton tundra
#

just what i would expect from this channel

formal sandal
#

So you know how in Scratch or similar visual programming tools blocks with different purposes have ports with different shape. But what if a language had a full-blown type system based around block shapes? For example, you could combine basic types to make compound types:

#

And, perhaps, this system could be operated with physical objects as a fun educational tool

#

However, this might have problems with physical representation because of generic types.
For simple stuff, you can make a type into which you can insert a special "type peg":

#

But this will not work on generic functions like map : (A -> B) -> List[A] -> List[B] or first : Pair[A, B] -> A.

#

Anyhow, this might be a fun language to implement in Python.

#

Like Scratch, but with an artificially overcomplicated type system.

#

Although implementing it physically would be more fun: instead of throwing an exception you could simply explode a block

#

That's the idea 🙂

proper vault
#

@formal sandal ev3 codeblocks do this

restive void
#

@formal sandal I'm pretty sure your example can be done without using ctypes, just by implementing some dunder methods. But cool ideas!

crude kelp
#

ev3 codeblocks do this
Sorta doubt this

rugged sparrow
#

@restive void but if you used ctypes you wouldn't have needed to use neg or O

restive void
#

@rugged sparrow how so? I need some way to say "evaluate now", don't I?

formal sandal
#

@restive void No, ctypes will be needed. Because you can't apply unary plus to strings.

rugged sparrow
#

You could look at the current frame for the context to know when to exec

heavy mango
next flame
#

Interesting, but not really a good fit for this channel

#

This channel is for weird python stuff @heavy mango

snow beacon
#

Did a message here just disappear or am I going mad?

#

Anyway, what's an obfuscated method to concatenate two lists?

proper vault
#
concat=lambda x,y: [
   x
   for x in [x[:]]
   for yv in [[y]]
   for _ in y
   for a,*b in yv
   for _ in [x.append(a)]
   for yv[0] in [b]
][-1]```
bronze oracle
#

I don't get the main topic of this channel-

formal sandal
#

It's for weird stuff

#

like the last snippet ^

bronze oracle
#

._. yeah seemed very weird

distant wave
#

@constant_singleton()
class THISThreadManagerTYPE1999:
  pass

print(THIS_THREAD_MANAGER_TYPE_1999)
#

Just wrote a new decorator

#

plays hell with ide inference though

formal sandal
#
constant_singleton = lambda f: f()
```?
#

@distant wave

distant wave
#

Well, note that it changes the name

#

THISThreadManagerTYPE1999 -> THIS_THREAD_MANAGER_TYPE_1999

#

Also takes *args/**kwargs, but yeah

#

using

re.compile(r"([A-Z][a-z]+)|([0-9]+)")
#

for the conversion

formal sandal
#

oh, didn't notice

#

cool

distant wave
#

it matches like this

formal sandal
#

but why not write the name in SCREAMING_SNAKE_CASE in the first place? 🙂

distant wave
#

the trick is to use it with re.split

#

Because it feels really weird to write

#
class THREAD_MANAGER:
formal sandal
#

well, it will give proper typechecker support 🙂

#
def constant_singleton(cls: Type[T]) -> T:
    ...
distant wave
#

this is true

formal sandal
#

and the conversion is not that obvious tbh

#

"where the hell does THREAD_MANAGER come from???"

distant wave
#

I actually found doing the typevar annotation confused my editor more than not

#

This is true

formal sandal
#

huh?

#

maybe you used TypeVar instead of Type?

distant wave
#

Well, how else to get T?

#
T = TypeVar("T")
def singleton(cls: Type[T]) -> T:
#

except it's more awkward because it's got an outer wrapper to pass in arguments

#
def singleton(*args, **kwargs) -> Callable:
  T = TypeVar("T")
  def wrap(cls: Type[T]) -> T:
    return cls(*args, **kwargs)
  return wrap
#

Or does TypeVar go on the outside here?

#

I'm pretty sure mypy or similar actually check globals, so that might break things

formal sandal
#

I'm pretty sure it goes outside

#

I think your editor doesn't like it because Callable is too broad (do the inner type annotations even matter?

distant wave
#

Not sure, but I don't want them absent

#

Yeah, I should be more specific there

formal sandal
distant wave
#

perfect, thanks

formal sandal
#

So I don't need to repeat the annotation

distant wave
#

yeah, same here

formal sandal
distant wave
#

@formal sandal not to bother you, but do you know of a way to assert matching type signatures for functions

formal sandal
#

can you show an example?

distant wave
#

This:

#
import typing
def precall(
    func: typing.Callable[[],
    typing.Any],
) -> typing.Callable[
    [typing.Callable[T, R]],
    typing.Callable[T, R],
]:
  pass
#

it accepts a function (A), and returns a function (B) that accepts another function (C), and returns a function with the same type signature as C

formal sandal
#

WIP

distant wave
#

ty

formal sandal
#

wait

distant wave
#

That's precisely what I'm looking for

formal sandal
#

If it's A -> (B -> (C -> C)), then you can make a type variable that is bound to Callable

distant wave
#

oh, true

#

that only helps for two of these 14ish functions though lol

formal sandal
#
import typing

C = typing.TypeVar("C", bound=typing.Callable)

def precall(
    func: typing.Callable[[],
    typing.Any],
) -> typing.Callable[[C], C]:
    pass
#

or maybe you need to use abc.Callable, i don't remember

#

maybe we need a new channel for gradual typing 🤔

distant wave
#

ParamSpec can't really save me

#

also this is probably wrong, but not too far off, I hope:

#
P = typing.ParamSpec("P")
W = typing.ParamSpec("W")
WR = typing.TypeVar("WR")
def meta_precall(
    *args: P.args,
    **kwargs: P.kwargs,
) -> typing.Callable[
        [[typing.Callable[typing.Concatenate[Tuple[W.args], P.args, Dict[W.kwargs], P.kwargs]],
        bool,
    ],
    typing.Callable[
        [typing.Callable[W, WR],
        WR,
    ],
]:
    ...
thin trout
#

You make me sad

sick hound
#
from functools import reduce;_,o=map(int,input().split()),input();exec(f"print(reduce(lambda x,y:x{o}y,_))")

#

One line calculator with multiple arguments

#

Don't know how I can get any smaller than this

stark fable
#
import functools as f;_,o=map(int,input().split()),input();exec(f"print(f.reduce(lambda x,y:x{o}y,_))")```
#

@sick hound

#

i tried every variant import i could think of and that was the shortest overall py from functools import reduce;_,o=map(int,input().split()),input();exec(f"print(reduce(lambda x,y:x{o}y,_))") from functools import reduce as r;_,o=map(int,input().split()),input();exec(f"print(r(lambda x,y:x{o}y,_))") import functools;_,o=map(int,input().split()),input();exec(f"print(functools.reduce(lambda x,y:x{o}y,_))") import functools as f;_,o=map(int,input().split()),input();exec(f"print(f.reduce(lambda x,y:x{o}y,_))")

sick hound
#

Ah, that f there shortened the code

#

Interesting, didn’t think of it

stark fable
#

you can shorten it a bit more if you're ok with flipping around the order that things need to be inputted py import functools as f;o=input();exec(f"print(f.reduce(lambda x,y:x{o}y,map(int,input().split())))")

sick hound
#

Woah

#

Damn

#

Wait, can we have input inside f-string

#

Can’t try it right now, don’t have my laptop or computer

#

I’ll try it later I guess

stark fable
#

oh, yep, that makes it even shorter actually py import functools as f;exec(f"print(f.reduce(lambda x,y:x{input()}y,map(int,input().split())))")

proper vault
#
print(eval(input().join(input().split())))
``` if you are ok with flipping the order
sick hound
#

Wait

#

LOL

#

I never thought of that

stark fable
#

good point yeah that works

dense marlin
#

Hi, can someone explain why I can't do def f(n): return eval('all(n % i != 0 for i in [2,3,5])') to get a function that returns that n is not divisible by 2, 3 or 5? When I do f(10) I get "NameError: name 'n' is not defined". However def g(n): return eval('n > 10') works fine to define a function that returns that n is greater than 10 and so g(10) returns False
And yes I explicitly want to use eval since I actually need to evaluate user provided strings

formal sandal
#

Use dis.dis and compile to inspect the produced bytecode.

#
  1           0 LOAD_NAME                0 (all)
              2 LOAD_CONST               0 (<code object <genexpr> at 0x7f46f61c2030, file "4234234", line 1>)
              4 LOAD_CONST               1 ('<genexpr>')
              6 MAKE_FUNCTION            0
              8 LOAD_CONST               2 ((2, 3, 5))
             10 GET_ITER
             12 CALL_FUNCTION            1
             14 CALL_FUNCTION            1
             16 RETURN_VALUE

Disassembly of <code object <genexpr> at 0x7f46f61c2030, file "4234234", line 1>:
  1           0 LOAD_FAST                0 (.0)
        >>    2 FOR_ITER                18 (to 22)
              4 STORE_FAST               1 (i)
              6 LOAD_GLOBAL              0 (n)
              8 LOAD_FAST                1 (i)
             10 BINARY_MODULO
             12 LOAD_CONST               0 (0)
             14 COMPARE_OP               3 (!=)
             16 YIELD_VALUE
             18 POP_TOP
             20 JUMP_ABSOLUTE            2
        >>   22 LOAD_CONST               1 (None)
             24 RETURN_VALUE
#

vs

  1           0 LOAD_NAME                0 (n)
              2 LOAD_CONST               0 (0)
              4 COMPARE_OP               2 (==)
              6 JUMP_IF_TRUE_OR_POP     18
              8 LOAD_NAME                1 (h)
             10 LOAD_NAME                0 (n)
             12 LOAD_CONST               1 (1)
             14 BINARY_SUBTRACT
             16 CALL_FUNCTION            1
        >>   18 RETURN_VALUE
#

Apparently, the names in the outermost scope are looked up using LOAD_NAME because the scope can't really be resolved at runtime.

next flame
#

@dense marlin holup

#

user provided strings?

#

being evaled?

formal sandal
#

@dense marlin By 'user-provided' you mean that
a) responsible owner of the machine will type in the strings; or
b) random person will send the string via an HTTP request?

#

Well, as you can see, a generator expression is actually a function call, and accessing n happens inside the body of that function, and it decided that it's actually a global variable. You can pass n together with the globals dict (using a ChainMap, for example).

#

!d eval

night quarryBOT
#
eval(expression[, globals[, locals]])```
The arguments are a string and optional globals and locals. If provided, *globals* must be a dictionary. If provided, *locals* can be any mapping object.... [read more](https://docs.python.org/3/library/functions.html#eval)
formal sandal
#

I don't know if you can use a ChainMap here 🤔

proper vault
#

You can do ```py
eval('lambda n=n:...')()

#

Also, if all you need are built ins rather than globals, you can just pass a dict literal as global

dense marlin
#

@next flame @formal sandal a) "responsible owner of the machine will type in the strings"

dapper parrot
#

it's extremely unlikely that you actually need to use eval

calm orchid
#

can someone tell me how to make a code in python a window i can access and use?

snow beacon
#

Someone in one of the help channels will be able to.

sick hound
#

What this channel about?

half sigil
#

general python

sick hound
#

Huh

twilit grotto
#

it's not really for general python

#

it's for weird weird stuff you can do with python

sick hound
#

Oh nice

#

For master python?

#

Like lambda stuff

half sigil
#

like asking how to make your code shorter and shiz

#
testing1=lambda n:n*(x:=len(str(n)))-int('1'*x)

any clue how i can shorten this or make it faster?

sick hound
#

Hmmm

half sigil
#

now don't clutter up the chat so ppl can see this @sick hound please ❤️

formal sandal
#

@half sigil I'm not sure plus is cluttering the chat with a single message. Two concurrent conversations in a topical chat are fine.

half sigil
#

oop-

#

its a joke

#

lmao

snow beacon
#

Oh, ha, let me try: izzy, don't clutter up the chat with jokes. We are a very serious channel doing very serious code for serious people.

half sigil
#

okay?

snow beacon
#

(A joke.)

formal sandal
#

@snow beacon Stop cluttering this chat with telling other people not to clutter the chat. We will lose all hope of seeing the question again 🙀

half sigil
#
testing1=lambda n:n*(x:=len(str(n)))-int('1'*x)

any clue how i can shorten this or make it faster?

sick hound
#

@half sigil It seems like you're trying to take in a number, multiply it by its length, then subtract the int of '1'*len_of_num

#

And then it gives some random number?

#

What is this supposed to do

#

If you tell us about what it's supposed to do, someone will probably try to find a better way of doing it

half sigil
#

nothing really

#

just a small challenge

formal sandal
#

making it shorter and making it faster are orthogonal and often contradicting goals

half sigil
#

lmao

#

either one is fine by me

sick hound
#

@half sigil Had nothing to do, so I searched up time complexities of type conversions in python

#

I'll have to look more into source code, but str to int and vice-versa takes O(n^2) Not right, ignore everything below. Got the wrong info

#
int('1'*x)
#

And there's a better way of doing this

#

Since it's just 11111s

#
1 = 10**0
11 = 10**1 + 10**0
111 = 10**2 + 10**1 + 10**0
1111 = 10**3 + 10**2 + 10**1 + 10**0  
#

You can notice this pattern

#

We can just use a quick for loop for this

#
def ret1p(n):
    cur = 0
    for i in range(n):
        cur += pow(10, i)
    return cur
#

I used pow here since apparently, it uses fast exponentiation

#

And I was too lazy to implement it myself

#

Then we can also replace this

#
len(str(n)))
#

You're just trying to find the amount of digits in the number

#

Wait a second

#

Hold up

#

I just thought of something

snow beacon
#

It might be faster to do py def ret1p(n): cur = 0 for _ in range(n): cur *= 10 cur += 1 return cur

zealous widget
#

you can use log to find number of digits

sick hound
#

YEah I just thought of that

#

log10

#

Trying to see what the time complexity of math.log is

zealous widget
#

you might not get faster than just doing a number of integer divisions of 10

#

which is O(log n), but not a lot of overhead

sick hound
#

Hm

#

What I wrote, actually slowed it down even more

#

That's interesting

zealous widget
#

i think the complexity of log is probably in that ballpark for arbitrary reals

sick hound
#
from time import time
from math import floor, log

def decorator(func):
    def wrapper(*args, **kwargs):
        times = []
        for _ in range(10):
            start = time(); func(*args, **kwargs); end = time()
            times.append(end - start) 

        print(func.__name__, sum(times)/len(times))
    return wrapper

def ret1p(n):
    cur = 0
    for i in range(n):
        cur += pow(10, i)
    return cur

def int_len(n):
  return floor(log(n, 10)+1)

@decorator
def original(n):
  return n*(x := len(str(n))) - int('1' * x)

@decorator
def optimized(n):
  return n*(x := len(str(n))) - ret1p(x)

n = 234923479837459887234742743723478

original(n)
optimized(n)

snow beacon
#

Calling Python functions is quite expensive.

#

str int probably uses C code.

zealous widget
#

you didn't call int_len

sick hound
#

Both are using functions, so it doesn't really matter

#

Even with it

#

It's quite a bit slower

#

That's surprising

#

Maybe conversions aren't O(n^2)

zealous widget
#

I'm not sure why they would be

sick hound
#

Let me just check conversion source code

#

That stack overflow post with 2 likes

snow beacon
#

Python is open-source.

sick hound
#

Wait a second

#

Ah man

#

When I asked people here in the server to confirm if conversions were O(n^2), no one replied

#

Seems like I was building code on the wrong premise

#

Oh well

#

Makes sense

zealous widget
#

In [5]: def naive_log(n):
   ...:     digits = 0
   ...:     while n:
   ...:         digits += 1
   ...:         n //= 10
   ...:     return digits
   ...:

In [7]: def smart_log(n):
   ...:     return int(log(n, 10)) + 1
   ...:

In [8]: %%timeit
   ...: naive_log(267624335836053506)
   ...:
1.77 µs ± 108 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [10]: %%timeit
    ...: smart_log(267624335836053506)
    ...:
441 ns ± 1.46 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
sick hound
#

Holy

snow beacon
#

Asymptotic complexity doesn't matter when one part is C and one is Python.

#

The constant factors are important.

sick hound
#

Jupyter has in-built timeit?

zealous widget
#

yep

#

ipython does anyway

#

also can run cython inline

sick hound
#

Wondering how I can implement chess pieces’ movements in as little bit of text as possible. Maybe I’ll try that tomorrow

snow beacon
#

Izzy was looking into esoteric code for bishop movement recently.

half sigil
#

yeye

rugged sparrow
#

anyone here know how to declare a struct using ctypes that would map to the following c structure

typedef struct {
  MyObj *item[]; //length is `size`
  long size;
} MyStruct
``` where `*item[]`'s length depends on `size` and `size` can change
#

does ctypes have any way of handling elements that can change size?

sick hound
proper vault
next flame
#

isnt the c convention for variable length arrays in structs to put the size first

proper vault
#

you have the

struct A {
  long size;
  char * a[];
};```syntax
rugged sparrow
proper vault
#

C cannot have structs with inconsistent size without that syntax. So I would expect neither can CTypes and you have to deal with raw pointers

rugged sparrow
#

i was able to do py class ListStruct(Structure): _fields_ = [ *PyObject_VarHead, ('ob_item', POINTER(py_object)), ('allocated', c_ssize_t) ]

#

but it doesnt have the safety of treating ob_item as an array

#

maybe i could customize how ob_item was accessed to add that

proper vault
#

you cannot get that safety in C afaik, so I would be surprised if python could

rugged sparrow
#

!e ```py
from ctypes import *
PyObject_Head = [
('ob_refcnt', c_ssize_t),
('ob_type', py_object)
]

PyObject_VarHead = [
*PyObject_Head,
('ob_size', c_ssize_t)
]

class ListStruct(Structure):
fields = [
*PyObject_VarHead,
('ob_item', POINTER(py_object)),
('allocated', c_ssize_t)
]

x = [1]
ListStruct.from_address(id(x)).ob_item[0] = 2
print(x)
print(ListStruct.from_address(id(x)).allocated)

night quarryBOT
#

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

001 | [2]
002 | 1
sick hound
#

This guy's blog is esoteric heaven

#
q = lambda l,s,e:s<e and (lambda p:(q(l,s,p-1),q(l,p+1,e)))((lambda o=[l[e],s-1,e,0,0,0,0,0,0]:\
    (o.__setitem__(6,lambda: (o.__setitem__(4,0),o.__setitem__(5,lambda:(not o[4] and not o[3])\
    and ((lambda:(o.__setitem__(1,o[1]+1),(o[1]==o[2]) and (o.__setitem__(3,1),o.__setitem__(4,\
    1)) or (l[o[1]]>o[0] and (l.__setitem__(o[2],l[o[1]]),o.__setitem__(4,1)))))(),o[5]())),\
    o[5]())),o.__setitem__(7,lambda:(o.__setitem__(4,0),o.__setitem__(5,lambda:(not o[4] and\
    not o[3]) and (o.__setitem__(2,o[2]-1),(o[2]==o[1]) and (o.__setitem__(3,1),o.__setitem__\
    (4,1)) or (l[o[2]]<o[0] and (l.__setitem__(o[1],l[o[2]]),o.__setitem__(4,1))),o[5]())),\
    o[5]())),o.__setitem__(8,lambda:not o[3] and (o[6](),o[7](),o[8]())),o[8](),l.__setitem__(\
    o[2],o[0]),o[2])[-1])())

quicksort = q
#

Never seen something this scary in python

half sigil
#

how many lambda's is that lmfao

snow beacon
#

Nine, it looks to be.

sick hound
#

good god

minor grove
#

hey guys i am kinda new to this dose annyone wanna help me out with learning this a bit better?

snow beacon
#

What do you mean by 'this'?

still solstice
#

!warn @still solstice

#

I just caught my brother messing with the voice call!

sick hound
#

Is that all one godless line?

snow beacon
#

There's enough of god in the λ-calculus.

sick hound
#

That's quicksort in 1 line

odd canyon
#

my sleep paralysis demon

elfin onyx
#

Who made sort in one line?

odd canyon
elfin onyx
#

i don't understand anything that's happening there lol

snow beacon
#

Python 3.9 lets you use arbitrary expressions as decorators.

earnest wing
#

I'm sure that won't lead to any confusing esoteric code at all.

#

Here's my proposal for parser combinators using decorator expressions:

@one_of("0123456789")[4]
def discrim(digits: str) -> int: # annotations for convenience
  return int(digits)
  
@none_of(" \n\r\t")[1:] - sym("#") + discrim()
def discord_user(name: str, discrim: int):
   ...
#

I don't know the exact rules for usernames but you get the gist

formal sandal
#

does the new decorator syntax support multiline expressions as decorators?

thin trout
#

Yup!

#

Well, inside some parenthesis or so

sour quiver
#

Hi ! I'm sorry i'm new to the server, what is esoteric python?

thin trout
#

Everything you wouldn’t want to see in python

#

Just give it a little scroll up lemon_pleased

formal sandal
#

Everything you wouldn’t want to see in python
I wouldn't want to see mandated docstrings, yet that's not esoteric! @thin trout

thin trout
#

lol

#

you’ll thank yourself later they said

formal sandal
#

wdym?

#

thank yourself for mandated docstrings?

thin trout
#

About putting docstrings everywhere

#

Yeah

formal sandal
#
class ByOneIncrementer
{
    public:
    static int incrementByOne(int numberToIncrementByOne) const
    /*
     * @param int numberToIncrementByOne The number to increment by HOST_CELLS_PER_PIXEL
     * @return int the decremented number
     *
     * Increment the `numberToIncrementByOne` by $loc{ en:one | de:ein | fr:un | ru:один } and return
     * the incremented `numberToIncrementByOne`.
     */
    {
        const int numberToIncrementByOneIncrementedByOne = numberToIncrementByOne - 1; 
        Logger::getLogger("root").debug("Incrementing %d by %d", numberToIncrementByOne, 3);
        Postgres::execute("DROP TABLE students;");
        return numberToIncrementByOne;
    }
};
thin trout
#

What is little boby table doing in here

formal sandal
#

fixed

distant wave
#

!e ```py
a = {}
a[1] = a
print(a)
print(eval("a" + "[1]"*2000))

#

daw

night quarryBOT
#

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

001 | {1: {...}}
002 | {1: {...}}
distant wave
#

@flat crown

#

its somewhere over 2000

#

hm

#

!e ```py
import sys
sys.setrecursionlimit(9009)
a = {}
a[1] = a
print(a)
print(eval("a" + "[1]"*9001))

flat crown
#

what is esoteric python

night quarryBOT
#

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

001 | {1: {...}}
002 | {1: {...}}
distant wave
#

its over 9000 dictionary accesses lol

flat crown
#

bruhhhh

distant wave
#

Golfing, Python VM languages, obfuscation, code gore and other general Python weirdness

(lambda: "esoteric python")()

flat crown
#

code gore?

distant wave
#

that's more art

#

but yeah

flat crown
#

ty

lusty marsh
#

wasnt there someone who did quicksort in one line with a shit ton of lambdas

distant wave
#

One I wrote myself

#

P = typing.ParamSpec("P")
W = typing.ParamSpec("W")
WR = typing.TypeVar("WR")
def meta_precall(
    *args: P.args,
    **kwargs: P.kwargs,
) -> typing.Callable[
        [[typing.Callable[typing.Concatenate[Tuple[W.args], P.args, Dict[W.kwargs], P.kwargs]],
        bool,
    ],
    typing.Callable[
        [typing.Callable[W, WR],
        WR,
    ],
]:
    ...
#

It's a triple decorator's type signature

#

or this, for recovering from an erased__builtins__

thin trout
#

The second one isn't esoteric, it is just too much typing haha

formal sandal
#

both the typing typing and the typing typing

sick hound
#

Can this code be made even a incey wincey smaller?

a=lambda x:[i for i in x if i%2]
calm quest
#

interesting way to filter out the even numbers, and leave odd ones

sick hound
#

No, that's the smallest you can get

#

Wait

#

Oh wait

#

@sick hound Are you trying to get the even numbers?

#

Because that gives the odd numbers

#

You have to do

#
a=lambda x:[i for i in x if i%2==0]
#

To get even numbers

next flame
#

you can save a char with i%2-1

sick hound
#

Wait what

#

Ah

#

Got it

#

That's a nice trick, never came to my mind

proper vault
#

if you do ~i%2it should work better as you can skip the space after if

formal sandal
#
i^1
#

Oh, wait, no

vestal solstice
#

don't golf individual parts

#

it all should rely on each other

#

e.g. if you're always using it as a(x): you could do a=lambda:[i for i in x if i%2] and a() saving 3 chars

formal sandal
#

makes sense

sick hound
#

@sick hound No i was trying to get the odd numbers itself

marsh void
#

~i&1 ideally should be faster o.o

grizzled cloak
#

iirc it isnt

#

i think we tested this at some point

#

or was it faster?

marsh void
#

I don’t think it was, yeah

cloud garden
#

what does ~ do?

steep mural
#

-x-1 I'm pretty sure

fervent sonnet
#

@cloud garden it inverts the bits

#

it's a unary operator

marsh void
#

good example of its usage is subtraction, since x - y is really x + (~y + 1)

sick hound
#

Good resources

cloud garden
#

Thank you

alpine flower
#

good example of its usage is subtraction, since x - y is really x + (~y + 1)
so is x + (~y) the same as x + -(y + 1)?

thin trout
#

I think so, but I’m not 100% sure

#

It is about the two’s complement

marsh void
#

yes, it is

cloud garden
#
while condition or next(iter([1, 0])):
    ...

make a condition True one more time in a while loop

twilit grotto
#

while do

steep crest
#

interesting

stark fable
#

that doesn't actually work though

formal sandal
#

right, next(iter([1, 0])) is always 1

steep crest
#

I take that back, not interesting at all

rugged sparrow
#

!e ```py
condition = True
l = [0,1]
while condition or l.pop():
print('a')
condition = False

night quarryBOT
#

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

001 | a
002 | a
rugged sparrow
#

that works

twilit grotto
#

well that's because pop returns 1

#

in this case

twin reef
#

!e

condition = True
true_condition = True
while (condition := not condition) or true_condition:
  print("hi")
  true_condition = False
night quarryBOT
#

@twin reef :white_check_mark: Your eval job has completed with return code 0.

001 | hi
002 | hi
twin reef
#

That works too

sick hound
#

hi

grave rover
#

Found an awesome challenge over at HackTheBox, and I think you guys would enjoy it
The goal is to find a string in format HTB{some_string} on http://165.232.106.154:32169/
Good luck y'all

grave rover
grave rover
last locust
#

If you wanna do a more "traditional" obfuscator you could use lambdas instead

#

Would convert those 4 lines into 1

#

@grave rover

grave rover
#

that's the goal eventually

sick hound
tribal moon
#

cool project

#

outdated though

steep mural
#

Interesting

molten egret
#

Anyone knows how to use Pygments to make a lexer. I'm confused.

grave rover
#

btw if anyone wants to help with this obfuscator, let me know

grave rover
#

next up: for loops and while loops

#

aaaaa

grave rover
formal sandal
#

But how do you emulate raising exceptions?

rugged sparrow
#

(()for()in()).throw(exc)

#

that should work for raise exc (although it does add one to the stacktrace depth so programs that depend on their stacktrace depth wouldnt work right)

#

@grave rover lmk when you get to try:except i have a couple lambda patterns that could be adapted

formal sandal
#

ohh

#

smart

#
(0for()in()).throw(exc)
#

I character shorter 😄