#esoteric-python
1 messages · Page 22 of 1
sure
would you like clash of code in shorten mode? i want to learn golf
saw
saw
can you join here?
to play shorten mode
oh sure
i think i sended it too fast
thats okay
yeah???
print(hex(int(input(),2)))
fk!!!
dw I submitted a longer one
sure
if someone want to play shortest code
niceee
can you try picking a harder one
no its completly random
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 😦
j=input;j()
for i in j().split():print('['+' x'[int(i)%2]+']',i)
ª
tf! thx, enjoy your dinner ill be studying that code
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
@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'}) {}
@half escarp ^ that should work along with the initial loop to apply hooks
you can hook
type.__init__to apply hooks late
what if they use a metaclass that isn'ttype?
im curious lol
Metaclass inherits from type, so you apply the hook to all subclasses of type
hm that could work yeah
!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
@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>}) {}
yea see above, you would have to reapply the hook when B is initialized
why not, in type.__init__, hook the .__init__ of the created class
yea
to have the desired behaviour
thats the best way to ensure it
also should probably have a flag to check if hooks have been applied to a given class
ah yeah
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
maybe through __prepare__
i dont remember the features being able to interact very much but now im curious
ill look into it
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)
@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'
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
hooking type.__prepare__ does not seem to work however
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```
@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'
ah yea it does work
i think that type.__dict__ is added explicitly
ah
so it would ignore slots
i wonder if there's a way to remove that after the fact
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
!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())
@rugged sparrow :warning: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
[No output]
ah
yea it just segfaults
i was hoping that they checked for NULL ptr
hm true
!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)}")
@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
You should probably use timeit
!tipy for _ in range(10_000_000): float(1)
@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
Oh I didn't know that this command existed
you can also use it in the terminal
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
Why sys.stdin.readline instead of input?
it takes too much time
You can do open(0) to read stdin
What is it supposed to do?
I question the character saving of those builtin assignments
the golfing done so far is largely syntactic
you've made it shorter using the same (large) algo
for k in j:t.extend(k)->*map(t.extend,k),
^^^
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
what is it supposed to do though?
ah
and print it
i can read that lmao
can you send the test input / expected output here?
# 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
yeah I'm reading it rn
do you know korean?
I'm korean
mhm
i didn't know that
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
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
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
aren't those both just equivalent to rotating the chunk/all the chunks by 180 degrees?
no,
Operations 5-8 are applied on entire chunks (**the chunks themselves move, while the values within each chunk remain the same)**
you rotate each chunk and then you rotate the entire matrix taking each chunk as just an element and not modifying it
Which ones?
operations 1-4 and operations 5-8
since flipping both horizontally and vertically is just 180 degree rotation
and clockwise and counterclockwise cancel
Different chunk sizes
You might run something on chunk size 4x4 then run something else on with chunk size 2x2 for example
ah
@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
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.
How can I see the local state of a high order function ?
wdym "high order"
This is my newbie code
Maybe I should say a function which has an inner function
ah. you mean, from inside an inner function, inspect the state of the outer function?
not sure if the term is correct but the outter function provides a context for the inner function , correct ?
I could start the debugger , but I am searching for the objects or attributes which are builts this context
something like locals()
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
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
__closure__ is for outside variables referenced in the inner function
not global variables though
without nonlocal the compiler can only "see" them if you don't assign to them
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
test.closure[0].cell_contents , there is my value , but it not very convinient
nevertheless thank you ! Thought it's easier to access it
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)
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])])```
you are aware that is one single line lol?
but mine is not complete
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
!e
code
that list call is illegal
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])]]))```
are all of the inputs < 10?
no
this assumes that every element of the input < 10
print(sum(x[::2])+sum(a*2-a//5*9for a in x[1::2]))
50 bytes
doesnt work
sum only takes 1 arg
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.
oh i take it back
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)```
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
@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)]
it is not listed in the docs...
the generator stuff won't execute
bc lazy evaluation
use a comprehension
I can't find a single version that supports variable sum out of the box
ye I edited it to list
in your version that has it do print(sum)
see if it is a builtin
i feel like ive seen varargs sum before
then check sum.__module__
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
I swear sum only ever worked with iterables
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
>>>
!d 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.
!d 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.
and this isn't ipython or something? very weird
oh god no i hate ipython
its super bloated and fills up the global namespace with lots pointless stuff
That is really weird tho
3.8
is it possible youve changed the implementation yourself and recompiled without realising?
i doubt that i would forget doing something like that
idk what other explanation for it there could be
though you've given me an idea
i might have something weird in $PYTHONSTARTUP
i'll go check that brb
Can you print sys.implementation?
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
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
yeah so
turns out i have some weird test script from like 2 years ago sitting in my $PYTHONSTARTUP
which replaces a ton of random builtins
thats really weird
i am very annoyed with my past self.
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)]
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?
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)]
([*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
no I tried it
no?
but if map() seemed to always be true
!e ```py
a = map(int, [])
if a:
print(a)
else:
print("no")
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
<map object at 0x7fcb9c038a30>
ah yeah
weird behavior but ye
([*map(open,s)]or(open(0),)) -> map(open,s or[0])
ahh
ooh thats a good one
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)]
for f in map(open,s or[0]):print(*re.findall(f'.*{r}.*',f.read()),sep='\n')```
should be functionally equivalent with the default behavior of re.findall
also @versed eagle ^
do you need sep="\n"? is it not included in the regex?
no unfortunately
can't you add it
!e ```py
import re
text = """
ab!c
def
ghi
jk!l
"""
r = "!"
print(re.findall(f".{r}.", text))```
@past plank :white_check_mark: Your 3.11 eval job has completed with return code 0.
['ab!c', 'jk!l']
no newline is included
!e ```py
import re
text = """
ab!c
def
ghi
jk!l
"""
r = "!"
print(re.findall(rf".{r}.\n", text))
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
['ab!c\n', 'jk!l\n']
adding r\n is shorter than sep
does . include \r?
for windows newlines
!e ```py
import re
print(re.findall(".*\n", "hello\r\nworld"))```
@past plank :white_check_mark: Your 3.11 eval job has completed with return code 0.
['hello\r\n']
import sys,re
_,r,*s=sys.argv
for f in map(open,s or[0]):print(*re.findall(f'.*{r}.*\n',f.read()))
nice
I wonder if there's a single character that corresponds to a newline
you don't need the r in fr
I feel like there might be
I think that actually breaks it
will the regex be fine with a newline character instead of \n?
yeah ^
it has to be that
how so?
not too greedy
this will definitely break if someone tries to enter a pattern like ^abc$ though
yeah...
if the last line doesn't have a newline it is also a problem
you can add a single ? to fix it tho
yeah
import sys,re
_,r,*s=sys.argv
for f in map(open,s or[0]):print(*re.findall(f'.*{r}.*\n?',f.read()))
there is
but you wouldn't be able to use it
because, it's a newline
if it was triple quoted then you'd get single character newlines
but triple quotes are rarely worth it
that'd lose more characters than it'd save
i dont think this works
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
(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
you could just add .splitlines() and then it would work as you want
and then you don't need the other part
.splitlines()
.split("\n")
!d str.split
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:
default sep = " "
if sep = None, it uses space
ah you're right
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
I thought I had a clever solution but then I noticed that round supports negative ndigits
wait it does?
i did not know that
at all
oh nice
my solution works
for negative ndigits
yea before I noticed that I had this || round = lambda i,n=0:type(i)(f'{i:.{n}f}') ||
oh wow that's quite nice
but it doesnt work for negative digits
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
I just happened to remember that fstrings round floats instead of just cutting them off
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
f'{x:b}' instead of bin(x)[2:]
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
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)
!ot
Please read our off-topic etiquette before participating in conversations.
@winter basin
that makes an assumption though
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' 
ye but it passes idk why
@serene garnet does it accept pyth by any chance?
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?
You dont need this weird decorator and all duplicate methods
Use self.__class__ instead of Vector in methods
And modify IntVector.__init__
why even have 2 classes here?
python dataclasses aren't typed, your Vector class works fine with ints
You can add .round()->Vector method
all your operations also work the exact same way
you just need to add __floordiv__ if you want that
interesting, maybe I over-engineered this.
__floordiv__ works with floats as well
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
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
why though
kind of weird behavior
I dont like generic idea
It will almost always be a vector of floats, so you need to specify T every time.
I implemented almost the same type recently. I had only one class that works with float values (you can use integers, but typechecher thinks that .x and .y are floats).
To convert to ints Point.round() method that returns tuple[int,int], so i can do x, y = p.round()
So that I can do
a = Vector(2, 0)
a += a.norm
a += a.norm
and still get an int vector like I started
I mean, you're either specifying float or T
don't see much more work here, if you truly need to support multiple types
Thats not always possible.
Vector(1,1).norm is not an integer (and not a rational too)
In my case i needed only float vectors (and sometimes int vectors).
So i typed it as a vector of floats and added conversions to ints
something like a: Vector[int] = Vector(2, 0)?
well yes but you don't need to hint that, it will be inferred
yes
def __add__(self: Point[T], rhs: Point[T]) -> Point[T]:...
in the methods you can do
def __add__(self, other: Vector[T]) -> Vector[T]:
or it can be -> Self as well
and T = TypeVar('T') from typing import Generic?
depending on if you want the return type to use the current type or the other type
You should add bound too. Because T should support addition, subtraction, division, ...
how do I do that?
if you're just supporting int and float you can do TypeVar("T", int, float)
or you'd make a runtime checkable protocol for those you need
class _Tproto(SupportsAdd, SupportsMul, ..., Protocol):...
T=TypeVar(T, bound=_Tproto)
It takes any thing that is acceptable as annotation
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?
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)
oh boy....
Otherwise V[int]+V[float] is an error
And V[A]=V[B] is error too if A and B are not the same
It is usually a good idea to use self.__class__ instead of Vector.
It wont break anything but it will work well with subclasses
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
You can use Vector[T] instead of Self. It works the same if you have only one class, but will break typing for subclasses
ok, thanks!
ooh, nice
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
>>> mybool = False
>>> for _ in iter(lambda:[print(1),print(2),print(3) if mybool else None],1):pass
1
2
1
2
...
>>> mybool = True
>>> for _ in iter(lambda:[print(1),print(2),print(3) if mybool else None],1):pass
1
2
3
1
2
3
...
``` this maybe?
while 1:print(1);print(2);[print(3)if ... else 0]
while (print(1, 2, sep="\n"), mybool and print(3)):...
not shorter
but its a fun way to do it imo
!e py set(iter(lambda l=[]:print(len(l))or l.append(1) or len(l), 10))
@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
ooh thats nice
Technically it is a do/while loop but you could swap it to normal while loop with an early bailout
while print(1,2,... and 3,sep="\n")+1:0
that would print Ellipsis
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
while print(1,2,'3'*True,sep="\n")or 1:0
the function call ones?
while loops dont like it
here's a fun one:
ooh do tell
>>> for x in range(10), x in range(10):
... print(x)
range(0, 10)
True
and range in range is well defined!
!e Heres another weird one: py x = [0] for x[0], x[0] in ((1, 2),):pass print(x)
@rugged sparrow :white_check_mark: Your 3.11 eval job has completed with return code 0.
[2]
what's happening there
single lines means there shouldn't be statements that expect indent
i didn't know you could index into the loop variables lmao
and can put in tuples or lists or etc
For allows for any assignments, so you can store into an index or an attribute
for example (x for i in range(10)) this is a single line for loop
that's quite interesting
i didn't know that
what is the point of ”3”*True
this could just be while(*map(print,'123')):0
the three should only print if a condition is true
this is 32 bytes py while 1:print("1\n2"+'\n3'*mybool)
yep
BTW the same is true for context managers. So you can `with open('file.txt') as x[0]: pass'
what about except clauses in try/except blocks?
those are harder, you can use ContextDecorator
I believe chilaxan also got one to work using bytecode manipulation
ah no it doesn't like it for except clauses
import/as statements don't like it either
it raises a SyntaxError for me
while(print("1\n2"+'\n3'*mybool),):0
^ why there is a comma?
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
although that would result in a closed file object being stored in x[0]
yo!
this only works if you already defined the name x before that loop
range(10), x in range(10) is evaluated the first to give a NameError
Can you guys help me?
with?
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?
in #esoteric-ruby maybe?
This is Ruby
what do you expect from a python server
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?
nope
okay
Closed if you check it outside the context manager scope, isn't it?
Yea
!e py import sys sys.stdout.write("hello")
@zealous burrow :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello
^
i just found the import
but didn't find the module
Bruh what if its using it for something else
can you give me all the ways that you know ?
tell me what does it prints
and search that with ctrl+f
sure
you'll find the line and the code
already did that
and u found it ?
!e
import io;_ы_ы_ы_=eval("".join(chr(_ы) for _ы in [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())
@zealous burrow :white_check_mark: Your 3.11 eval job has completed with return code 0.
If you bought this you got scammed
Search for this string i mean
being telling that for last min 💀
and if u cant find it, delete the code.
I see github at last
and go sleep
He paid $50
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
Search for “if you bought this you got scammed” in the code
!e ```py
import sys
sys.stdout.write('If you bought this you got scammed \n man just search this output fr')
@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
@sick hound search "scammed"
!e
print("I just did it fam :/")
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
I just did it fam :/
maybe the dev defined the words through out the code
Or just contact them fr
omfg there are so many diff files
search in each of them
he don't want to tell me
ask for refund
- why do u even want to see where it is getting printed
i mean the code works right ?
i already edited it but i know what i do sooo
he's completely working
but this shitty message is not appearing
!e
𩳅=chr;𩳆=ord;𩳈=divmod;𩳁=print;𩳉="""\x62\x69\x74\x5f\x6c\x65\x6e\x67\x74\x68""";𩳊="""\x5f\x5f\x63\x6c\x61\x73\x73\x5f\x5f""";𩳇=getattr;𩳀,𩳂=0O10060541316327106626054422415611*0O2*0O2*0O2*0O3*0O13,0;𩳃=(𩳇(𩳀,𩳉)()+(1<<3)-1)//1<<3-1
while 𩳀:𩳀,𩳄=𩳈(𩳀,1<<8);𩳁(𩳅(𩳄),end=𩳇(𩳅(𩳄),𩳊)());𩳂+=1
𩳁()
@tough willow :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello, world!
@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
@sick hound just post the code so we can help look
(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
!e
from einspect import impl
@impl(int)
def __getitem__(self, item):
return self
@low lynx :warning: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
[No output]
why does this sigsegv?
!e ```py
from fishhook import hook
@hook(int)
def getitem(self, item):
return self
@rugged sparrow :warning: Your 3.11 eval job has completed with return code 0.
[No output]

its crashing inside of PyGC_Collect from Py_FinalizeEx
huh
weird
@dry mirage odd crash with einspect, seems to be accessing freed memory when the interpreter finalizes
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
0.5.10
seems fine in 0.5.12
!e
from einspect import impl
@impl(int)
def __getitem__(self, item):
return self
print(1[0])
@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?
prior to 0.5.12 it didn't allocate the PyMethods struct for subclasses, but not sure why that causes the segfault
huh on the bot it is crashing when the hook is made
on my machine (0.5.11) it was crashing on gc collect
without structs on subclasses it would violate the inheritance assumption so it makes sense that it would crash somewhere
but if the subclass tp_as_xxx call is NULL that shouldn't reach the parent right?
yeah that seems to be a 0.5.10 - 0.5.11 difference
there are places that assume that if superclass->tp_as_* != NULL then subclass->tp_as_* != NULL
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
yea recursive allocation is what I found to be most stable back when I was writing fishhook
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
I haven't noticed any timing issues (since it is a one time cost at hook time i didn't worry about it)
you might not want to use object.__sizeof__ for this though, in many cases it has nothing to do with the struct size
list.__sizeof__ includes the heap allocated vector that's not with the struct, for example
!e
print(object.__sizeof__(list()))
print(object.__sizeof__(list(range(500000))))
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 40
002 | 40
i used object.__sizeof__ specifically for reasons like that
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
I'm pretty sure object.__sizeof__(o) just returns o.__basicsize__
Hmm it is different for tuples actually
Interesting
no
at least, not for ints
for ints it's int.__basicsize__ + (4 * ob_size)
(ignoring the sign bit in ob_size, that is)
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
ah
chilaxan i have a question for you
in fishhook, you create a lot of local variables in the build_orig function
(https://github.com/chilaxan/fishhook/blob/master/fishhook/fishhook.py#L181-L202)
that's so that you can use those functions even if they get hooked, right?
Yea, otherwise orig can end up in a recursive loop
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"))
@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
does esoteric = fast ish but gives you more headaches or does esoteric just mean headaches for the sake of headaches
Esoteric is usually not faster than just writing it normally, its usually shortest code possible, or abusing cpython bugs
afaik
Output time wise I don’t mind sitting for hours just to shave seconds
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
It's about as good as I can get it
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?
Not safely
why not?
is it something to do with garbage collection at the end of the python process
There are internal checks that check type using pointer equality, swapping those out would fail the checks
Subclass delegation typically
ah
Those few types might slip by but it's the kind of thing that could definitely break hard on an update
ah. that wouldnt really be worth the effort of implementing it then
Can you guys help me?
depends on what you want help with. but you're probably in the wrong channel
why do you think so?
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
!e seems to work here
from einspect import impl, orig
@impl(type(().__add__))
def __call__(self, *args):
return orig(type(().__add__)).__call__(self, *args)
@impl(int)
def __add__(self, other):
return orig(int).__add__(self, other - 1)
print(int("1") + int("1"))
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
1
!e is list to tuple supposed to work here then? weird 
(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))
@dry mirage :warning: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
[No output]
I can't really tell what the code is calling so
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")
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
is list to tuple supposed to work here then? weird
as for that, i have no clue. the list should be small enough to fit into the tuple
what's the point of moving in chunks though?
str2num=lambda s,o=[]:[o:=o+[ord(i)]for i in s]*0 or o
is there a shorter way of doing this?
what does it do?
convert a string to a list of numbers
but 2 args?
the second argument is so it can fit into a lambda
wut
its just setting o to a blank list
so i can not have errors when doing o:=o+[ord(i)]
str2num=lambda s:[*map(ord,s)]

thanks
there's no point. i found memmove in the docs after i had finished making it and im too lazy to go back and remake it with memmove.
sunk cost fallacy and all that
!e Wouldnt it just be this 🤔
from ctypes import *
def switch_ob(a, b):
a_size = object.__sizeof__(a)
b_size = object.__sizeof__(b)
if b_size > a_size:
# object `b` is too big to fit into object `a`.
# return the size difference as an error code
return b_size - a_size
memmove(id(a), id(b), b_size)
return 0 # return success
switch_ob("a", "b")
print("a" == "b")
@rugged owl :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
yep
like i said, sunk cost fallacy
Yeah, there is a few ways. Editing the grammar file directly, or the easier way making a codec with regex and just swapping your syntax to valid python
mean like add brackets insted of :
that is so hot
now just change elif to elseif
You can fork and edit their translate function probably
aight
this fr making python 20x better
I mean, as with all projects on pypi, it's open source 
You can check for yourself 
trueeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
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)
!e
from ctypes import*
x = 1000000000000000000
cast(id(x), POINTER(c_int))[6] += 1
print(x)
@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.
1000000000000000001
!e doesn't work for 30 bit boundaries though 😔
from ctypes import *
x = 100000000000000000
cast(id(x), POINTER(c_int))[6] *= 2
print(x)
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
100000000495583232
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
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```
@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
It's always gonna fail at some point
!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
@unique heath :warning: Your 3.11 eval job timed out or ran out of memory.
[No output]
you can technically increase the array size by 1 or 2 depending on alignment
but that's not really allocated memory
with python malloc=DEBUG that will have an assertion error during GC
that sounds... non-portable
alignment is scary
all CPython builds have the same alignment iirc
@dry mirage why is my thing so slow
you never assign to c so it never gets to 4
its been taking over 10 seconds now
the inner while loop never finishes
any ideas?
.
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)```
/=
use //=2 or >>=1
also the c*=3+1 is the same as c*=4
oh i mbdumb
but that wont work because the first statement checks for evenness
that's the collatz conjecture right?
wont matter
as it is now, it makes it into a float
which iirc doesn't have & implemented
yep
its taking 69 years rips
!e
n = 123
numloops = 0
while n != 1:
if n % 2:
n = n * 3 + 1
else:
n = n // 2
numloops += 1
print(numloops)
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
46
good idea (totally not gonna steal that)
__import__('random').choice is not less chars
time to obfuscoate
from random import*
while 1:
if input("rps?")in'rps':print("you %s!"%choice(['won','lost','tied']));break
short as ever
is it not shorter to negate the condition instead of having the if and break
this is even shorter
while 1:
if input("rps?")in'rps':print(f"you {__import__('random').choice(['won','lost','tied'])}!");break
no
cereal's is 106
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
99py from random import* while input("rps?")not in'rps':0 print("you %s!"%choice(['won','lost','tied']))
i think the length would've been the same if u've used f-strings
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(_))```
you forgot semi-colons
?
i'm representing newlines/semicolons as spaces which should make no difference in character count
oh wait I can save another character
97py while input("rps?")not in'rps':from random import* print("you %s!"%choice(['won','lost','tied']))
oops didn't mean to ping sorry
nice
does it still import if it never goes through the loop?
oh yeah that
!e
while 0: from random import*
print(choice)
@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
oh yeah, shoot
@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
from random import*;r=range;''.join(map(chr,choices([*r(65,123)]+[*r(48,58)],k=16)))
``` get rid of `o` as well (84)
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
from random import*
''.join(map(chr,choices([*range(65,123),*range(48,58)],k=16)))
```i forgot you could do this (should be 82)
yes it's 82
@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
cry
!e
from einspect import view
with view(False).unsafe() as v:
v <<= True
x = True
if x == False:
print('crazy')
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
crazy
What does <<= do?
@wheat river :white_check_mark: Your 3.11 eval job has completed with return code 0.
0b1000
but what does it do in einspect
move object
okay
That's a lot like a classic IOCCC entry, https://www.ioccc.org/1984/mullender/mullender.c. (Explanation at https://www.ioccc.org/1984/mullender/hint.html)
Rust also has inline assembly, but all of its functions are unsafe, so they expect an unsafe block
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
ctypes does a bunch of conditionals for platforms for its own dynamic c functions, perhaps you could do something similar?
Tbh I was toying around with using some of its internal ffi functions
people are just doing unix-only projects that i can't play with because i'm on windows
you could use a vm
actually, im pretty sure windows has functions that do the same things
yes but they're a little complicated to use
ah fair
can't u like use wsl
too lazy
use a vm
.
he didn't reply
lets golf something
what about some euler challenge
what about 40
A website dedicated to the fascinating world of mathematics and programming
not too simple not too hard
how about a generalization of that to avoid any ambiguity of hardcoding
sure
take an input integer k and print the product from i=0 to k of d_(10**i)
so for Sum[d_10^n, n=0 -> k]
yeah
too lazy
use an online vm
it's three clicks + 10s loading for me to pull up a NixOS vm rn
in my browser
I have free time tomorrow, gonna update fishhook.asm to be as universal as I can get it
(I can also leave an internal function to exec raw asm if you want)
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?
ok
well you don't need the 0 in the second function
remove spaces as well
true
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
hmm a hybrid golf/runtime coding challenge would be pretty fun
c works but I messed up f apparently
like what
oh are you a mod now
congrats
nvm I think it's working?
either optimise for speed or length
do you have any test values?
lemme make some
eg for this euler problem generating the constant and taking the product naively would be pretty short, but slow
the idea was that it's not memory bounded
but that would be
like this
because the generation method is hardcoding pretty much
shorter ```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(10k))if k else a
I was thinking more like to avoid ```f =lambda _:some_precomputed_value``
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(10k))if k else a
for _ in range(1,7):
print(f(_))
@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
q=[-~x*10**x*9for x in range(20)]
def c(n):
i=0
while n>q[i]:n-=q[i];i+=1
return int(str(10**i+~-n//-~i)[~-n%-~i])
f=lambda k,a=1:f(k-1,a*c(10**k))if k else a
``` shorter
yes yes
