#esoteric-python

1 messages · Page 22 of 1

sly ibex
#

i want you be my friend

meager zinc
sly ibex
#

would you like clash of code in shorten mode? i want to learn golf

meager zinc
#

sure I can help you golf

#

so you want to find the max?

meager zinc
sly ibex
#

i think i sended it too fast

meager zinc
#

thats okay

sly ibex
#

when you finish press "show code"

#

to see your code

meager zinc
#

mhmm

#

yours could be slightly shorter

sly ibex
#

yeah???

meager zinc
#
print(hex(int(input(),2)))
sly ibex
#

fk!!!

meager zinc
#

dw I submitted a longer one

sly ibex
#

you are right

#

again?

meager zinc
#

sure

sly ibex
#

niceee

meager zinc
#

can you try picking a harder one

sly ibex
meager zinc
#

oh I see

#

ok after this im gonna eat dinner

sly ibex
#

yeah sure

#

press "show code"

#

mine

#
c=input()
for i in input().split():
    if int(i)%2:
        print("[x]",i)
    else:
        print("[ ]",i)```
#

i can't to see yours 😦

meager zinc
#
j=input;j()
for i in j().split():print('['+' x'[int(i)%2]+']',i)
sly ibex
#

ª

sly ibex
rugged sparrow
#

You can do either, globally would depend on the operator and what behavior your goal is to evoke

#

What operator are you trying to hook?

#

You can use fishhook.hook and loop over all types to hook the operators there, or you can use fishhook.asm.hook on the C functions (Unix x86 only rn)

#

!e ```py
from fishhook import *

@hook(type)
def init(*args, **kwargs):
print(args, kwargs)
return orig(*args, **kwargs)

class A:pass
class B(type):pass
``` you can hook type.__init__ to apply hooks late

night quarryBOT
#

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

001 | (<class '__main__.A'>, 'A', (), {'__module__': '__main__', '__qualname__': 'A'}) {}
002 | (<class '__main__.B'>, 'B', (<class 'type'>,), {'__module__': '__main__', '__qualname__': 'B'}) {}
rugged sparrow
#

@half escarp ^ that should work along with the initial loop to apply hooks

versed eagle
#

im curious lol

rugged sparrow
#

Metaclass inherits from type, so you apply the hook to all subclasses of type

versed eagle
#

hm that could work yeah

rugged sparrow
#

!e ```py
from fishhook import *

@hook(type)
def init(*args, **kwargs):
print(args, kwargs)
return orig(*args, **kwargs)

class A:pass
class B(type):
def init(*args, **kwargs):
pass # stops inheritance of type.init
class C(metaclass=B):pass

night quarryBOT
#

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

001 | (<class '__main__.A'>, 'A', (), {'__module__': '__main__', '__qualname__': 'A'}) {}
002 | (<class '__main__.B'>, 'B', (<class 'type'>,), {'__module__': '__main__', '__qualname__': 'B', '__init__': <function B.__init__ at 0x7ff35f10efc0>}) {}
rugged sparrow
versed eagle
#

why not, in type.__init__, hook the .__init__ of the created class

rugged sparrow
#

yea

versed eagle
#

to have the desired behaviour

rugged sparrow
#

thats the best way to ensure it

#

also should probably have a flag to check if hooks have been applied to a given class

versed eagle
#

ah yeah

rugged sparrow
#

because if you are applying hooks to metaclasses like that if a given metaclass calls super().__init__(...) in its init then you would double apply hooks

versed eagle
#

mhm

#

can metaclasses control whether or not a class has __slots__?

rugged sparrow
#

maybe through __prepare__

versed eagle
#

i dont remember the features being able to interact very much but now im curious

rugged sparrow
#

ill look into it

versed eagle
#

yep

#

!e

class meta(type):
    def __prepare__(cls, bases):
        return {"__slots__":("test", "test2")}
class thing(metaclass=meta):
    def __init__(self):
        self.test = 1
        self.test2 = 2
        self.test3 = 3
print(thing().test)
night quarryBOT
#

@versed eagle :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 9, in <module>
003 |   File "<string>", line 8, in __init__
004 | AttributeError: 'thing' object has no attribute 'test3'
versed eagle
#

you can

#

using that, you could add a flag slot to every class

#

and then use that to check whether or not something's been hooked already

#

you'd use slots since the dict can be deleted or cleared, but unless someone explicitly modifies the slot it won't be overwritten

rugged sparrow
#

hooking type.__prepare__ does not seem to work however

versed eagle
#

no?

#

that's surprising

rugged sparrow
#

huh

#

what

#

so __prepare__ ran, but the slots added were disregarded

#

even weirder

#

oh right

#

I am an idiot

#

!e ```py
from fishhook import *

@hook(type)
def prepare(cls, bases):
print('here')
return {'slots': ()}

class A:pass

A().a = 1```

night quarryBOT
#

@rugged sparrow :x: Your 3.11 eval job has completed with return code 1.

001 | here
002 | Traceback (most recent call last):
003 |   File "<string>", line 10, in <module>
004 | AttributeError: 'A' object has no attribute 'a'
rugged sparrow
#

ah yea it does work

versed eagle
#

though it should also work on type instances

#

shouldn't it?

#

type(type) is type

rugged sparrow
#

i think that type.__dict__ is added explicitly

versed eagle
#

ah

rugged sparrow
#

so it would ignore slots

versed eagle
#

i wonder if there's a way to remove that after the fact

rugged sparrow
#

not safely

#

its stored explicitly in the typeobject struct tp_dict

versed eagle
#

what if you just make it a NULL ptr

#

does it segfault or does it check for NULL first?

#

im gonna go check that brb

rugged sparrow
#

!e ```py
from fishhook import getmem, find_offset, getdict

class A:pass
A_mem = getmem(A)
A_mem[find_offset(A_mem, id(getdict(A)))] = 0
print(A)
print(A())

night quarryBOT
#

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

[No output]
versed eagle
#

ah

rugged sparrow
#

yea it just segfaults

versed eagle
#

i was hoping that they checked for NULL ptr

rugged sparrow
#

it makes sense that it doesnt

#

tp_dict should never be NULL

versed eagle
#

hm true

cloud garden
#

!e

import time


def benchmark_float(n: int) -> float:
    s = time.time()
    for _ in range(n):
        float(1)
    e = time.time()
    return e - s


def benchmark_divby1(n: int) -> float:
    s = time.time()
    for _ in range(n):
        1 / 1
    e = time.time()
    return e - s


def benchmark_multby1p0(n: int) -> float:
    s = time.time()
    for _ in range(n):
        1 * 1.0
    e = time.time()
    return e - s

print(f"float() conversion: {benchmark_float(10_000_000)}")
print(f"Division by 1: {benchmark_divby1(10_000_000)}")
print(f"Multiplication by 1.0: {benchmark_multby1p0(10_000_000)}")
night quarryBOT
#

@cloud garden :white_check_mark: Your 3.10 eval job has completed with return code 0.

001 | float() conversion: 0.7997469902038574
002 | Division by 1: 0.20440340042114258
003 | Multiplication by 1.0: 0.20499849319458008
meager zinc
#

You should probably use timeit

arctic skiff
night quarryBOT
#

@arctic skiff :white_check_mark: Your 3.11 timeit job has completed with return code 0.

1 loop, best of 5: 691 msec per loop
cloud fossil
#

Oh I didn't know that this command existed

next flame
serene garnet
#

hi

#

can you golf this code?

#
import sys
q=sys.stdin.readline;g=len;o=range;z=list;k=map;v=int;y=zip
w=lambda u,f,l,a:f([[a([k[j:j+l] for k in u[i:i+l]])for j in o(0,g(u),l)]for i in o(0,g(u),l)])
def e(u,r):
 s=[]
 for i in o(2**r):
  for j in y(*u[i]):
   t=[]
   for k in j:t.extend(k)
   s.append(t)
 return s
n,m=k(v,q().split())
u=[z(k(v,q().split()))for _ in o(2**n)]
f=[lambda x:x[::-1],lambda x:[i[::-1]for i in x],lambda x:z(k(z,y(*x[::-1]))),lambda x:z(k(z,y(*x)))[::-1]]
for _ in o(m):a,b=k(v,q().split());r=n-b;l=g(u)//2**r;u=e(w(u,z,l,f[a-1]),r)if a<5 else e(w(u,f[a-5],l,z),r)
for i in u:print(*i)
#

i need it

#

asap

proper vault
#

Why sys.stdin.readline instead of input?

serene garnet
#

it takes too much time

gleaming linden
#

You can do open(0) to read stdin

gleaming linden
low lynx
#

I question the character saving of those builtin assignments

earnest wing
#

the golfing done so far is largely syntactic

#

you've made it shorter using the same (large) algo

versed eagle
quartz wave
versed eagle
#
import sys
q=sys.stdin.readline
o=range
z=list
k=map
w=lambda u,f,l,a:f([[a([k[j:j+l]for k in u[i:i+l]])for j in o(0,len(u),l)]for i in o(0,len(u),l)])
e=lambda u,r:[sum(k,start=[])for i in o(2**r)for j in zip(*u[i])
n,m=k(int,q().split())
u=[z(k(int,q().split()))for _ in o(2**n)]
f=lambda x:x[::-1],lambda x:[i[::-1]for i in x],lambda x:z(k(z,zip(*x[::-1]))),lambda x:z(k(z,zip(*x)))[::-1]
for _ in o(m):a,b=k(int,q().split());r=n-b;l=len(u)//2**r;u=e(w(u,z,l,f[a-1]),r)if a<5 else e(w(u,f[a-5],l,z),r)
for i in u:print(*i)
#

im pretty sure that does the same thing

#

but idk what its meant to do so

#

cant say for sure

serene garnet
#

oh thanks

#

🙂

#

i challenged my friend

gleaming linden
#

what is it supposed to do though?

serene garnet
#

this is the problem:

#

it means

#

...

#

just input a list and

#

do a function

gleaming linden
#

ah

serene garnet
#

and print it

gleaming linden
#

i can read that lmao

gleaming linden
serene garnet
#
# input
3 8
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52 53 54 55 56
57 58 59 60 61 62 63 64
1 1
2 2
3 1
4 2
5 2
6 1
7 1
8 2

# output 
64 63 62 61 60 59 58 57
56 55 54 53 52 51 50 49
48 47 46 45 44 43 42 41
40 39 38 37 36 35 34 33
32 31 30 29 28 27 26 25
24 23 22 21 20 19 18 17
16 15 14 13 12 11 10 9
8 7 6 5 4 3 2 1
#

it's quite complicated

gleaming linden
#

yeah I'm reading it rn

serene garnet
#

do you know korean?

gleaming linden
#

I'm korean

serene garnet
#

this is the address

gleaming linden
#

mhm

quartz wave
gleaming linden
#

wait

#

I'm translating it

serene garnet
#

the non-golfed original code is

import sys
input = sys.stdin.readline

def change(li, r, func):
    l = len(li) // 2**r
    res = []
    for i in range(0, len(li), l):
        temp = []
        for j in range(0, len(li), l):
            temp.append(func([k[j:j+l] for k in li[i:i+l]]))
        res.append(temp)
    return res  
    
def change2(li, r, func):
    l = len(li) // 2**r
    res = []
    for i in range(0, len(li), l):
        temp = []
        for j in range(0, len(li), l):
            temp.append([k[j:j+l] for k in li[i:i+l]])
        res.append(temp)
    return func(res)   

def merge(li, r):
    l = 2**r
    res = []
    for i in range(l):
        for j in zip(*li[i]):
            temp = []
            for k in j:
                temp.extend(k)
            res.append(temp)
    return res

n, m = map(int, input().split())
li = [list(map(int, input().split())) for _ in range(2**n)]

func = [lambda x: x[::-1], lambda x: [i[::-1] for i in x],
        lambda x: list(map(list, zip(*x[::-1]))),
        lambda x: list(map(list, zip(*x)))[::-1]]

for _ in range(m):
    a, b = map(int, input().split())
    r = n-b
    if a <= 4:
        li = merge(change(li, r, func[a-1]), r)
    else:
        li = merge(change2(li, r, func[a-5]), r)

for i in li: print(*i)
#

i tried to code the function with recursions

#

but it took too much time

low lynx
#

can't you just slice the list with odd indices and then slice them with even indices

#

for the 2 case

#

idea is the same for bigger squares I think

#

tho idk what the Korean is saying

serene garnet
#

ill try again, if i have time

#

and i have no time

gleaming linden
#

There is a 2**N x 2**N grid of numbers and 8 operations (described later)

Each operation is performed by splitting the grid into 2**l x 2**l chunks and performing the operation on those chunks

Operations 1-4 are applied within each chunk
operation 1 flips the values in each chunk vertically
operation 2 flips the values in each chunk horizontally
operation 3 rotates the values in each chunk 90 degrees clockwise
operation 4 rotates the values in each chunk 90 degrees counterclockwise
Operations 5-8 are applied on entire chunks (the chunks themselves move, while the values within each chunk remain the same)
operation 5 flips chunks vertically
operation 6 flips chunks horizontally
operation 7 rotates chunks 90 degrees clockwise
operation 8 rotates chunks 90 degrees counterclockwise

Given the grid and a series of operations, output the state of the grid after performing the operations

First line of input contains N and R (1<= N <= 7, 1 <= R <= 1000)

The next 2**N lines contain the grid itself (integers ofc)

The next R lines contain integers k and l (1 <= k <= 8, 0 <= l < N, which means operation k should be applied with chunk size l

low lynx
#

aren't those both just equivalent to rotating the chunk/all the chunks by 180 degrees?

serene garnet
#

no,
Operations 5-8 are applied on entire chunks (**the chunks themselves move, while the values within each chunk remain the same)**

low lynx
#

you rotate each chunk and then you rotate the entire matrix taking each chunk as just an element and not modifying it

serene garnet
#

hmm

#

idk

low lynx
#

operations 1-4 and operations 5-8

#

since flipping both horizontally and vertically is just 180 degree rotation

#

and clockwise and counterclockwise cancel

gleaming linden
#

Different chunk sizes

#

You might run something on chunk size 4x4 then run something else on with chunk size 2x2 for example

serene garnet
low lynx
#

ah

gleaming linden
#

@serene garnet ```py
(N,*),*L=open(0)
N=2**int(N)
u=range
G=[[*map(int,L[x].split())]for x in u(N)]
p=(Q:=lambda g:R(R(R(g))),F:=lambda g:g[::-1],lambda g:Q(F(R(g))),R:=lambda g:[*zip(*F(g))])
S=lambda G,s:[[[G[i+k][j:j+s]for k in u(s)]for j in u(0,N,s)]for i in u(0,N,s)]
def J(g,s):
q=[]
for r in g:
t=[()]*s
for b in r:
for j in u(len(b)):t[j]+=*b[j],
q+=t
return q
for k,
,l,_ in L[N:]:k=int(k);f=p[k%4];G=S(G,l:=2**int(l));G=J([[[f(c)for c in r]for r in G],f(G)][k>4],l)
for i in G:print(*i)

#

it might be too slow though

#
(N,*_),*L=open(0)
N=2**int(N)
u=range
G=[[*map(int,L[x].split())]for x in u(N)]
p=(Q:=lambda g:R(R(R(g))),F:=lambda g:g[::-1],lambda g:Q(F(R(g))),R:=lambda g:[*zip(*F(g))])
def J(g,s):
 q=[]
 for r in g:
  t=[()]*s
  for b in r:
   for j in u(len(b)):t[j]+=*b[j],
  q+=t
 return q
for k,_,l,_ in L[N:]:k=int(k);l=int(l);f=p[k%4];G=[[[G[i+k][j:j+l]for k in u(l)]for j in u(0,N,l)]for i in u(0,N,l)];G=J([[[f(c)for c in r]for r in G],f(G)][k>4],l)
for i in G:print(*i)
``` 466, might be able to get rid of `J` as well
#

I'll go to sleep now

unique viper
#

i have a feeling all of you folks might know if this is possible—i want to be able to control where the debugger lands when pytest --pdb plops it down, and also the stack trace. Can i edit the stack when an error happens so my users end up in a more helpful spot? Currently they have to go up several frames to get through the logging and other decoration my library uses to get to a more useful spot.

olive cargo
#

How can I see the local state of a high order function ?

versed eagle
#

wdym "high order"

olive cargo
#

This is my newbie code

versed eagle
#

i don't want to see your code

#

i want clarification

#

on your question

olive cargo
#

Maybe I should say a function which has an inner function

versed eagle
#

ah. you mean, from inside an inner function, inspect the state of the outer function?

olive cargo
#

not sure if the term is correct but the outter function provides a context for the inner function , correct ?

versed eagle
#

yes

#

variables in the outer function are visible to the inner function

olive cargo
#

I could start the debugger , but I am searching for the objects or attributes which are builts this context

#

something like locals()

versed eagle
#

anything in the outer function should be visible to the inner function already

#

but if you need to you can use something like sys._getframe

olive cargo
#

ah ok , I think then print() will be my friend 🙂

#

but there is an attribute called closure

#

maybe that is what i am looking for

versed eagle
#

__closure__ is for outside variables referenced in the inner function

#

not global variables though

quartz wave
versed eagle
#

true

#

well. if you assign to them without nonlocal then it's not the same variable

#

it's a new local variable

#

which overshadows the old variable

olive cargo
#

test.closure[0].cell_contents , there is my value , but it not very convinient

#

nevertheless thank you ! Thought it's easier to access it

quartz wave
# gleaming linden ```py (N,*_),*L=open(0) N=2**int(N) u=range G=[[*map(int,L[x].split())]for x in ...

untested slight improvements, 445 ```py
(N,),*L=open(0)
N=2**int(N)
u=range
G=[[*map(int,L[x].split())]for x in u(N)]
def J(g,s):
q=[]
for r in g:
t=[()]*s
for b in r:
for a,c in zip(t,b):a+=*c,
q+=t
return q
U=u(0,N,l)
for k,
,l,_ in L[N:]:k=int(k);l=int(l);f=(Q:=lambda g:R(R(R(g))),F:=lambda g:g[::-1],lambda g:Q(F(R(g))),R:=lambda g:[*zip(*F(g))])[k%4];G=[[[G[i+k][j:j+l]for k in u(l)]for j in U]for i in U];G=J([[map(f,r)for r in G],f(G)][k>4],l)
for i in G:print(*i)

sly ibex
#

hey guys how would you do this in one single line

#

at the moment i have this

#
print([i*2 if y%2 else i for y,i in enumerate([7,9,9,2,7,3,9,8,7,1])])```
astral rover
#

you are aware that is one single line lol?

sly ibex
#

i didnt the last part

#

i almost did it

#

./run

print(sum([sum(list(int, t)) if t>10 else t for t in [i*2 if y%2 else i for y,i in enumerate([7,9,9,2,7,3,9,8,7,1])]]))```
#

jajaja

rugged owl
#

!e

night quarryBOT
#
Missing required argument

code

sly ibex
#

pj

#

map

sly ibex
#

done it

#
print(sum([sum(list(map(int, str(t)))) if t>10 else t for t in [i*2 if y%2 else i for y,i in enumerate([7,9,9,2,7,3,9,8,7,1])]]))```
next flame
#

dont need the list

#

sum works on map()

sly ibex
next flame
#

like potential inputs

#

otherwise the golfed answer would just be hardcoding 67

sly ibex
#

oh you mean

#

i should do

#

=

next flame
#

no

sly ibex
#

teach me

#

ahh

#

noo

#

is just 67

#

that-s it

next flame
#

anyways

#
print(sum(x[::2])+sum(a*2-9*(a>5)for a in x[1::2]))

51 bytes, input via x

next flame
#
print(sum(x[::2])+sum(a*2-a//5*9for a in x[1::2]))

50 bytes

versed eagle
#
print(sum(*x[::2],*(a*2-a//5*9for a in x[1::2])))
#

49

next flame
#

sum only takes 1 arg

astral rover
#

sum takes varargs

#

!d sum

night quarryBOT
#
sum

sum(iterable, /, start=0)```
Sums *start* and the items of an *iterable* from left to right and returns the total. The *iterable*’s items are normally numbers, and the start value is not allowed to be a string.

For some use cases, there are good alternatives to [`sum()`](https://docs.python.org/3/library/functions.html#sum "sum"). The preferred, fast way to concatenate a sequence of strings is by calling `''.join(sequence)`. To add floating point values with extended precision, see [`math.fsum()`](https://docs.python.org/3/library/math.html#math.fsum "math.fsum"). To concatenate a series of iterables, consider using [`itertools.chain()`](https://docs.python.org/3/library/itertools.html#itertools.chain "itertools.chain").

Changed in version 3.8: The *start* parameter can be specified as a keyword argument.
astral rover
#

oh i take it back

versed eagle
#

¯_(ツ)_/¯

astral rover
#
Python 3.12.0a0 (heads/main:4114bcc, Sep  7 2022, 19:35:54) [Clang 13.1.6 (clang-1316.0.21.2.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> sum(1,2,3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sum() takes at most 2 arguments (3 given)```
versed eagle
#

huh

#

for some reason, the behaviour is different depending on what python version i use

#

i dont remember the function specification changing between 3.10 and 3.11?

#

idfk

meager zinc
#

@versed eagle here's what I got for grep, can probably be quite improved

import sys,re
_,r,*s=sys.argv
[print(l,end="")for f in([*map(open,s)]or(sys.stdin,))for l in f.readlines()if re.match(r,l)]
fleet bridge
versed eagle
#

use a comprehension

rugged sparrow
# versed eagle

I can't find a single version that supports variable sum out of the box

versed eagle
#

which is why im confused

meager zinc
rugged sparrow
#

see if it is a builtin

astral rover
#

i feel like ive seen varargs sum before

versed eagle
rugged sparrow
#

then check sum.__module__

fleet bridge
#

for some reason python 2.7.18 is screaming at me: ```py
Python 2.7.18 (v2.7.18:8d21aa21f2, Apr 20 2020, 13:25:05) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

sum(1,2,3)
File "<stdin>", line 1
sum(1,2,3)
^
SyntaxError: invalid syntax
sum(1, 2, 3)
File "<stdin>", line 1
sum(1, 2, 3)
^
SyntaxError: invalid syntax
sum(1, 2, 3)
File "<stdin>", line 1
sum(1, 2, 3)
^
SyntaxError: invalid syntax
sum(1, 2, 3);
File "<stdin>", line 1
sum(1, 2, 3);
^
SyntaxError: invalid syntax
print sum(1, 2, 3)
File "<stdin>", line 1
print sum(1, 2, 3)
^
SyntaxError: invalid syntax
x = 1
File "<stdin>", line 1
x = 1
^
SyntaxError: invalid syntax

meager zinc
#

I swear sum only ever worked with iterables

fleet bridge
#
Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:01:55) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> sum(1,2,3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sum expected at most 2 arguments, got 3
>>>
meager zinc
#

!d sum

night quarryBOT
#
sum

sum(iterable, /, start=0)```
Sums *start* and the items of an *iterable* from left to right and returns the total. The *iterable*’s items are normally numbers, and the start value is not allowed to be a string.

For some use cases, there are good alternatives to [`sum()`](https://docs.python.org/3/library/functions.html#sum "sum"). The preferred, fast way to concatenate a sequence of strings is by calling `''.join(sequence)`. To add floating point values with extended precision, see [`math.fsum()`](https://docs.python.org/3/library/math.html#math.fsum "math.fsum"). To concatenate a series of iterables, consider using [`itertools.chain()`](https://docs.python.org/3/library/itertools.html#itertools.chain "itertools.chain").

Changed in version 3.8: The *start* parameter can be specified as a keyword argument.
astral rover
#

oh im thinking of min/max

#

they work with varargs

meager zinc
#

!d min

night quarryBOT
#
min

min(iterable, *, key=None)``````py

min(iterable, *, default, key=None)``````py

min(arg1, arg2, *args, key=None)```
Return the smallest item in an iterable or the smallest of two or more arguments.

If one positional argument is provided, it should be an [iterable](https://docs.python.org/3/glossary.html#term-iterable). The smallest item in the iterable is returned. If two or more positional arguments are provided, the smallest of the positional arguments is returned.

There are two optional keyword-only arguments. The *key* argument specifies a one-argument ordering function like that used for [`list.sort()`](https://docs.python.org/3/library/stdtypes.html#list.sort "list.sort"). The *default* argument specifies an object to return if the provided iterable is empty. If the iterable is empty and *default* is not provided, a [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "ValueError") is raised.
meager zinc
#

yeah min has a varargs impl

#

but not sum

rugged sparrow
versed eagle
versed eagle
#

its super bloated and fills up the global namespace with lots pointless stuff

meager zinc
#

that could actually break some code

#

and is bad for golfing

rugged sparrow
meager zinc
astral rover
#

is it possible youve changed the implementation yourself and recompiled without realising?

versed eagle
#

i doubt that i would forget doing something like that

astral rover
#

idk what other explanation for it there could be

versed eagle
#

though you've given me an idea
i might have something weird in $PYTHONSTARTUP
i'll go check that brb

rugged sparrow
meager zinc
#

it looks like it's not a python 3.10 only feature which is extremely strange

#

so I'm guessing your end has something weird

versed eagle
meager zinc
#

3.10.7 only?

#

I see four changes to sum for the 3.10.7 release (unless it also works on 3.10.6)

#

and it

#

isn't the second or last

versed eagle
meager zinc
#

thats really weird

versed eagle
#

i am very annoyed with my past self.

meager zinc
#

it's okay

#

any ideas for the grep?

#
import sys,re
_,r,*s=sys.argv
[print(l,end="")for f in([*map(open,s)]or(sys.stdin,))for l in f.readlines()if re.match(r,l)]
versed eagle
#

sys.stdin -> open(0)

#

is the only thing i can think of

meager zinc
#
import sys,re
_,r,*s=sys.argv
[print(l,end="")for f in([*map(open,s)]or(open(0),))for l in f.readlines()if re.match(r,l)]
#

do we need end=""?

#

or could we just slice it?

versed eagle
#

yeah you could slice it

#

rather than end=""

meager zinc
#
import sys,re
_,r,*s=sys.argv
[print(l[:-1])for f in([*map(open,s)]or(open(0),))for l in f.readlines()if re.match(r,l)]
versed eagle
#

([*map(open,s)]or(open(0),))
(map(open,s)or(open(0),))

#

map is iterable already

#

we dont need to convert it to a list

meager zinc
#

no I tried it

versed eagle
#

no?

meager zinc
#

but if map() seemed to always be true

#

!e ```py
a = map(int, [])
if a:
print(a)
else:
print("no")

night quarryBOT
#

@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.

<map object at 0x7fcb9c038a30>
versed eagle
#

ah yeah

meager zinc
#

weird behavior but ye

versed eagle
#

you're right, map objects are always true

#

which is. weird but

past plank
meager zinc
#

ahh

versed eagle
#

ooh thats a good one

meager zinc
#
import sys,re
_,r,*s=sys.argv
[print(l[:-1])for f in map(open,s or[0])for l in f.readlines()if re.match(r,l)]
past plank
#

should be functionally equivalent with the default behavior of re.findall

#

also @versed eagle ^

meager zinc
#

do you need sep="\n"? is it not included in the regex?

past plank
#

no unfortunately

meager zinc
#

can't you add it

past plank
#

!e ```py
import re

text = """
ab!c
def
ghi
jk!l
"""

r = "!"
print(re.findall(f".{r}.", text))```

night quarryBOT
#

@past plank :white_check_mark: Your 3.11 eval job has completed with return code 0.

['ab!c', 'jk!l']
past plank
#

no newline is included

meager zinc
#

!e ```py
import re

text = """
ab!c
def
ghi
jk!l
"""

r = "!"
print(re.findall(rf".{r}.\n", text))

night quarryBOT
#

@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.

['ab!c\n', 'jk!l\n']
meager zinc
#

adding r\n is shorter than sep

past plank
#

does . include \r?

#

for windows newlines

#

!e ```py
import re

print(re.findall(".*\n", "hello\r\nworld"))```

night quarryBOT
#

@past plank :white_check_mark: Your 3.11 eval job has completed with return code 0.

['hello\r\n']
past plank
#

yes

#

okay that should work then

meager zinc
#
import sys,re
_,r,*s=sys.argv
for f in map(open,s or[0]):print(*re.findall(f'.*{r}.*\n',f.read()))
past plank
#

nice

meager zinc
#

I wonder if there's a single character that corresponds to a newline

past plank
#

you don't need the r in fr

meager zinc
#

I feel like there might be

past plank
#

I think that actually breaks it

meager zinc
#

will the regex be fine with a newline character instead of \n?

past plank
#

it has to be that

meager zinc
#

ok ok

#

is it too greedy?

past plank
#

how so?

meager zinc
#

not too greedy

past plank
#

this will definitely break if someone tries to enter a pattern like ^abc$ though

meager zinc
#

yeah...

#

if the last line doesn't have a newline it is also a problem

#

you can add a single ? to fix it tho

past plank
#

yeah

meager zinc
#
import sys,re
_,r,*s=sys.argv
for f in map(open,s or[0]):print(*re.findall(f'.*{r}.*\n?',f.read()))
versed eagle
#

but you wouldn't be able to use it

#

because, it's a newline

low lynx
#

if it was triple quoted then you'd get single character newlines

#

but triple quotes are rarely worth it

versed eagle
#

that'd lose more characters than it'd save

versed eagle
#

since in grep regex you can use ^ and $ for start and end of lines

#

but in that, ^ would be the start of the whole file, not the start of a line

#

same with $ being the end of the line vs the end of the whole file

gleaming linden
# gleaming linden ```py (N,*_),*L=open(0) N=2**int(N) u=range G=[[*map(int,L[x].split())]for x in ...
(N,*_),*L=open(0)
N=2**int(N)
u=range
G=[[*map(int,L[x].split())]for x in u(N)]
for k,_,l,_ in L[N:]:
 k=int(k);l=2**int(l);f=(Q:=lambda g:R(R(R(g))),F:=lambda g:g[::-1],lambda g:Q(F(R(g))),R:=lambda g:[*zip(*F(g))])[k%4];G=[[[G[i+k][j:j+l]for k in u(l)]for j in u(0,N,l)]for i in u(0,N,l)];q=[[[f(c)for c in r]for r in G],f(G)][k>4]
 G=[]
 for r in q:
  t=[()]*l
  for b in r:
   for j in u(len(b)):t[j]+=*b[j],
  G+=t
for i in G:print(*i)
``` 440
meager zinc
#

and then you don't need the other part

versed eagle
#

.splitlines()
.split("\n")

meager zinc
#

!d str.split

night quarryBOT
#

str.split(sep=None, maxsplit=- 1)```
Return a list of the words in the string, using *sep* as the delimiter string. If *maxsplit* is given, at most *maxsplit* splits are done (thus, the list will have at most `maxsplit+1` elements). If *maxsplit* is not specified or `-1`, then there is no limit on the number of splits (all possible splits are made).

If *sep* is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). The *sep* argument may consist of multiple characters (for example, `'1<>2<>3'.split('<>')` returns `['1', '2', '3']`). Splitting an empty string with a specified separator returns `['']`.

For example:
meager zinc
#

what's the default sep?

#

I dont see it

#

Looks equivalent to

versed eagle
#

default sep = " "

meager zinc
#

str.strip().split(' ')

#

that's default

versed eagle
#

if sep = None, it uses space

eager ore
#

it's just a space

#
>>> '1 2 3'.split()
['1', '2', '3']
meager zinc
#

(see bottom example)

#

it's not just space

#

it's whitespace and can be >1

versed eagle
#

ah you're right

meager zinc
#

so it's more like

#

re.split(r'\w+', STR.strip())

versed eagle
#

ooh i have a challenge for you all

#

golf an implementation of the round function

#

my shortest implementation so far is 53 chars
however, it's far from optimal

rugged sparrow
versed eagle
#

wait it does?

#

i did not know that

#

at all

#

oh nice

#

my solution works

#

for negative ndigits

rugged sparrow
#

yea before I noticed that I had this || round = lambda i,n=0:type(i)(f'{i:.{n}f}') ||

versed eagle
#

oh wow that's quite nice

rugged sparrow
#

but it doesnt work for negative digits

versed eagle
#

here's what i've got so far ||round=lambda n,d=0:int((n:=n*10**d)+(n%1>=0.5))/10**d||

#

i really wish i had thought of using ||f-strings|| like you did, that's quite brilliant

rugged sparrow
serene garnet
#

hey

#

golf this code

#

quick!!

#
while 1:
 t=int(input())
 if t==0:break
 x=1
 while int(bin(x)[2:])%t:x+=1
 print(bin(x)[2:])
#

asap

gleaming linden
#

what is this

#

binary of next power of 2?

#

oh wait

gleaming linden
#

and you could probably walrus that too

#

and while t:=int(input()):

#
while t:=int(input()):
 x=1
 while int(r:=f'{x:b}')%t:x+=1
 print(r)
``` 93 -> 68
serene garnet
#

thanks!!!

#

sorry, one more time

#

if you know golfscript,

#

can you translate it to golfscript?

#

asap, please

#

i need it quick

#

plz

#

my friend golfed one byte more than me

#
x=1
while t:=int(input()):
 while int(r:=f'{x:b}')%t:x+=1
 print(r)
winter basin
#

hello

#

guys

#

hey

tough willow
#

!ot

night quarryBOT
tough willow
#

@winter basin

gleaming linden
earnest wing
#

Why is my custom codec being called multiple times in this control flow?

# bootstrap.py
import hoopy
hoopy.register()
import main
# main.py
# coding: hoopy
def ($)(f, x):
   return f x
add = (+)
print $ add 1 2
#

Codec registration:

def register():
    codecs.register(searcher)

def searcher(name: str) -> codecs.CodecInfo | None:
    if name.lower() == "hoopy":
        return codecs.CodecInfo(
            lambda input, errors="strict": utf_8.encode(input, errors),
            decode_hoopy,
        )

def decode_hoopy(input: bytes, errors: str = "strict") -> tuple[str, int]:
    from .transform import transform
    source, read = utf_8.decode(input, errors=errors)
    return transform(source), read
#

decode_hoopy is first called with the whole source, then with the line b'add = (+)\n' BABA_IS_THINK

serene garnet
gleaming linden
#

@serene garnet does it accept pyth by any chance?

prisma eagle
#

Hi all, I have a pretty esoteric Python question. I have two class definitions Vector and IntVector. The Vector has float x and y and implements a whole bunch of dunder methods (add, sub, etc.) I want the IntVector to inherit all of the functionality of Vector, but return the int(x), int(y) version of Vector. Here is the code I have so far:

@dataclass(frozen=True)
class Vector():
    x: float
    y: float

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
    
    def __sub__(self, other):
        return Vector(self.x - other.x, self.y - other.y)
    
    def __iter__(self):
        return iter((self.x, self.y))

    def __truediv__(self, other):
        return Vector(self.x / other, self.y / other)
    
    @property
    def length(self):
        return sqrt(self.x ** 2 + self.y ** 2)

class IntVector(Vector):
    x: int
    y: int

    @staticmethod
    def intify(func):
        @wraps(func)
        def wrapped(*args, **kwargs):
            result = func(*args, **kwargs)
            if isinstance(result, Vector):
                return IntVector(int(result.x), int(result.y))
            elif isinstance(result, float):
                return int(result)
            elif isinstance(result, int):
                return result
            else:
                raise ValueError(f"Unable to intify {result}")
        return wrapped

    #def __new__(cls, *args, **kwargs):
    #    vector = super().__new__(cls, *args, **kwargs)

    def __init__(self, *args, **kwargs):
        super().__init__(*map(int, args), **kwargs)
    
    @intify
    def __add__(self, other):
        return super().__add__(other)

    @intify
    def __sub__(self, other):
        return super().__sub__(other)

    @intify
    def __truediv__(self, other):
        return super().__truediv__(other)

    @property
    @intify
    def length(self):
        return super().length

Is there any way to make this more succinct?

fleet bridge
#

You dont need this weird decorator and all duplicate methods

Use self.__class__ instead of Vector in methods
And modify IntVector.__init__

dry mirage
#

python dataclasses aren't typed, your Vector class works fine with ints

fleet bridge
#

You can add .round()->Vector method

dry mirage
#

all your operations also work the exact same way

#

you just need to add __floordiv__ if you want that

prisma eagle
#

interesting, maybe I over-engineered this.

fleet bridge
#

__floordiv__ works with floats as well

dry mirage
#

for typing purposes you could make it a generic, but that doesn't affect runtime

#
@dataclass(frozen=True)
class Vector(Generic[T]):
    x: T
    y: T
prisma eagle
#

Small note: I left out two dunder methods to make the message shorter:

    @property
    def length(self):
        return sqrt(self.x ** 2 + self.y ** 2)

    @property
    def norm(self):
        return self / self.length
#

I'd like norm to return an int when possible

#

so Vector(2, 0).norm == Vector(1, 0)

#

And that spawned this over-engineered design choice

dry mirage
#

kind of weird behavior

fleet bridge
prisma eagle
#

So that I can do

a = Vector(2, 0)
a += a.norm
a += a.norm

and still get an int vector like I started

dry mirage
#

don't see much more work here, if you truly need to support multiple types

fleet bridge
prisma eagle
#

true

#

How would the API look with the generic you suggested?

fleet bridge
prisma eagle
#

something like a: Vector[int] = Vector(2, 0)?

dry mirage
fleet bridge
dry mirage
#

in the methods you can do

def __add__(self, other: Vector[T]) -> Vector[T]:
#

or it can be -> Self as well

prisma eagle
#

and T = TypeVar('T') from typing import Generic?

dry mirage
#

depending on if you want the return type to use the current type or the other type

fleet bridge
prisma eagle
#

how do I do that?

dry mirage
#

or you'd make a runtime checkable protocol for those you need

fleet bridge
#

class _Tproto(SupportsAdd, SupportsMul, ..., Protocol):...
T=TypeVar(T, bound=_Tproto)

prisma eagle
#

gotcha, ty!

#

so bound= take a protocol?

fleet bridge
#

It takes any thing that is acceptable as annotation

prisma eagle
#

Also quick question on

    def __add__(self, other: Self) -> Self:
        return Vector(self.x + other.x, self.y + other.y)

If self is a Vector[float] and other is a Vector[int], does this Self typing make sense?

fleet bridge
#

Int is a subclass of float

#

If you want Vector[int] to be assignable to Vector[float] you should make T covariant (or contravariant, i forgot what these things even mean)

prisma eagle
#

oh boy....

fleet bridge
#

Otherwise V[int]+V[float] is an error
And V[A]=V[B] is error too if A and B are not the same

fleet bridge
earnest wing
#

you cannot use Self for generic types (if you want the generic parameter to vary in the signature)

#

if you could, you would be able to encode higher-kinded types (very difficult) into the type system

fleet bridge
#

You can use Vector[T] instead of Self. It works the same if you have only one class, but will break typing for subclasses

prisma eagle
#

ok, thanks!

gleaming linden
arctic skiff
#

is it possible to have a single line while loop?

#
while 1:
    print(1)
    print(2)
    if ...:
      print(3)
```is it possible to make it in in 1 line
tough willow
meager zinc
#
while 1:print(1);print(2);[print(3)if ... else 0]
versed eagle
#
while (print(1, 2, sep="\n"), mybool and print(3)):...
#

not shorter

#

but its a fun way to do it imo

rugged sparrow
#

!e py set(iter(lambda l=[]:print(len(l))or l.append(1) or len(l), 10))

night quarryBOT
#

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

001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
versed eagle
#

ooh thats nice

rugged sparrow
#

Technically it is a do/while loop but you could swap it to normal while loop with an early bailout

meager zinc
#

while print(1,2,... and 3,sep="\n")+1:0

versed eagle
#

that would print Ellipsis

meager zinc
#

well it's supposed to be a bool

#

but it would also fail then tbf

versed eagle
#

wait im stupid

#

its not literal ellipsis

#

it would print False if the bool was false though

#

also print returns None

#

cant add an int to None

meager zinc
#

while print(1,2,'3'*True,sep="\n")or 1:0

versed eagle
#
while(print(f"1\n2{'\n3'*mybool}"),):0
#
while(print("1\n2"+'\n3'*mybool),):0
meager zinc
#

smart

#

can you remove the parens?

#

not the tuple ones but the other ones

versed eagle
#

the function call ones?

meager zinc
#

nevermind

#

sometimes you can do

#

1,2 as a tuple

#

for _ in 1,2:print(_)

versed eagle
#

while loops dont like it

earnest wing
#

here's a fun one:

versed eagle
#

ooh do tell

earnest wing
#
>>> for x in range(10), x in range(10):
...     print(x)
range(0, 10)
True
versed eagle
#

ah interesting

#

it gets parsed as for x in (range(10), x in range(10))

earnest wing
#

and range in range is well defined!

rugged sparrow
#

!e Heres another weird one: py x = [0] for x[0], x[0] in ((1, 2),):pass print(x)

night quarryBOT
#

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

[2]
versed eagle
#

what's happening there

arctic skiff
versed eagle
#

i didn't know you could index into the loop variables lmao

arctic skiff
rugged sparrow
arctic skiff
meager zinc
#

while *map(print,(1,2,”3”*True)):0

#

might need a set of list brackets

versed eagle
#

i didn't know that

meager zinc
#

i wish walrus did

#

its dumb that for can assign while walrus cant

past plank
#

this could just be while(*map(print,'123')):0

tough willow
past plank
versed eagle
#

yep

sonic birch
versed eagle
#

what about except clauses in try/except blocks?

proper vault
#

those are harder, you can use ContextDecorator

#

I believe chilaxan also got one to work using bytecode manipulation

versed eagle
#

ah no it doesn't like it for except clauses

#

import/as statements don't like it either

versed eagle
finite blaze
#

while(print("1\n2"+'\n3'*mybool),):0
^ why there is a comma?

versed eagle
#

that was to make it a tuple

#

so that it would always evaluate to true

#

the print returns None

#

as it is, it evaluates to (None,)

#

since the tuple isn't empty, it's Truthy

#

but without the comma, it's (None), which is just None

#

which is Falsey

rugged sparrow
dusty shadow
#

yo!

near siren
#

range(10), x in range(10) is evaluated the first to give a NameError

earnest wing
#

You're right it is

#

That was a repl side-effect

winter basin
#

Can you guys help me?

low lynx
#

with?

winter basin
#

Can you shorted this?

#

($.+=1while(r=("%b"%$.).to_i)%T>0;p r)while 0<T=gets.to_i

#

it is Ruby

#

Can you short the bite?

earnest wing
#

in #esoteric-ruby maybe?

winter basin
#

This is Ruby

quartz wave
winter basin
#

sorry

#

I was cinfused

#

confused

#

Can you shortest this code?

#

while True:
t = int(input())
if t == 0:
break
cnt = 1
while int(format(cnt,'b')) % t != 0:
cnt += 1
print(format(cnt,'b'))

winter basin
#

Can you more short?

quartz wave
winter basin
#

okay

sonic birch
rugged sparrow
#

Yea

sick hound
#

huh can you help me to find hidden print ?

#

in my code

zealous burrow
#

!e py import sys sys.stdout.write("hello")

night quarryBOT
#

@zealous burrow :white_check_mark: Your 3.11 eval job has completed with return code 0.

hello
zealous burrow
sick hound
#

but didn't find the module

#

Bruh what if its using it for something else

zealous burrow
#

i mean this was just one of the ways-

#

search for what it prints 🧠

sick hound
zealous burrow
#

and search that with ctrl+f

sick hound
zealous burrow
#

you'll find the line and the code

sick hound
zealous burrow
#

and u found it ?

sick hound
#

Lol

zealous burrow
#

!e

import io;_ы_ы_ы_=eval("".join(chr(_ы) forin [112,114,105,110,116]));_ы_=sorted;__ы=lambda ь:1;_ы__=str.join;_=chr;__=ord;ы=io.StringIO();_ы_ы_ы_(_ы__("",_ы_([_(__(_(__(____)))) for ____ in "If you bought this you got scammed"],key=__ы)),file=ы);_ы_ы_ы_(ы.getvalue())
night quarryBOT
#

@zealous burrow :white_check_mark: Your 3.11 eval job has completed with return code 0.

If you bought this you got scammed
sick hound
#

Search for this string i mean

zealous burrow
#

and if u cant find it, delete the code.

sick hound
zealous burrow
#

and go sleep

sick hound
zealous burrow
#

yea well

#

guy should know that u shouldnt break Tos

#

bad things happen to those who break the rules

#

and tf am i talking about 💀 like a old parent

sick hound
#

@zealous burrow check that

#

i found import sys but it's not used in the code

sick hound
zealous burrow
#

!e ```py
import sys
sys.stdout.write('If you bought this you got scammed \n man just search this output fr')

sick hound
#

already did

#

but didn't find

night quarryBOT
#

@zealous burrow :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | If you bought this you got scammed 
002 |  man just search this output fr
zealous burrow
#

@sick hound search "scammed"

sick hound
#

!e

print("I just did it fam :/")
night quarryBOT
#

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

I just did it fam :/
zealous burrow
#

maybe the dev defined the words through out the code

sick hound
#

Lol

#

I mean if it works who cares

zealous burrow
#

Or just contact them fr

sick hound
#

the code seems like that

#

Interesting

zealous burrow
#

search in each of them

sick hound
zealous burrow
sick hound
#

Lol why

#

that's why i asked you

sick hound
#

check that

#

If u cant provide code we cant really help

#

a

zealous burrow
#
  • why do u even want to see where it is getting printed
#

i mean the code works right ?

sick hound
#

because i want to delete it

zealous burrow
#

yea then leave it

#

Coding 101: Never ever touch code that works.

sick hound
#

he's completely working

#

but this shitty message is not appearing

tough willow
night quarryBOT
#

@tough willow :white_check_mark: Your 3.11 eval job has completed with return code 0.

Hello, world!
night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name 'ctypes' is not defined. Did you mean: 'type'?
#

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

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

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name 'json' is not defined
pure dew
#

@sick hound just post the code so we can help look

versed eagle
#
(a := (lambda b, c: (not (d := (e := object.__sizeof__)(b), f :=
 e(c)), f - d)[(g := [d < f])[h := 0]] or (i := tuple)((j := map
)((lambda k, l: {(h, (m := k.from_address)((n := g[h].__add__)((
o := id)(b))).__setattr__((p := "value"), getattr(m(n(o(c))), p)
), g.__setitem__(h, n(l)))[h] for q in iter((lambda: g[h] <= f -
 l), h)}), (r := ((s := __import__("ctypes")).c_int64, s.c_int32
, s.c_int16, s.c_int8)), i(j(s.sizeof, r)))) and h))
#

object swapper

#

it's basically << from einspect but it doesn't use memmove and it has only very rudimentary checks for safety

#

this could be a lot shorter, but i wanted to make it so that the lines were ending on the same column

#

so there's a few variables that don't really do very much

low lynx
#

!e

from einspect import impl
@impl(int)
def __getitem__(self, item):
    return self
night quarryBOT
#

@low lynx :warning: Your 3.11 eval job has completed with return code 139 (SIGSEGV).

[No output]
low lynx
#

why does this sigsegv?

rugged sparrow
#

!e ```py
from fishhook import hook

@hook(int)
def getitem(self, item):
return self

night quarryBOT
#

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

[No output]
low lynx
rugged sparrow
low lynx
#

huh

rugged sparrow
#

weird

rugged sparrow
dry mirage
#

!e

import einspect

print(einspect.__version__)
night quarryBOT
#

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

0.5.10
dry mirage
#

seems fine in 0.5.12

#

!e

from einspect import impl

@impl(int)
def __getitem__(self, item):
    return self

print(1[0])
night quarryBOT
#

@dry mirage :x: Your 3.11 eval job has completed with return code 139 (SIGSEGV).

<string>:7: SyntaxWarning: 'int' object is not subscriptable; perhaps you missed a comma?
dry mirage
#

prior to 0.5.12 it didn't allocate the PyMethods struct for subclasses, but not sure why that causes the segfault

rugged sparrow
#

huh on the bot it is crashing when the hook is made

#

on my machine (0.5.11) it was crashing on gc collect

rugged sparrow
dry mirage
#

but if the subclass tp_as_xxx call is NULL that shouldn't reach the parent right?

dry mirage
rugged sparrow
dry mirage
#

ah hm

#

seems in 0.5.10 to 0.5.11 the only relevant change is excluding type from the subclass allocation

#

so starting in 0.5.10 it was already allocating subclasses, just not recursively (only 1 layer of inheritance)

#

in 0.5.12 I got rid of the type exclusion and properly allocated recursively for all subclasses and subclasses of those

rugged sparrow
dry mirage
#

I was kind of scared of how long it would take though

#

but probably not a huge issue

#

though it is allocating like, thousands of classes depending on import

rugged sparrow
#

I haven't noticed any timing issues (since it is a one time cost at hook time i didn't worry about it)

dry mirage
#

list.__sizeof__ includes the heap allocated vector that's not with the struct, for example

versed eagle
#

!e

print(object.__sizeof__(list()))
print(object.__sizeof__(list(range(500000))))
night quarryBOT
#

@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 40
002 | 40
versed eagle
#

because the __sizeof__ method isn't consistent between classes

#

but object.__sizeof__ works on everything
or at least, everything that I've tested it with

rugged sparrow
#

Hmm it is different for tuples actually

#

Interesting

versed eagle
#

at least, not for ints

#

for ints it's int.__basicsize__ + (4 * ob_size)

#

(ignoring the sign bit in ob_size, that is)

rugged sparrow
#

Actually it makes sense that it works now, but I think at some point stuff like lists still defined tp_itemsize (they don't anymore)

#

I remember I had some reason why I didn't use it but I don't think it is the case anymore

versed eagle
#

ah

versed eagle
#

chilaxan i have a question for you

rugged sparrow
#

Yea, otherwise orig can end up in a recursive loop

versed eagle
#

it still can

#

with hooking method-wrapper

#

!e

from fishhook import hook, orig
@hook(type(().__add__))
def __call__(self, *args):
    return orig(self, *args)
@hook(int)
def __add__(self, other):
    return orig(self, other - 1)
print(int("1") + int("1"))
night quarryBOT
#

@versed eagle :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 8, in <module>
003 |   File "<string>", line 7, in __add__
004 |   File "/snekbox/user_base/lib/python3.11/site-packages/fishhook/fishhook.py", line 246, in __call__
005 |     return get_cache_trace('orig', getframe(1))(*args, **kwargs)
006 |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
007 |   File "/snekbox/user_base/lib/python3.11/site-packages/fishhook/fishhook.py", line 215, in get_cache_trace
008 |     code = get_code(frame)
009 |            ^^^^^^^^^^^^^^^
010 |   File "<string>", line 4, in __call__
011 |   File "/snekbox/user_base/lib/python3.11/site-packages/fishhook/fishhook.py", line 246, in __call__
... (truncated - too many lines)

Full output: too long to upload

rough crane
#

does esoteric = fast ish but gives you more headaches or does esoteric just mean headaches for the sake of headaches

rugged owl
#

afaik

rough crane
#

Output time wise I don’t mind sitting for hours just to shave seconds

last locust
#

Speed has nothing to do with esoteric code

#

Tl;Dr; is that it's obfuscation and/or golfing

#

But it does divulge into other areas too

rugged sparrow
versed eagle
#

would it be possible to create a copy in memory of "essential" types such as method-wrapper, function, etc, and then use those as the ob_type of stuff rather than the main class?

rugged sparrow
#

Not safely

versed eagle
#

why not?

#

is it something to do with garbage collection at the end of the python process

rugged sparrow
#

There are internal checks that check type using pointer equality, swapping those out would fail the checks

versed eagle
#

what are the checks for?

#

like, why check the type

rugged sparrow
#

Subclass delegation typically

versed eagle
#

ah

rugged sparrow
#

Those few types might slip by but it's the kind of thing that could definitely break hard on an update

versed eagle
#

ah. that wouldnt really be worth the effort of implementing it then

rugged sparrow
#

Yea exactly

#

As it is, the safety features of orig cover 99% of use cases

winter basin
#

Can you guys help me?

versed eagle
winter basin
#

why do you think so?

versed eagle
#

because the vast majority of people who ask for help in this channel are simply doing so because they have no clue what this channel is for, and chose it at random to ask for help in

dry mirage
night quarryBOT
#

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

1
dry mirage
# versed eagle i used `object.__sizeof__` specifically for reasons like that

!e is list to tuple supposed to work here then? weird pithink

(a := (lambda b, c: (not (d := (e := object.__sizeof__)(b), f :=
 e(c)), f - d)[(g := [d < f])[h := 0]] or (i := tuple)((j := map
)((lambda k, l: {(h, (m := k.from_address)((n := g[h].__add__)((
o := id)(b))).__setattr__((p := "value"), getattr(m(n(o(c))), p)
), g.__setitem__(h, n(l)))[h] for q in iter((lambda: g[h] <= f -
 l), h)}), (r := ((s := __import__("ctypes")).c_int64, s.c_int32
, s.c_int16, s.c_int8)), i(j(s.sizeof, r)))) and h))((1, 2), [1, 2, 3])

print((1, 2))
night quarryBOT
#

@dry mirage :warning: Your 3.11 eval job has completed with return code 139 (SIGSEGV).

[No output]
dry mirage
#

I can't really tell what the code is calling so

versed eagle
#

just a moment, i have a less obfuscated version somewhere

#
from ctypes import *
def switch_ob(a, b):
    size = object.__sizeof__
    if (a_size := size(a)) < (b_size := size(b)):
        # object `b` is too big to fit into object `a`.
        # return the size difference as an error code
        return b_size - a_size
    types = (
        c_int64, c_int32, c_int16, c_int8,
    )
    offset = 0
    for ctype, ctype_size in zip(types, map(sizeof, types)):
        while offset <= b_size - ctype_size:
            ctype.from_address(id(a) + offset).value = (
                ctype.from_address(id(b) + offset).value
            )
            offset += ctype_size
    return 0 # return success
#

its something like that

#

the second bit is just an implementation of memmove, but it does it in chunks

#

it starts with chunks of 8, and then when there's less than 8 bytes left to move, it goes on to 4 bytes, then 2 bytes, then 1 byte

#

basically: ensure that b can fit into a, and then move all bytes of b into a

#

!e

from ctypes import *
def switch_ob(a, b):
    size = object.__sizeof__
    if (a_size := size(a)) < (b_size := size(b)):
        # object `b` is too big to fit into object `a`.
        # return the size difference as an error code
        return b_size - a_size
    types = (
        c_int64, c_int32, c_int16, c_int8,
    )
    offset = 0
    for ctype, ctype_size in zip(types, map(sizeof, types)):
        while offset <= b_size - ctype_size:
            ctype.from_address(id(a) + offset).value = (
                ctype.from_address(id(b) + offset).value
            )
            offset += ctype_size
    return 0 # return success
switch_ob("a", "b")
print("a" == "b")
night quarryBOT
#

@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.

True
versed eagle
#

is list to tuple supposed to work here then? weird pithink
as for that, i have no clue. the list should be small enough to fit into the tuple

dry mirage
humble rune
#
str2num=lambda s,o=[]:[o:=o+[ord(i)]for i in s]*0 or o

is there a shorter way of doing this?

humble rune
#

convert a string to a list of numbers

dry mirage
#

but 2 args?

humble rune
#

the second argument is so it can fit into a lambda

dry mirage
#

wut

humble rune
#

its just setting o to a blank list

#

so i can not have errors when doing o:=o+[ord(i)]

dry mirage
#

str2num=lambda s:[*map(ord,s)]

humble rune
#

bruhhh

#

im a goober

#

i forgot about map

#

im rusty

dry mirage
humble rune
#

thanks

versed eagle
rugged owl
night quarryBOT
#

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

True
versed eagle
#

like i said, sunk cost fallacy

rapid kayak
#

aight sooooooo

#

is it possible to

#

change the python syntaxxxxxxxxxxx

rugged owl
rapid kayak
rugged owl
#

There is a module for that i think

rapid kayak
#

now just change elif to elseif

rugged owl
rapid kayak
#

this fr making python 20x better

rapid kayak
#

like no virus

last locust
#

You can check for yourself Shrug

rapid kayak
fair quartz
#

guys how do i mutate ints in place :DDDDDDDDDD

#
def add1(x):
    py_object.from_address(id(x)).value += 1

x = 100000000000000000000000
print(x)
add1(x)
print(x)
restive void
#

!e

from ctypes import*
x = 1000000000000000000
cast(id(x), POINTER(c_int))[6] += 1
print(x)
night quarryBOT
#

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

1000000000000000001
dry mirage
night quarryBOT
#

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

100000000495583232
versed eagle
# dry mirage !e doesn't work for 30 bit boundaries though 😔 ```py from ctypes import * x =...
from ctypes import *
def inplace_incr(i):
    max_amount = (1 << ((abs(
        c_ssize_t.from_address(id(i) + 16).value
    ) - 1) * 32)) - 1
    if i >= max_amount:
        raise MemoryError(f"value of {i + 1} is larger than the largest amount that can fit into {object.__sizeof__(i) - 24} bytes ({max_amount})")
    digit_offset = 24
    # do{ ... } while() loop. increment successive digits until there's no more overflow
    while True:
        current = c_uint.from_address(
            id(i) + digit_offset
        ).value
        if current <= c_uint(current + 1).value:
            c_uint.from_address(
                id(i) + digit_offset
            ).value += 1
            break
        c_uint.from_address(
            id(i) + digit_offset
        ).value += 1
        digit_offset += 4
unique heath
#

im bored so imma golf euler14

#

!e

a = {}
for i in range(1e6):
    b = 0
    c = i
    while c != 4:
        if c&1:3*c+1
        else:c/2
        b += 1
    a[i] = b```
night quarryBOT
#

@unique heath :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | TypeError: 'float' object cannot be interpreted as an integer
restive void
unique heath
#

!e

m = 0
for i in range(10**6):
    b = 0
    c = i
    while c != 4:
        if c&1:3*c+1
        else:c/2
        b += 1
    if b>m:m=b
night quarryBOT
#

@unique heath :warning: Your 3.11 eval job timed out or ran out of memory.

[No output]
dry mirage
#

but that's not really allocated memory

#

with python malloc=DEBUG that will have an assertion error during GC

versed eagle
#

alignment is scary

dry mirage
#

all CPython builds have the same alignment iirc

versed eagle
#

do they?

#

i didnt know that

unique heath
#

@dry mirage why is my thing so slow

dry mirage
#

well it's just a long loop right

versed eagle
#

you never assign to c so it never gets to 4

unique heath
#

its been taking over 10 seconds now

versed eagle
#

the inner while loop never finishes

unique heath
unique heath
#

oh im dumb

#

how is this not wowrkign

m = 0
for i in range(1,10):
    b = 0
    c = i
    while c != 4:
        if c&1: c*=3+1
        else: c/=2
        b += 1
    if b>m:m=b
print(m)```
versed eagle
#

also the c*=3+1 is the same as c*=4

unique heath
unique heath
versed eagle
#

that's the collatz conjecture right?

versed eagle
#

as it is now, it makes it into a float

#

which iirc doesn't have & implemented

#

yep

unique heath
#

its taking 69 years rips

versed eagle
night quarryBOT
#

@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.

46
unique heath
#

good idea (totally not gonna steal that)

unique heath
#

ok

#

so

quartz wave
#

__import__('random').choice is not less chars

unique heath
#

time to obfuscoate

quartz wave
#
from random import*
while 1:
 if input("rps?")in'rps':print("you %s!"%choice(['won','lost','tied']));break
#

short as ever

low lynx
#

is it not shorter to negate the condition instead of having the if and break

brittle olive
low lynx
#

no?

#

that's 107c

low lynx
#

cereal's is 106

quartz wave
#

lmao why do people still think __import__ is shorter when i literally showed them this ```
import random random.choice
import random as r r.choice
import('random').choice
from random import* choice

past plank
#

99py from random import* while input("rps?")not in'rps':0 print("you %s!"%choice(['won','lost','tied']))

brittle olive
past plank
#

imagine if you could use _ outside of the repl, this 2 character reduction would be sick

from random import*
while input("rps?")not in'rps':'won','lost','tied'
print("you %s!"%choice(_))```
quartz wave
#

i'm representing newlines/semicolons as spaces which should make no difference in character count

past plank
#

97py while input("rps?")not in'rps':from random import* print("you %s!"%choice(['won','lost','tied']))

#

oops didn't mean to ping sorry

low lynx
#

does it still import if it never goes through the loop?

quartz wave
low lynx
#

!e

while 0: from random import*
print(choice)
night quarryBOT
#

@low lynx :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | NameError: name 'choice' is not defined
past plank
tough willow
#

@gleaming linden
from random import*;o=ord;r=range;''.join(map(chr,choices([*r(65,123)]+[*r(48,58+1)],k=16))) 92

#

oh wait no

#

i forgot to remove the +1

#

from random import*;o=ord;r=range;''.join(map(chr,choices([*r(65,123)]+[*r(48,58)],k=16))) 90

gleaming linden
#
from random import*;r=range;''.join(map(chr,choices([*r(65,123)]+[*r(48,58)],k=16)))
``` get rid of `o` as well (84)
tough willow
#

i also forgot that

#
from random import*
r=range
''.join(map(chr,choices([*r(65,123)]+[*r(48,58)],k=16)))
``` still 84 but if you dont use crlf you can use newlines instead of semicolons
gleaming linden
#
from random import*
''.join(map(chr,choices([*range(65,123),*range(48,58)],k=16)))
```i forgot you could do this (should be 82)
tough willow
#

yes it's 82

rapid kayak
#

what if

#

!e

False = True

x = True

if x == False:
  print("crazy")
night quarryBOT
#

@rapid kayak :x: Your 3.11 eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     False = True
003 |     ^^^^^
004 | SyntaxError: cannot assign to False
rapid kayak
#

cry

low lynx
#

!e

from einspect import view
with view(False).unsafe() as v:
    v <<= True
x = True
if x == False:
    print('crazy')
night quarryBOT
#

@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.

crazy
tough willow
#

What does <<= do?

wheat river
#

inplace bit shit to the left

#

!e

i = 0b10
i <<= 2
print(bin(i))
night quarryBOT
#

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

0b1000
tough willow
quartz wave
tough willow
#

okay

vapid finch
sick hound
#

Rust also has inline assembly, but all of its functions are unsafe, so they expect an unsafe block

rugged sparrow
#

What is rmcof? Cross platform assembly support?

#

Ah clever

#

fishhook.asm uses something like that written in python to hook C functions

#

I need to implement the windows api for memory protection and make the jump compile at runtime to ensure it's the correct opcode. I also have a plan to implement a needle/haystack hooking protocol to allow hooks in the middle of C functions

#

Windows doesn't use mprotect/mmap afaik

#

In this case I can, the code is just a short jump op + arg. So it's just a matter of selecting the correct op

#

Yea I know I just haven't written it yet

#

@sick hound yea that lib won't work on windows (unless you build it using the posix compatibility layer)

#

Idk if that would happen automatically when python builds it

dry mirage
rugged sparrow
#

Tbh I was toying around with using some of its internal ffi functions

quartz wave
#

people are just doing unix-only projects that i can't play with because i'm on windows

versed eagle
#

you could use a vm

#

actually, im pretty sure windows has functions that do the same things

quartz wave
versed eagle
#

ah fair

low lynx
#

can't u like use wsl

quartz wave
low lynx
#

fair enough

#

I'm setting it up for latex stuff now and it's annoying

meager zinc
versed eagle
meager zinc
#

he didn't reply

#

lets golf something

#

what about some euler challenge

#

what about 40

#

not too simple not too hard

low lynx
#

how about a generalization of that to avoid any ambiguity of hardcoding

meager zinc
#

sure

low lynx
#

take an input integer k and print the product from i=0 to k of d_(10**i)

meager zinc
#

so for Sum[d_10^n, n=0 -> k]

low lynx
#

yeah

meager zinc
#

alright

#

lemme get a basic impl

quartz wave
meager zinc
#

use an online vm

#

it's three clicks + 10s loading for me to pull up a NixOS vm rn

#

in my browser

rugged sparrow
#

(I can also leave an internal function to exec raw asm if you want)

meager zinc
#

ok this is a base impl for #40

#
q=[9*(x+1)*10**x for x in range(20)]
def c(n):
    i=0
    while n>q[i]:n-=q[i];i+=1
    d,m=divmod(n-1,i+1)
    return int(str(pow(10,i)+d)[m])
def f(k):
    a=1
    for i in range(0,k):a*=c(10**k)
    return a
#

i think it works but correct me if it doesn't

#

any ideas to shorten it?

versed eagle
#

sorry

low lynx
#

remove spaces as well

meager zinc
#

true

low lynx
#

making f a lambda is probably possible

#

a recursive one

meager zinc
#
q=[9*(x+1)*10**x for x in range(20)]
def c(n):
 i=0
 while n>q[i]:n-=q[i];i+=1
 d,m=divmod(n-1,i+1)
 return int(str(pow(10,i)+d)[m])
f=lambda k,a=1:a if k==0else f(k-1,a*c(10**k)
#

probably works

languid hare
#

hmm a hybrid golf/runtime coding challenge would be pretty fun

meager zinc
#

c works but I messed up f apparently

versed eagle
#

congrats

meager zinc
#

nvm I think it's working?

languid hare
low lynx
#

do you have any test values?

meager zinc
#

lemme make some

languid hare
#

eg for this euler problem generating the constant and taking the product naively would be pretty short, but slow

meager zinc
#

but that would be

meager zinc
#

because the generation method is hardcoding pretty much

quartz wave
low lynx
#

I was thinking more like to avoid ```f =lambda _:some_precomputed_value``

meager zinc
#
f(0) = 1
f(1) = 1
f(2) = 5
f(3) = 15
f(4) = 105
f(5) = 210
#

test cases

#

!e ```py
q=[-~x10**x9for x in range(20)]
def c(n):
i=0
while n>q[i]:n-=q[i];i+=1
d,m=divmod(n-1,i+1);return int(str(10i+d)[m])
f=lambda k,a=1:f(k-1,a*c(10
k))if k else a
for _ in range(1,7):
print(f(_))

night quarryBOT
#

@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | <string>:1: SyntaxWarning: invalid decimal literal
002 | 1
003 | 5
004 | 15
005 | 105
006 | 210
007 | 210
meager zinc
#

Looks good

#

wait

quartz wave
meager zinc
#

yes yes