#esoteric-python
1 messages · Page 20 of 1
!e @fleet bridge found something else weird ```py
corrupt = iter(lambda:0, 0)
class Cstr:
def hash(self):
return hash('iter')
def eq(self, other):
[*corrupt]
return other == 'iter'
builtins = builtins.dict if hasattr(builtins, 'dict') else builtins
oiter = builtins['iter']
del builtins['iter']
builtins[Cstr()] = oiter
print(corrupt.reduce())```
this code should not trigger a segfault, it should pass a NULL into PyBuild_Value inside of callable_iter.__reduce__ and trigger a SystemError exception. But for some reason the PyCLEAR of iterable->seq_callable is not actually clearing the pointer?
@rugged sparrow :x: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
(<built-in function iter>, (<function at 0x7f5c07b404a0>, 0))
so it is freeing the lambda but not clearing the pointer (which is a weird + big issue if it is a problem with PyCLEAR)
the extra weird bit is that I cannot trigger it on my machine, only on the bot
how do you find these things?
I was trying to find a way to execute python code when _PyEval_GetBuiltin is called
And use that to clear some attributes before they are read so that it would pass NULLs to to PyBuild_Value
hey guys
sombody can understand my code?
for x,i in enumerate(n:=list(input()[::-1])):
if x!=len(n)-1:i=int(i);n[x]='0';n[x+1]=[n[x+1],str(int(n[x+1])+1)][i>4]
print(*n[::-1],sep='')
round?
round to max digit?
carry-round to max digit?
Yeah that's probably right
yep ```pycon
for x,i in enumerate(n:=list(input()[::-1])):
... if x!=len(n)-1:i=int(i);n[x]='0';n[x+1]=[n[x+1],str(int(n[x+1])+1)][i>4]
...
1445
print(*n[::-1],sep='')
2000
it took a minute to inspect and a few seconds to figure out what it actually does
not bad imo
I can't read code on mobile
r=lambda x:r(x[1:])if'4'==x[0]else['4']<x
a,*b=input()
print(str(int(a)+r(b))+'0'*len(b))
``` golfed
wow
wait, but it doesn't work at 1-digit numbers.
it raises indexerror
oops
how about this code:
n=int(input());d=1
while n>9:n+=5;n//=10;d*=10
print(n*d)
i found an algorithm
oh that's pretty smart
yeah i googled it 🙂
I've computed the coefficients of the sin function by hand
This is more cursed than esoteric
The base formula:
Played a little with factorials of 5 and 7
Function:
sin = lambda x: (x-((x**3)/6)+((x**5)/118)-((x**7)/4482.4706564094))```
And its output is the same as output of math.sin
!e ```py
import math
sin = lambda x: (x-((x3)/6)+((x5)/118)-((x**7)/4482.4706564094))
print(math.sin(2))
print(sin(2))```
@sly root :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0.9092974268256817
002 | 0.9092974268256817
!rule english
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
!pastebin
How fast is it in comparison with math.sin() ?
!e
import timeit
sin = lambda x: (x-((x**3)/6)+((x**5)/118)-((x**7)/4482.4706564094))
print(timeit.timeit("sin(100000)", setup="from __main__ import sin"))
print(timeit.timeit("sin(100000)", setup="from math import sin"))
@turbid dragon :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0.6931726009934209
002 | 0.07194424699991941
any ideas why math.sin is faster?
Because it's written in C.
What's more it works for arguments other than 2.
it basically just is a wrapper around math.h's sin iirc
Try this:
#include<stdio.h>
#include<math.h>
double factorial(int);
void calc(float, float*);
int main()
{
int x;
float radian, result = 0;
printf("Enter value of x in degrees\n");
scanf("%d", &x);
radian = x * (3.1415926 / 180.0); // convert degrees to radians
calc(radian, &result);
printf("sin(%d) = %f\n", x, result);
return 0;
}
void calc(float num, float *res)
{
int count, n = 1, sign = 1;
for(count = 1; (n <= 10); count += 2)
{
*res += sign * (pow(num, count) / factorial(count));
n += 1;
sign *= -1;
}
}
double factorial(int num)
{
int count;
double prod = 1;
for(count = 1; count <= num; count++)
{
prod *= count;
}
return prod;
}
but what if i go and pass 10pi radians? 
Well it does not allow for that. This was an answer to an earlier question about a an implementation posted even earlier. It answers that question. I just did this for a laugh because someone wanted to see it in C. It's a very long time since I played with all that unnecessarily complicated C stuff.
typically sin and cos Taylor series approximations would shift it down to (-pi/2, pi/2) first I think

import numpy as np
def key(keÿ):
kèÿ,kéy,kéÿ,kêy,*kèy=0,0,*keÿ.shape
while kèÿ<kéÿ and kéy<kêy:
try:kêÿ=kèÿ+keÿ[kèÿ:,kéy].nonzero()[0][0]
except IndexError:kéy+=1;continue
if kêÿ!=kèÿ:keÿ[[kèÿ,kêÿ]]=keÿ[[kêÿ,kèÿ]]
keÿ[kèÿ]/=keÿ[kèÿ,kéy];keÿ[-~kèÿ:,kéy:]-=keÿ[-~kèÿ:,kéy:-~kéy]*keÿ[kèÿ,kéy:];kèy+=[(kèÿ,kéy)];kèÿ+=1;kéy+=1
for këy,këÿ in kèy[::-1]:keÿ[:këy,këÿ:]-=keÿ[:këy,këÿ:-~këÿ]*keÿ[këy,këÿ:]
return keÿ, kèy
key
what does this do exactly ```py
import numpy as np
def func(A):
a, b, c, d, *e = 0, 0, *A.shape
while a<c and b<d:
try:
B = a + A[a:, b].nonzero()[0][0]
except IndexError:
b += 1
continue
if B!=a:
A[[a,B]] = A[[B,a]]
A[a] /= A[a,b]
A[a+1:, b:] -= A[a+1:, b:b+1] * A[a, b:]
e += [(a,b)]
a += 1
b += 1
for x, y in e[::-1]:
A[:x, y:] -= A[:x, y:-~y] * A[x, y:]
return A, e
wait i forgot i removed the copy bit
!e
import numpy as np
def key(keÿ):
kèÿ,kéy,kéÿ,kêy,*kèy=0,0,*keÿ.shape
while kèÿ<kéÿ and kéy<kêy:
try:kêÿ=kèÿ+keÿ[kèÿ:,kéy].nonzero()[0][0]
except IndexError:kéy+=1;continue
if kêÿ!=kèÿ:keÿ[[kèÿ,kêÿ]]=keÿ[[kêÿ,kèÿ]]
keÿ[kèÿ]/=keÿ[kèÿ,kéy];keÿ[-~kèÿ:,kéy:]-=keÿ[-~kèÿ:,kéy:-~kéy]*keÿ[kèÿ,kéy:];kèy+=[(kèÿ,kéy)];kèÿ+=1;kéy+=1
for këy,këÿ in kèy[::-1]:keÿ[:këy,këÿ:]-=keÿ[:këy,këÿ:-~këÿ]*keÿ[këy,këÿ:]
return keÿ, kèy
arr1 = np.arange(9, dtype=float).reshape((3, 3))
arr2 = np.arange(12, dtype=float).reshape((3, 4))
arr3 = arr1.copy()
arr3[0, 0] = -1
print(arr1)
print(key(arr1))
print(arr2)
print(key(arr2))
print(arr3)
print(key(arr3))
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | [[0. 1. 2.]
002 | [3. 4. 5.]
003 | [6. 7. 8.]]
004 | (array([[ 1., 0., -1.],
005 | [ 0., 1., 2.],
006 | [ 0., 0., 0.]]), [(0, 0), (1, 1)])
007 | [[ 0. 1. 2. 3.]
008 | [ 4. 5. 6. 7.]
009 | [ 8. 9. 10. 11.]]
010 | (array([[ 1., 0., -1., -2.],
011 | [ 0., 1., 2., 3.],
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ozezacovij.txt?noredirect
I assume this is what you sent me in Discord earlier. I'll no longer be soliciting advice from individuals performing summoning of the old gods with their code.

it's just linalg tho
pandas does nested for loops to address a nested list directly by index: Blasphemy.
Stickie uses 20 different accents on the same word in one valid output: #esoteric-python
Maybe I'll just hide in here and claim that my musings are just deliberately esoteric.
ooh you just gave me a good idea
oh no
!e
from einspect import impl
from itertools import product
@impl(int)
def __matmul__(self, other):
return int(not(self&other)) # nand gate
def full_adder(è, é, ê):
return è@é@(ê@(è@é@è@(è@é@é))),è@é@è@(è@é@é)@ê@(è@é@è@(è@é@é))@(ê@(ê@(è@é@è@(è@é@é))))
for i, j, k in product(range(2), repeat=3):
print(i, j, k, full_adder(i, j, k))
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 0 0 (0, 0)
002 | 0 0 1 (0, 1)
003 | 0 1 0 (0, 1)
004 | 0 1 1 (1, 0)
005 | 1 0 0 (0, 1)
006 | 1 0 1 (1, 0)
007 | 1 1 0 (1, 0)
008 | 1 1 1 (1, 1)
it's now even more unreadable
When Sir Bankston Binary the Third created Binary back in 927 AD on the sacred tablets, I think he would be horrified to see what humanity has done.
Found another method
sin(x) = e^(X*1j)
@sly root :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0.2383187820087187
002 | 0.07195955800125375
!e ```py
import timeit
print(timeit.timeit("(2.718281828459045**(100000*1j)).imag"))
print(timeit.timeit("sin(100000)", setup="from math import sin"))
@sly root :white_check_mark: Your 3.10 eval job has completed with return code 0.
001 | 0.06613369201659225
002 | 0.08648197798174806
Hey esoteric people!
You guys seem like the people to talk to about micro optimizations. Not that such a thing should ever be entertained
But out of curiosity
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
What might I do so squeeze a little more out of this?
like 186 to 192 ```py
match self.observe():
case '\n':
yield from self.consume() # ignore
case '\r':
yield from self.consume() # ignore
this can just bepy
match self.observe():
case '\n' | '\r':
yield from self.consume() # ignore
Will that improve performance?
I figured it would have desugared into the same two checks in the bytecode
it'll certainly avoid unnecessary code duplication
Derp. Totally true
but the duplicated code should be equivalent in performance to the code if not duplicated
numerals is redundant here in lines 250 to 257 ```py
numerals = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
}
return numerals, 'ε', 'ι'
other than that i have nothing else to suggest
I guess that's a good thing! I really have taken pains in the interest of performance
I'm hoping that once converted to Cython, and with the help of some clever inlining perhaps, it'll be lightning fast
Not that lexer's need to be all that fast. But it's good to at least try
My only real concern is the chaining of yield froms. I don't really understand how all that works under the hood, but I wouldn't be surprised if it comes with some non-negligible overhead
XD It's that damn newline tokenizer. It's the only one that yields more than one token in a single pass. On the other hand, there are a few that don't yield anything, so I suppose generator mechanics clean that mess up rather nicely
!e ```py
k=6
s='E6 84 9B E3 81 97 E3 81 A6 E3 82 8B E3 82 88 E5 85 88 E8 BC A9'
i=[iter(s:=''.join(map(lambda x:x[2:],map(bin,bytes.fromhex(s)))))]*k
n=len(s)//k
r=[*map(int,map(''.join,map(map,[next]*n,[i]*n)),[2]*n)]
print(r)
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
[57, 40, 18, 27, 56, 56, 6, 23, 56, 56, 6, 38, 56, 56, 10, 11, 56, 56, 10, 8, 57, 24, 22, 8, 58, 11, 50, 41]
i love this part: [*map(int,map(''.join,map(map,[next]*n,[i]*n)),[2]*n)]
map(map, ...) is cursed lmao
what is going on here
[*map(int, # convert base 2 to ints
map(''.join, # join string
map(
map, # get an item from i
[next]*n,
[i]*n
)
),
[2]*n
)]
So basically just ```py
r = [int(''.join(j), 2) for j in i]
nope
!e
*map(print,(1,2,3))
@versed eagle :x: Your 3.11 eval job has completed with return code 1.
001 | File "<string>", line 1
002 | SyntaxError: can't use starred expression here
¯_(ツ)_/¯
!e ```py
x = ["SEGEMENTATION FAULT"]
for _ in range(100_000):
x = map(int, x)
list(x)```
@split salmon :warning: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
[No output]
Clean way to exit
This fees like a cpython bug
It is
works on my machine
had to raise it up to 2^17 iterations
but yeah just seems like the implementation of map overflows its stack if recursively evaluating itself without checks
I think it overflows into kernel space
I discovered it
!e
*map(print, (1,2,3)),```
@long fulcrum :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1
002 | 2
003 | 3
¯_(ツ)_/¯
i mean yeah
if you unpack it into a tuple
which is not the same thing as having it bare
it's literally what you said wouldn't work
i said that *map(print,stuff) wouldn't work

isnt it overflowing stack?
and it is happening in C so it cannot be checked?
>>> x = []
>>> for _ in range(100_000): x = zip(x)
...
>>> x
<zip object at 0x000001E37F6C5B40>
>>> list(x)
<crashes>
>>> x = []
>>> for _ in range(100_000): x = enumerate(x)
...
>>> list(x)
<crashes>
>>> x = []
>>> for _ in range(100_000): x = filter(bool, x)
...
>>> list(x)
<crashes>
>>> x = []
>>> for _ in range(100_000): x = reversed(x)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list_reverseiterator' object is not reversible
``` :-(
>>> x = []
>>> for _ in range(100_000): x = iter(x)
...
>>> list(x)
[]
``` this works because `iter(<iterator>)` returns iterator itself
Yea
Try a higer number (1M)
!e py x = ["wot?"] for _ in range(100_000): x = (_ for _ in x) list(x)
@split salmon :warning: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
[No output]
Yea
Its for function that yield values
Like map, zip, enum, filter, genexp, etc
Apparently it is allocated when you call the list function
Hold on, multiprocessing uses processes, lets see what happens
from multiprocessing import Pool
def crash(a):
print(a)
for _ in range(100_000):
a = (_ for _ in a) # func calls are expensive
list(a)
with Pool(4) as p:
p.map_unordered(crash, [0, 1, 2, 3])```
!e py from multiprocessing import Pool import time def crash(a): print(a) for _ in range(100_000): a = (_ for _ in a) # func calls are expensive time.sleep(0.5) list(a) with Pool(4) as p: p.map_unordered(crash, [0, 1, 2, 3])
@split salmon :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 7, in <module>
003 | File "/usr/local/lib/python3.11/multiprocessing/context.py", line 119, in Pool
004 | return Pool(processes, initializer, initargs, maxtasksperchild,
005 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
006 | File "/usr/local/lib/python3.11/multiprocessing/pool.py", line 191, in __init__
007 | self._setup_queues()
008 | File "/usr/local/lib/python3.11/multiprocessing/pool.py", line 346, in _setup_queues
009 | self._inqueue = self._ctx.SimpleQueue()
010 | ^^^^^^^^^^^^^^^^^^^^^^^
011 | File "/usr/local/lib/python3.11/multiprocessing/context.py", line 113, in SimpleQueue
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/wuboxuleke.txt?noredirect
Lol piping failed ig
@split salmon :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 "/usr/local/lib/python3.11/multiprocessing/context.py", line 119, in Pool
004 | return Pool(processes, initializer, initargs, maxtasksperchild,
005 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
006 | File "/usr/local/lib/python3.11/multiprocessing/pool.py", line 191, in __init__
007 | self._setup_queues()
008 | File "/usr/local/lib/python3.11/multiprocessing/pool.py", line 346, in _setup_queues
009 | self._inqueue = self._ctx.SimpleQueue()
010 | ^^^^^^^^^^^^^^^^^^^^^^^
011 | File "/usr/local/lib/python3.11/multiprocessing/context.py", line 113, in SimpleQueue
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/usilelusec.txt?noredirect
@split salmon :x: Your 3.11 eval job has completed with return code 1.
001 | File "<string>", line 12
002 | p.map_unordered(crash, [0, 1, 2, 3])
003 | ^
004 | IndentationError: unindent does not match any outer indentation level
!e py from multiprocessing import Pool import time def crash(a): print(a) for _ in range(100_000): a = (_ for _ in a) # func calls are expensive time.sleep(0.5) list(a) with Pool(4) as p: print("hi");p.map_unordered(crash, [0, 1, 2, 3])
@split salmon :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 "/usr/local/lib/python3.11/multiprocessing/context.py", line 119, in Pool
004 | return Pool(processes, initializer, initargs, maxtasksperchild,
005 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
006 | File "/usr/local/lib/python3.11/multiprocessing/pool.py", line 191, in __init__
007 | self._setup_queues()
008 | File "/usr/local/lib/python3.11/multiprocessing/pool.py", line 346, in _setup_queues
009 | self._inqueue = self._ctx.SimpleQueue()
010 | ^^^^^^^^^^^^^^^^^^^^^^^
011 | File "/usr/local/lib/python3.11/multiprocessing/context.py", line 113, in SimpleQueue
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/jetozayexa.txt?noredirect
!e py from multiprocessing import Pool import time def crash(a): print(a) for _ in range(100_000): a = (_ for _ in a) # func calls are expensive time.sleep(0.5) list(a) with Pool(4) as p: print("hi");p.map_unordered(crash, [0, 1, 2, 3])
@split salmon :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 "/usr/local/lib/python3.11/multiprocessing/context.py", line 119, in Pool
004 | return Pool(processes, initializer, initargs, maxtasksperchild,
005 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
006 | File "/usr/local/lib/python3.11/multiprocessing/pool.py", line 191, in __init__
007 | self._setup_queues()
008 | File "/usr/local/lib/python3.11/multiprocessing/pool.py", line 346, in _setup_queues
009 | self._inqueue = self._ctx.SimpleQueue()
010 | ^^^^^^^^^^^^^^^^^^^^^^^
011 | File "/usr/local/lib/python3.11/multiprocessing/context.py", line 113, in SimpleQueue
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/evalukegih.txt?noredirect
!e py from multiprocessing import Pool import time def crash(a): print(a) for _ in range(100_000): a = (_ for _ in a) # func calls are expensive time.sleep(0.5) list(a) with Pool() as p: print("hi");p.map_unordered(crash, [0, 1, 2, 3])
@split salmon :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 "/usr/local/lib/python3.11/multiprocessing/context.py", line 119, in Pool
004 | return Pool(processes, initializer, initargs, maxtasksperchild,
005 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
006 | File "/usr/local/lib/python3.11/multiprocessing/pool.py", line 191, in __init__
007 | self._setup_queues()
008 | File "/usr/local/lib/python3.11/multiprocessing/pool.py", line 346, in _setup_queues
009 | self._inqueue = self._ctx.SimpleQueue()
010 | ^^^^^^^^^^^^^^^^^^^^^^^
011 | File "/usr/local/lib/python3.11/multiprocessing/context.py", line 113, in SimpleQueue
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/iripitutim.txt?noredirect
@split salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.
['usr', 'snekbox', 'lib64', 'lib', 'etc']
There is no dev shm
@split salmon :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 | OSError: [Errno 30] Read-only file system: '/dev'
@split salmon :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 | OSError: [Errno 30] Read-only file system: '/tmp'
exit = lambda:(l:=(p:=__import__("ctypes").cdll.LoadLibrary("libc.so.6")).malloc(16)) and p.free(l)
segfault in python speedrun
(linux-only)
doesn't this work with mingw?
general windows python, no it doesn't
sad
my approach works on Windows too:
exit = lambda:__import__("ctypes").c_char_p.from_address(0)
51 ```py
import ctypes;f=lambda:ctypes.c_int.from_address(0)
import ctypes;exit=lambda:ctypes.c_int.from_address(0) # 54
import ctypes as _;exit=lambda:_.c_int.from_address(0) # 54
from ctypes import c_int as _;exit=_.from_address # 49
import ctypes as _;exit=_.c_int.from_address # 44
from os import _exit as exit # 28
exit needs a status though
and it doesn't "segfault" like the .from_address() stuff do
piping is a funny word
!e ```py
import ctypes;f=lambda:ctypes.string_at(0)
f()
@rugged sparrow :warning: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
[No output]
what about shortest segfault without importing ctypes 👀
somthing like this
deep C-level recursion
!e x=[];[*[(x:=zip(x))for _ in [0]*100000][-1]]
@fleet bridge :warning: Your 3.11 eval job has completed with return code 0.
[No output]
!e 42 ```py
x=[];[*[(x:=zip(x))for _ in[0]*10**5][-1]]
@sick hound :warning: Your 3.11 eval job has completed with return code 0.
[No output]
if you're going to do it that way, normal loop is shorter
36
x=[]
for _ in[0]*10**6:x=zip(x)
[*x]
though it doesn't segfault either way
so, a bit pointless
+3 using map(id, instead which should segfault
can you do 10e6 there or does it have to be an int?
there must be an int
is 9^9 greater than 10^6?
35 then
why 10e6 if you can do 1e9 ?
cant use that in range though
dw chilaxan
that segfaulted on my machine
its just the bot being weird
x=[];[[x:=zip(x)for()in[x]*6**7],*x]
``` weird
Chatgpt made rock paper scissors and guess my number in as few characters as possible, what do you guys think?
(These are all in 1 line of code)
a,b=input().lower(),input().lower();print("D"if a==b else"1W"if a+b in("rockpaperscissors","scissorspaperrock","paperscissorsrock")else"2W")
import random as r;a,g=r.randint(1,100),0;exec("g=int(input());print('LHW'[a>g::2][a<g::-2])\nwhile a!=g:")
I mean, it's definitely not the shortest possible
also using exec is kinda cheating
since using a \n in an exec
gets around 1 lining
also also that doesn't even work
~~```py
a,b=('rockpaperscissors'.find(input().lower())for _ in(0,1));print('LWD'[(a+b==9)-(a>=b)+(a==b)])
```py
a,b=('rockpaperscissors'.find(input().lower())for _ in(0,1));print([f'{[a<b,a>b][a+b==9]+1}W','D'][a==b])
``` 106 vs 141, still shorter
doesnt even work because of SyntaxError
I think you could remove like scissors and do functionality with -1
oh yeah
75 chars
a,b=('rp'.find(input().lower()[0])for _ in'__');print('D12 WW'[(a-b)%3::3])
assuming a few things about the input
66 chars ```py
print('D12 WW'[eval("'rp'.find(input().lower()[0])-"*2+'0')%3::3])
!e no ctypes
import gc
def g():
v = object()
yield v
next(x for x in gc.get_referrers(v) if isinstance(x, tuple))[-1]
tuple(g())
@dry mirage :warning: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
[No output]
!e ```py
import gc
def g():
v=object()
yield v
next(x for x in gc.get_referrers(v)if isinstance(x,tuple))[-1]
tuple(g())
@sick hound :warning: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
[No output]
i have a good way to do it, import a module compiled with mypyc :)
def g():
v=object()
yield v
next(x for x in __import__('gc').get_referrers(v)if isinstance(x,tuple))[-1]
tuple(g())
length is 118, 4 longer than mine
https://www.nas.nasa.gov/hecc/support/kb/common-causes-of-segmentation-faults-(segfaults)_524.html why does nasa have this type of support?
!epy (x:=[],[x:=map(int,x) for _ in range(100000)],list(x))
@arctic skiff :warning: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
[No output]
!epy (x:=(),[x:=map(int,x) for _ in range(100000)],[*x])
@arctic skiff :warning: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
[No output]
!e```py
print(len('(x:=(),[x:=map(int,x) for _ in range(100000)],[*x])'))
@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.
51
esoteric Python? I'm ready to release my skill of using assembly language though .dll in my projects
mov rax, offset point
point: lock jmp rax
don't think you're in the right spot
dll. that's more of a #c-extensions type of thing
!e @dry mirage heres another weird way of raising SystemError ```py
def bug():
if bug.clear:
return 1
else:
bug.clear = True
list(bug.iterator)
return 0
bug.iterator = iter(bug, 1)
bug.clear = False
next(bug.iterator)
@rugged sparrow :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 11, in <module>
003 | SystemError: Objects/object.c:722: bad argument to internal function
this can 100% be shorter

Objects/object.c lines 720 to 724
if (v == NULL || w == NULL) {
if (!_PyErr_Occurred(tstate)) {
PyErr_BadInternalCall();
}
return NULL;```
abuses this part of calliter_iternext ```c
static PyObject *
calliter_iternext(calliterobject *it)
{
PyObject *result;
if (it->it_callable == NULL) {
return NULL;
}
result = _PyObject_CallNoArgs(it->it_callable); // clears the iterable inside this call
if (result != NULL) {
int ok;
ok = PyObject_RichCompareBool(it->it_sentinel, result, Py_EQ); // which means that `it->it_sentinel` is NULL here
if (ok == 0) {
return result; /* Common case, fast path */
}
722 is rich compare?
for whatever version of 3.11 the bot is running
so it_sentinel got set to NULL here?
yea, because bug exhausts its own iterator
amazing
I guess this just needs another check of it->it_sentinel == NULL after the pyobject call?
store it->it_sentinel (dangerous, need to keep track of ref counts) or that ^
!e -2 chars ```py
(x:=(),[x:=map(int,x)for _ in range(99999)],[*x])
@meager zinc :warning: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
[No output]
!e ```py
def b():
if b.c:return 1
b.c=1
[*b.i]
b.i=iter(b,1)
b.c=0
next(b.i)
@meager zinc :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 7, in <module>
003 | SystemError: Objects/object.c:722: bad argument to internal function
yea that works too, I didn't want to golf mine so it was more clear where the bug comes from
unfortunately you cannot use walrus on attributes
or it would be shorter
is it possible to un-inherit from a class during runtime?
yeah
import ctypes
{ "NULL": ctypes.c_voidp.from_address(0) }
it's a null pointer wrapped in a regular python object pointer
it's perfectly fine
oops i was thinking of something else
You can change __class__ in some cases
You can make .i and .c globals instead
ctypes.POINTER(ctypes.c_int)() creates a null int pointer @half escarp
that's access checked by ctypes
a.k.a doesn't immediately halt
This is probably way too long, but I tried using global
def b():global i,c;return 1if c else((c:=1)&0)*[*i]
c=0
next(i:=iter(b,1))
@rugged sparrow :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 | SystemError: Objects/object.c:722: bad argument to internal function
creates a void* from the data at address 0 from my understanding there
One doesn't have safety around it (creates data from the pointer) and gets dereferenced by print(), the other is technically a ctypes wrapper around it
pretty much if you do anything with c_voidp.from_address(0) you will segfault
because the void* gets used as a PyObject* ?
I believe so
that's from the wrapper
lemme find the source
Looks like <NULL> comes from object.c:
https://github.com/python/cpython/blob/3.11/Objects/object.c#L413-L414
Objects/object.c lines 413 to 414
if (v == NULL)
return PyUnicode_FromString("<NULL>");```
looks like it's not a PyObject* because that would be handled by that code
so I'm not quite sure what's happening
There's three different things:
import ctypes
# Creates a void pointer from 0, segfault upon dereference
c_voidp.from_address(0) # segfault
# Creates a `ctypes` POINTER safety-checked wrapper
ctypes.POINTER(ctypes.c_int)() # <NULL>
# Creates a PyObject* that is handled in `object.c`
ctypes.py_object() # py_object(<NULL>)
Looks like the first two are PyCData_Type and PyCPointer_Type
https://github.com/python/cpython/blob/main/Modules/_ctypes/_ctypes.c
One stores the pointer (so it's not safe), the other stores a pointer to the pointer (so it's safer)
what's pythonapi?
oh
Looks like that returns a pointer to a PyObject*
hmm
Looks like it's a PyObject* -> NULL
*not really null
it's a pointer to a PyObject with empty memory
so like 00000000000 in memory
No, I don't think so
Because v is a pointer to valid memory, it's just all zeroes
(or it might be garbage? not sure)
Actually it seems like it's garbage
So v (the PyObject* containing the PyListObject*) has random stuff (0101101011110101...) and it will show up as py_object(MEMORY_ADDRESS) e.g. py_object(17192621)
Is 00000000000 equivalent to 0?
as a number, yes
Appears to use malloc in the definition
Ah nevermind
it does use calloc
This is the line: op->ob_item = (PyObject **) PyMem_Calloc(size, sizeof(PyObject *));
I meant memory context wise
Idk what a 0000000000000000 PyObject would actually be...? I would presume it would either trigger some error or be something like None
I think it's null
Like, would 00000000000 point to the same memory as 0
Is what I was asking
it is null?
null *PyObject pointer is still null
that creates a new list with a sized allocation
and returns the PyObject pointer
PyList_New(1) would create a list object with size 1 allocation and return a pointer to that object
!e
from ctypes import *
PyList_New = pythonapi.PyList_New
PyList_New.restype = py_object
PyList_New.argtypes = [c_int]
ls = PyList_New(3)
print(ls)
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
[<NULL>, <NULL>, <NULL>]
well the memory gets allocated and it doesn't point to 0, but it does technically count as NULL still.
null pointers just don't point to valid memory, it doesn't have to be 0
Ah i see
!e ```py
print(len('(x:=(),[x:=map(int,x)for _ in range(99999)],[*x]) '))
@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.
50
Its only 1 char short
100% so you making this in 0 chars?
at this point that's just hardware changes
!e
(x:=(),[x:=map(int,x)for _ in range(99999)],[*x])
print(x == 1)
@dense nova :warning: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
[No output]
-1 bits of ram is enough
[*x] causes seg fault which crashes before executing print
Or because it does too much recursion on the C side?
yes that seems to be the consensus
bruh you talk in this channel, respect bruh
This place needs to be alive xD
i need to practice wolf:(
golfing?
i was doing a easy exercise in codewars
the kata is
The length of your code should be less or equals to 44.
Your code should be one line.
The length of the reference solution is 37.```
@test.it("Basic Tests")
def tests():
test.assert_equals(f("HelloWorld"), 4)
test.assert_equals(f("Codewars"), 7)
test.assert_equals(f("X"), 0)
test.assert_equals(f("findX"), 0)```
my code
def f(s):
s = s[::-1]
m = 0
for x in s:
if x.isupper():
m = s.index(x)
break
return m```
you want a golf for this?
the cata is about golf
it doesnt take if the code is not in one single line
About golfing too
Onelining is easy
return next(filter(str.isupper,string[::-1]))
this is code golf so my use of filter doesn't count
don't smite me pls
it said reversed string so i think so?
yeah reversed
f=lambda s:[*map(str.isupper,s[::-1])].index(1)
``` easy fix
if it does, then this works
f=lambda s:[*map(str.isupper,s[::-1])].index(1)
ah
denball got to it first
f=lambda s:next(filter(str.isupper,s[::-1]))
is shorter
next and reduce are the go-tos when you want to one line a for loop imo
for the cases it does work
what the heck with codewars he said this code is too long
probably not golfed very well, but
def f(s): return [*map(lambda x:x.isupper(), s[::-1])].index(True)
``` works
ohh wait
ah
you used the same approach we did previously
lambda x:x.isupper() is just str.isupper tho
up here
me am blind apparently 🤦
its ok lol
since you can call a class' method with just the class and manually pass in self
i didnt read half the problem
before i started
writing stuff
so i missed the reversed bit
im pretty sure this is the shortest it can be
however you can try it in
https://www.codewars.com/kata/62f8d0ac2b7cd50029dd834c/train/python if you want
is this even correct? it returns the letter, you're supposed to return the index
oh true
in which case we're back to here
there's one single error
47 should be less or equal to 44.
in reference to len
huh
oh duh
wait
hmm
still not trivial nvm
oh wait we want index from back
i have this so far
f=lambda s:['@'<c<'['for c in s[::-1]].index(1)
but still 47
44? that's 43
unlock the solutions?
yep i got a 34
||```py
f=lambda s:s[-1]>'Z'and-~f(s[:-1])
wow
booom yeahh baby
that is
a good one
this returns False for X and findX instead of 0
ah it doesn't test strictly to 0
i just glanced at it and saw recursion and was like "OHHHH"
well good thing to note for the future
when in doubt try recursion
Is regex allowed?
Finding first upper
sure, but importing it is way more characters than it is worth
and it's probably longer even still
eh ```py
import re;f=lambda s:re.search('[A-Z]',s).start()
f=lambda s:next(i for i in range(len(s))if'@'<s<'[')
longer than what i thought of
but shorter than what you have
ok got it
yeah regex would suck here
how can i do this in one like, trying to capitalize the first letter without disturbing the others
a = ' '.join(input()).split()
a[0] = a[0].upper()
print(''.join(a))```
.capitalize()?
!e ```py
print("hi there".capitalize())
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hi there
.title() does a similar thing but that counts ' as separate words
There's a method in string somewhere that does that
!d string.capwords
string.capwords(s, sep=None)```
Split the argument into words using [`str.split()`](https://docs.python.org/3/library/stdtypes.html#str.split "str.split"), capitalize each word using [`str.capitalize()`](https://docs.python.org/3/library/stdtypes.html#str.capitalize "str.capitalize"), and join the capitalized words using [`str.join()`](https://docs.python.org/3/library/stdtypes.html#str.join "str.join"). If the optional second argument *sep* is absent or `None`, runs of whitespace characters are replaced by a single space and leading and trailing whitespace are removed, otherwise *sep* is used to split and join the words.
this does the job exactly how you want it to ```py
a=a[0].upper()+a[1:]
full code ```py
a=input()
a=a[0].upper()+a[1:]
one line would look like ```py
a=(a:=input())[0].upper()+a[1:]
get python 3.8+
can someone help me upload a text file in python and read it?
i just don’t know how to know the location and input it in code, the file is saved on my desktop
go to windows make it so that indexing searches all folders, after that search for ur file copy path paste it in ur input(if ur using windows)
jus do ctrl n paste the contents of the text file and save as text file and input ur relative path
import os
base_path = "/path/to/directory/holding/file/"
filename = "text.txt"
path_to_file = os.path.join(base_path, filename)
fd = open(path_to_file , 'r')
is that wrong
do we have an error?
we could do r"/path/to/..." instead of current one
not a directory error
single / could cause an error
also tried os.chdir('file:///Users/myname /Desktop/text.txt')
///?
that gave a file not found error but the location was copy and pasted from the url that opened when i opened the file on google chrome
yea that's a url not a file path
if u have a file explorer right click copy path?
u can move the text file to current working dir or simply google how to copy path of a file in mac
kk
the path here would just be /Users/myname/Desktop/text.txt
not a directory error
so something like
from pathlib import Path
with Path("/Users/myname/desktop/text.txt").open() as f:
# do stuff
...
YES!
also, this really isn't the channel for this question
No
U need r"<filename>" ?
yesh
its only a problem with \ paths, there is no issues with /
ok sorry did / instead of \
ihave returned
anyway what are we doing
:incoming_envelope: :ok_hand: applied mute to @verbal spear until <t:1676556886:f> (10 minutes) (reason: discord_emojis rule: sent 225 emojis in 10s).
The <@&831776746206265384> have been alerted for review.
It was done with a oneliner and 77 characters (including spaces)
!e for z in"啕⪪䗑⯪坵⺺嵝㨮嵝⺺坵⯪䗑⪪啕":print(f'{ord(z):015b}'.translate({49:"⬜",48:"⬛"}))
@verbal spear :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | ⬜⬛⬜⬛⬜⬛⬜⬛⬜⬛⬜⬛⬜⬛⬜
002 | ⬛⬜⬛⬜⬛⬜⬛⬜⬛⬜⬛⬜⬛⬜⬛
003 | ⬜⬛⬛⬛⬜⬛⬜⬜⬜⬛⬜⬛⬛⬛⬜
004 | ⬛⬜⬛⬜⬛⬜⬜⬜⬜⬜⬛⬜⬛⬜⬛
005 | ⬜⬛⬜⬛⬜⬜⬜⬛⬜⬜⬜⬛⬜⬛⬜
006 | ⬛⬜⬛⬜⬜⬜⬛⬜⬛⬜⬜⬜⬛⬜⬛
007 | ⬜⬛⬜⬜⬜⬛⬜⬛⬜⬛⬜⬜⬜⬛⬜
008 | ⬛⬜⬜⬜⬛⬜⬛⬛⬛⬜⬛⬜⬜⬜⬛
009 | ⬜⬛⬜⬜⬜⬛⬜⬛⬜⬛⬜⬜⬜⬛⬜
010 | ⬛⬜⬛⬜⬜⬜⬛⬜⬛⬜⬜⬜⬛⬜⬛
011 | ⬜⬛⬜⬛⬜⬜⬜⬛⬜⬜⬜⬛⬜⬛⬜
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/yewijimama.txt?noredirect
this is why we typically count bytes instead of characters for codegolf
!e I tried this a while back and couldn't figure it out, don't know why..
class MatchMeta(type):
def __instancecheck__(cls, inst):
return cls.isinstance(inst)
def matching(fn):
class cls(metaclass=MatchMeta):
isinstance = fn
return cls
# ---------
@matching
def even(number):
return number % 2 == 0
for i in [3, 4, "wat%s"]:
match i:
case even():
print(i, "is even")
case _:
print(i, "is not")
@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 3 is not
002 | 4 is even
003 | wat%s is not
Did you choose each symbol manually?
UDP: is it true that I potentially can draw any image with this method?
Nope... it was reverse
I had the pattern and translated to 0/1 to int to char
!e
from einspect import impl
@impl(int | str)
def is_even(self):
return isinstance(self, int) and not self % 2
for x in (3, 4, "wat"):
print(x, x.is_even())
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 3 False
002 | 4 True
003 | wat False
that wouldn't match against a type in a match stmt tho
Nice, I haven't really had time to look at einspect yet, but the | is a nice touch. But yeah, I specifically wanted to customize match-case behaviour.
thats a cool way of making match case utilities
!e print(sum(i for i in range(1000)if i%3<1or i%5<1))
how do i golf this even more lmfao
@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <string>:1: SyntaxWarning: invalid decimal literal
002 | 233168
!e
print(sum({*(r:=range(1000))[::3],*r[::5]}))
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
233168
you wanted every number divisible by either 3 or 5 from 0 to 1000
so that's also the union of the set of every third number from 0 to 1000 and every 5th number
Your approach reminds me this lib https://github.com/LubomyrIvanitskiy/CrazyPython/tree/main/typespace
Making crazy and, in general, useless stuff by abusing Python features - CrazyPython/typespace at main · LubomyrIvanitskiy/CrazyPython
just a question why is this program faster than the other
slower:
s = input()
a =len(''.join(i for i in s if i.isupper()))
print(s.upper() if not a==len(s)*0.5 and not a<len(s)*0.5 else s.lower())
faster:
s = input()
print(s.upper() if not len(''.join(i for i in s if i.isupper()))==len(s)*0.5 and not len(''.join(i for i in s if i.isupper()))<len(s)*0.5 else s.lower())```
What makes you say the second one is faster?
have you tried using timeit?
also, if you're using input(), it'll be variant
unless you've set stdin to be something
but even then, time for system calls can vary quite a bit depending on what else is happening
!ti py s = 'example' a =len(''.join(i for i in s if i.isupper())) print(s.upper() if not a==len(s)*0.5 and not a<len(s)*0.5 else s.lower())
@arctic skiff :white_check_mark: Your 3.11 timeit job has completed with return code 0.
200000 loops, best of 5: 1.49 usec per loop
!tipy s = 'example' print(s.upper() if not len(''.join(i for i in s if i.isupper()))==len(s)*0.5 and not len(''.join(i for i in s if i.isupper()))<len(s)*0.5 else s.lower())
@night quarry forgot to respond?
!ti py s = 'example' print(s.upper() if not len(''.join(i for i in s if i.isupper()))==len(s)*0.5 and not len(''.join(i for i in s if i.isupper()))<len(s)*0.5 else s.lower())
@arctic skiff :white_check_mark: Your 3.11 timeit job has completed with return code 0.
100000 loops, best of 5: 2.22 usec per loop
You probably forgot the space between the !ti and the ` of the codeblock
yeah
because !e don't require it
!epy ...
@arctic skiff :warning: Your 3.11 eval job has completed with return code 0.
[No output]
¯_(ツ)_/¯
@last locust :white_check_mark: Your 3.11 eval job has completed with return code 0.
hi
anyways 2nd one is slower
!src e
Run Python code and get the results.
Profile Python Code to find execution time.
It's special cased in the error handler for !e, probably could for timeit too...
if you want to profile short snippets of python, timeit is generally a reliable way to go
rather than trying to make a profiler yourself
bot/exts/backend/error_handler.py lines 66 to 71
if isinstance(e, errors.CommandNotFound) and not getattr(ctx, "invoked_from_error_handler", False):
if await self.try_silence(ctx):
return
if await self.try_run_eval(ctx):
return
await self.try_get_tag(ctx) # Try to look for a tag with the command's name```
There's special handling for !eval (try_run_eval), but not !timeit
oh
timeit needs justice...
is there any one who can help me to begin python please
i'm new in this "world"
and i'm french
no just trying it, also its a module from standard library right?,can u help im getting some error
globals().update({'add_ints':lambda *_:(__:=__import__('time').time(),[__import__('time').sleep(___)for ___ in _],int(__import__('time').time()-__))[-1]})```
any ideas for golfing this?
for n in range(101):print(n,all(n%i!=0for i in range(2,n)))
It prints the numbers from 0 to 100 and indicates whether each is prime (it fails for 1, but I couldn't find a short fix)
n%i>0 is a quick char save
hmm
actually in fact n%i is enough by itself
!e
def is_prime(n):
return n>1 and all(n%p for p in range(2, n))
num = ''.join(str(int(is_prime(n))) for n in range(101))
print(f'{int(num, 2):x}')
ok definitely not worth it lmao
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
6a28a20a08a20828228220808
still not worth
!e ```py
for n in range(101):print(n,all(n%i for i in range(2,n)))
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 True
002 | 1 True
003 | 2 True
004 | 3 True
005 | 4 False
006 | 5 True
007 | 6 False
008 | 7 True
009 | 8 False
010 | 9 False
011 | 10 False
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/hurutoneto.txt?noredirect
for n in range(101):print(n,n-1>0<all(n%i for i in range(2,n)))
``` is the shortest fix i can find
!e
for n in range(101):print(n,bool(0x6a28a20a08a20828228220808>>n&1))
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 False
002 | 1 False
003 | 2 False
004 | 3 True
005 | 4 False
006 | 5 False
007 | 6 False
008 | 7 False
009 | 8 False
010 | 9 False
011 | 10 False
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ixubozavel.txt?noredirect
Smart but too long
I think you encoded it wrong perhaps
yeah I encoded it backwards
It would be a 101 bit number which the max would be x20000000000000000000000000 which is unfortunate
unless we can store it in 10e10 format somehow
but it seems unlikely
can't we do ```py
n=0x...
while n:print(bool(n%2));n//=2
!e
n = 0x6a28a20a08a20828228220808
r = f'{n:b}'[::-1]
print(f'{int(r, 2):x}', int(r, 2))
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
808220a20a08228828228a2b 39771395718504928067455191595
sure but the question is how long is it ?
that's the actual one I think
!e
for n in range(101):print(n,bool(0x808220a20a08228828228a2b>>n&1))
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 True
002 | 1 True
003 | 2 False
004 | 3 True
005 | 4 False
006 | 5 True
007 | 6 False
008 | 7 False
009 | 8 False
010 | 9 True
011 | 10 False
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/mibayuloma.txt?noredirect
wait
it's still wrong tho
hm
here's one that doesn't count 0 and 1 as prime
for n in range(101):print(n,len([i for i in range(1,n)if n%i<1])==1)
since they arent
its only a few chars longer than this
!e
def is_prime(n):
return n>1 and all(n%p for p in range(2, n))
num = ''.join(str(int(is_prime(n))) for n in range(100, -1, -1))
print(f'{int(num, 2):x}')
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
20208828828208a20a08a28ac
lemme try something
we need a counter
ah ofc
!e
for n in range(101):print(n,bool(0x20208828828208a20a08a28ac>>n&1))
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 False
002 | 1 False
003 | 2 True
004 | 3 True
005 | 4 False
006 | 5 True
007 | 6 False
008 | 7 True
009 | 8 False
010 | 9 False
011 | 10 False
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/dijocojoki.txt?noredirect
!e ```py
def is_prime(n):
return n>1 and all(n%p for p in range(2, n))
num = ''.join(str(int(is_prime(n))) for n in range(100, -1, -1))
new = ''.join('1' if 0x20208828828208a20a08a28ac >> n & 1 else '0' for n in range(100, -1, -1))
print(f'{num}\n{new}\n{new[::-1]}')
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 00010000000100000100010000010100010000010100000100000100010100010000010100000100010100010100010101100
002 | 00010000000100000100010000010100010000010100000100000100010100010000010100000100010100010100010101100
003 | 00110101000101000101000100000101000001000101000100000100000101000001000101000001000100000100000001000
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 False
002 | 1 False
003 | 2 True
004 | 3 True
005 | 4 False
006 | 5 True
007 | 6 False
008 | 7 True
009 | 8 False
010 | 9 False
011 | 10 False
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/jehoceyazu.txt?noredirect
is that shorter than the current one?
Probably
neat
I'm on mobile someone else do the counting
for n in range(101):print(n,0x20208828828208a20a08a28ac>>n&1>0) #ties
for n in range(101):print(n,n-1>0<all(n%i for i in range(2,n))) #ties
for n in range(101):print(n,len([i for i in range(1,n)if n%i<1])==1)
for n in range(101):print(n,all(n%i for i in range(2,n))) # technically fails
oh damn
no cereal's the fix
see this
maybe we could look at expressing the huge number as like x**y + c
or something
I'll have a look at it once I get home
I can take a crack at the number with the smallest difference
go ahead
it'll take me a couple minutes brb
!e
print(f'{0x20208828828208a20a08a28ac-2**97:x}')
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
208828828208a20a08a28ac
2**97 is just the msb
i was just
taking the number
and dividing it by stuff
we're looking for like (smallish number)*(smallish number)**(smallish number) +- (smol remainder)
the remainder is really the main thing we need to minimize I think
everything else should be pretty small
i have an idea
what if you get rid of all the evens and hardcode 2 in
I'm figuring it out rn
bruteforce style
but the number is really big so I might have to figure out a threaded solution
hmm
I need to find a better method
I wonder if we could use a sort-of binary search
where we take 0 to NUM and get the number in the middle and check if a smaller number would be closer or a larger, then cut it
I can't quite figure it out but it might work
is this where we rediscover IEEE754
!e ```py
from functools import reduce as _reduce
def zip_dicts(*dicts, sentinal=None):
"yields a superset of keys from all dicts"
MY_SENTINAL = object()
def my_get(dic,k):
ret = dic.get(k, MY_SENTINAL)
if ret==MY_SENTINAL:return sentinal
return ret
keys = _reduce(lambda a,b: a|set(b), dicts, set())
for k in keys:
yield k, *(my_get(d,k) for d in dicts)
test1={1:2}
test2={3:4}
test3={5:6}
print(list(zip_dicts(test1,test2,test3)))```
@vague cairn :white_check_mark: Your 3.11 eval job has completed with return code 0.
[(1, 2, None, None), (3, None, 4, None), (5, None, None, 6)]
Is there a more canonical / pythonic way to do this?
for use like this:py for k,v1,v2,v3 in zip_dicts(d1,d2,d3): ...
Looks good
I hate the my_get() in there, but I'm paranoid that somewhere in the library there's a mapping object whose .get() raises errors when default=None and I specifically want a default of None to be possible.)
Oh, that argument should probably be renamed to default.
it's longer and less esoteric, but this works:
!e
d1 = {'a': 1, 'b': 2, 'c': 3}
d2 = {'x': 7, 'y': 8, 'z': 9}
for kv1, kv2 in zip(d1.items(), d2.items()):
k1, v1 = kv1
k2, v2 = kv2
print(k1, v1, k2, v2)
@flint hollow :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | a 1 x 7
002 | b 2 y 8
003 | c 3 z 9
Use a simple if instead of get, then
... that also could be useful, but not what I needed.
Yea that's a different thing
Thurisatic's code
That's what you replied to I assume?
yes
!e ```py
from functools import reduce as _reduce
def zip_dicts(*dicts, default=None):
"""yields a superset of keys from all dicts"""
keys = _reduce(lambda a,b: a|set(b), dicts, set())
for k in keys:
yield k, *(d.get(k, default) for d in dicts)
test1={1:2}
test2={3:4}
test3={5:6}
print(list(zip_dicts(test1,test2,test3)))```
Ayo
@haughty nova :white_check_mark: Your 3.11 eval job has completed with return code 0.
[(1, 2, None, None), (3, None, 4, None), (5, None, None, 6)]
Ok right?
Yes, that's exactly what I meant by, my_get() shouldn't be needed.
i think what grass is doing is, for each key in the set of all the keys, put all the values that correspond with that key from each dict into the tuple
and use the default value when a dict doesn't contain a value for that key
Correctus
!e
Better example I suppose ```py
from functools import reduce as _reduce
def zip_dicts(*dicts, default=None):
"""Yields a superset of keys from all dicts"""
keys = _reduce(lambda a,b: a|set(b), dicts, set())
for k in keys:
yield k, *(d.get(k, default) for d in dicts)
test1={1:2, 3:8}
test2={3:4, 9:25}
test3={5:6, 1:100}
print(list(zip_dicts(test1,test2,test3)))```
@haughty nova :white_check_mark: Your 3.11 eval job has completed with return code 0.
[(1, 2, None, 100), (3, 8, 4, None), (5, None, None, 6), (9, None, 25, None)]
I think you don't have to worry about custom mappers having an odd get method which would raise errors, but if you want to foolproof for user defined stuff```py
def ensure_get(d, key):
return d[key] if key in d else default
for ...
yield k, *(ensure_get(d, k) ...) ```
Don't think you can or should foolproof beyond that
fair enough.
If they have a strange get implementation that seems like more of a problem with that custom mapper than something here.
Also, maybe I'm missing something but you might consider moving this to a help channel - see #❓|how-to-get-help
I wish I remembered which Mapping was the problem. It may have been fixed since 3.5 when I started...
But I don't want help, I already closed my library and moved on, I just enjoyed the general-ness of the solution I found and wanted to A) share, and B) seek creative inspiration how to make it better.
i mean the Mapping type from collections.abc has get as one of its methods so if it doesn't then that's their issue i think
I think the name of the function should be changed to
def zip_dicts(D*, default=None):
for k in {k for k in d.keys() for d in D}:
yield k, *(d.get(d,default) for d in D)
test1={1:2}
test2={3:4}
test3={5:6}
print(list(zip_dicts(test1,test2,test3)))
Because while it zips
you dont need functools

Zip yields values as an intersection, as a shortest of all iterables
Nice!
Here it is unioning, equal or longer than all iterables
this is really more dict_zip_longest yeah
you have the asterisk the wrong way around
oop sorry about ping
D* algorithm
!e
def zip_dicts(*D, default=None):
for k in {k for d in D for k in d.keys()}:
yield k, *(d.get(k, default) for d in D)
test1={1:2}
test2={3:4}
test3={5:6}
print(list(zip_dicts(test1,test2,test3)))
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
[(1, 2, None, None), (3, None, 4, None), (5, None, None, 6)]
for k in d should work the same as for k in d.keys() i think
Yes
ah true
on this, best i've found so far is
(206*6936**7+0xeb81c62d490d4a28ac) # new
0x20208828828208a20a08a28ac # old
which is significantly longer still
i'm about to switch to using numpy so i can actually run the code im using for larger values since i think you'll need much larger values to get that remainder down
from a quick search doesn't seem like having it of the form a*b**p-c yields anything better
I can't create code that's efficient enough
i'm just doing this so far
num = 0x20208828828208a20a08a28ac
results = []
for b in range(3, 10000):
for a in range(1, 5000):
if foo(x := log(num, b) - log(a, b)) < 1e-7:
print(a, b, x)
results.append((a, b, x))
where foo is just x - int(x)
i have a feeling p-adic numbers could be helpful for this
but idk enough about them to utilize anything important
I feel like solving for the smallest a and b that provide the smallest x difference for any number n of the form a**b-x=n could be a really useful problem in general
We could also try encoding the number using modular arithmetic
But it would likely be similar length
just a**b isn't very restrictive tbh
You can solve for a with any b and solve for b with any a (logs + sqrt), and solve for x with either of those. n is given.
If you could figure out one then you would be good
also if we could figure out a guess-improvement method like Shor's algo or Newton's method that would be interesting. Also, a modified Shor's could be helpful. If we could get it O(N) that would be impressive. Currently it looks for prime factors and is O(N^2).
is our number prime or not?
nope divisible by 4
that's obvious since 0 and 1 are composite ig
here's the prime factorization btw
73442231024708479 * 5058929 * 271 * 79 * 5 * 2**2
took my computer ages to check that last number for primality
really should add wheel factorization
I can't get 1 to work right, but otherwise it's fine.
x=1
y=1
while x<101:print(x,y%x+1==x);y*=x;x+=1
couldnt u do x:=1
Needs to be x:=x+1 if I understand you right
@verbal spear :x: Your 3.11 eval job has completed with return code 1.
001 | File "<string>", line 1
002 | while x<101:print(x,y%x+1==x) or y,x =y*x,x+1
003 | ^^^^^^
004 | SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
@verbal spear :x: Your 3.11 eval job has completed with return code 1.
001 | File "<string>", line 1
002 | while x<101:print(x,y%x+1==x) or (y,x =y*x,x+1)
003 | ^^^^^^
004 | SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
!e x=1
y=1
while x<101:
print(x,y%x+1==x) or exec("x,y = x+1,y*x")
@verbal spear :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1 True
002 | 2 True
003 | 3 True
004 | 4 False
005 | 5 True
006 | 6 False
007 | 7 True
008 | 8 False
009 | 9 False
010 | 10 False
011 | 11 True
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/faruqiveko.txt?noredirect
wait, another way for a sieve? also, 1 is neither a prime or a composite number
hello
wilson's theorem is pretty slow for a primality test
even naive trial division is faster
fine for this tho
!e
x=y=1
while x<101:print(x,y%x>1<x);y*=x;x+=1
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1 False
002 | 2 False
003 | 3 True
004 | 4 True
005 | 5 True
006 | 6 False
007 | 7 True
008 | 8 False
009 | 9 False
010 | 10 False
011 | 11 True
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/irehedomap.txt?noredirect
wait
doesn't work for 2 or 4
because 1! is 1 and 4! is that one case where the residue is nonzero
that's incredibly annoying
my mouth drop when i see stickie and n0oO0oOob codes
🤔
!e I can fix 1 with
x=y=1
while x<101:print(x,y%x+1==x>1);y*=x;x+=1
48 bytes.
@vapid finch :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1 False
002 | 2 True
003 | 3 True
004 | 4 False
005 | 5 True
006 | 6 False
007 | 7 True
008 | 8 False
009 | 9 False
010 | 10 False
011 | 11 True
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/uterukonid.txt?noredirect
Actually it's even worse than that. I compute the factorial over the integers, so pretty soon you're doing lots of big integer arithmetic, and not long after, it eats all your memory.
(Well, I guess "not long" is relative. It'll go for a long time. But way less long than if you computed the factorial modulo x.)
!e
import struct, math
def fxor(a, b):
rtrn = []
a = struct.pack('d', a)
b = struct.pack('d', b)
for ba, bb in zip(a, b):
rtrn.append(ba ^ bb)
return struct.unpack('d', bytes(rtrn))[0]
print(fxor(float("inf"),1))
@muted cipher :white_check_mark: Your 3.11 eval job has completed with return code 0.
2.0
yes
how to get 2 without 2
ok wtf
!e
import struct, math
def fxor(a, b):
rt = []
a = struct.pack('d', a)
b = struct.pack('d', b)
for ba, bb in zip(a, b):
rt.append(ba ^ bb)
return struct.unpack('d', bytes(rt))[0]
print(fxor(float("inf"),3))
@muted cipher :white_check_mark: Your 3.11 eval job has completed with return code 0.
1.5
1+1
~-3
0b10
7//3
int(chr(50))
len((len,len))
len((len((len,len)),len((len,len))))
8 ** (1/3)
4**.5
__name__.__len__().__bool__().__add__(__name__.__len__().__bool__())
sum(-~a for a, b in zip(iter(int, 1),'xx'))
how long can we make this
i mean you could always just add as many .__call__s as you want
!e
print((("а" > "a") + ("a" < "а")))
@karmic pumice :white_check_mark: Your 3.11 eval job has completed with return code 0.
2
pulled a sneaky there
!e
print((("а" > "a") + ("a" < "а")))
print((("a" > "а") + ("a" < "а")))
print((("a" > "а") + ("а" < "a")))
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 2
002 | 1
003 | 0
!e ```py
from inspect import*
print(getframeinfo(currentframe()).lineno)
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
2
!e print(len(((),())))
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
2
!e print(True+True)
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
2
!e print(2)
@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.
2
!e ```py
import sys
print(sys._getframe().f_lineno)
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
2
!e
print((lambda x:(a:=x/2,[a:=1+x/a**2for _ in range(x*5)])[1][-1].__int__())(4))
@wheat river :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <string>:1: SyntaxWarning: invalid decimal literal
002 | 2
!e
print((lambda x:(a:=x/2,[a:=(1).__add__(x.__truediv__(a.__pow__(2)))for _ in range(x*5)])[1][-1].__int__())(4))
@wheat river :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 | File "<string>", line 1, in <lambda>
004 | File "<string>", line 1, in <listcomp>
005 | AttributeError: 'NotImplementedType' object has no attribute '__pow__'. Did you mean: '__doc__'?
rip
!e
from collections import deque
@print
@deque.popleft
@deque
@int.__str__
@int.__sizeof__
@int
@lambda _:_.__doc__
class _:
'1'
@wheat river :white_check_mark: Your 3.11 eval job has completed with return code 0.
2
!e
@print
@int
@next
@str.__iter__
@int.__str__
@int.__sizeof__
@int
@lambda _:_.__doc__
class _:
'1'
@wheat river :white_check_mark: Your 3.11 eval job has completed with return code 0.
2
!E
import re, types
from math import e, pi, tau
print(types.LambdaType(compile(f"{dir(types)[round(pi ** e - pi * e)][:int(tau)].casefold()} λ :--λ--λ", "sadness", "eval"), globals())()(re.T))
@near siren :white_check_mark: Your 3.11 eval job has completed with return code 0.
2
!e import os
print("hi")
print('<style>body{background-color:"red"}</style>')
os.system('touch pic.png')
@verbal spear :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | hi
002 | <style>body{background-color:"red"}</style>
!e
code
!eval [python_version] <code, ...>
Can also use: e
Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside of them.
By default your code is run on Python's 3.11 beta release, to assist with testing. If you run into issues related to this Python version, you can request the bot to use Python 3.10 by specifying the python_version arg and setting it to 3.10.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!
@verbal spear :warning: Your 3.11 eval job has completed with return code 0.
[No output]
!e import os
print(os.system(' ls - ali'))
@verbal spear :white_check_mark: Your 3.11 eval job has completed with return code 0.
32512
!e ```py
from random import randint
print(randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, 99999))))))))))))))))))))))))))))))))))))))))))))))))))))))))
@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.
0
!e
from random import randint
print(randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, 99999))))))))))))))))))))))))))))))))))))))))))))))))))))))))
@tough willow :white_check_mark: Your 3.11 eval job has completed with return code 0.
0
!e
from random import randint
print(randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, 999999999999999))))))))))))))))))))))))))))))))))))))))))))))))))))))))
@tough willow :white_check_mark: Your 3.11 eval job has completed with return code 0.
0
Ok
!e ```py
from random import randint
print(randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, randint(0, 2**100))))))))))))))))))))))))))))))))))))))))))))))))))))))))
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
177459
it has very weird distribution
!e ```py
print(
len(
((()
,( ),
() ,()
,(),
(),
()
,
((),)),())
)
)
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
2
neat
Hey @sick hound!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
so um i made code to see how long it takes to reach the end and
still not done
after hours
so latest took 1h 44m 49s 835 ms to reach that point
fun
You can probably compute the probability
but I'm not particularly familiar with it
you could probably speed it up with C and threading and SIMD vector operations
(or Rust)
also who is mango time
not bad, but you can do the entire calculation inside the transformer class and speed it ut
!e assert "" == ""
@meager zinc :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 | AssertionError
anyone here want to fork black with me and make it remove all the spaces
or any other formatter
!raw 1077068322354507908
== Raw message ==
!e `assert "" == ""`
!e print(-42.0 .is_integer())
@smoky scarab :white_check_mark: Your 3.11 eval job has completed with return code 0.
-1
alr do we want to do black or something like autopep8 instead
Honestly would have to looking at the repositorys first to see
only 2 remaining after 5h 38m 36s 258ms
unfortunately i have to stop now
experiment stopped at 8h 31m 38s 454 ms 646 us 400+ ns
iteration 2687300449
I can create one for you if you still need it, seems like a simple function
!pypi LoneDruid
made it myself after asking this
seems cool, have you thought of creating a repository for it? I'm sure a lot of people would have fun ideas for contributing
what is this
@wheat river
j is the amount of randint()s
ah k
https://youtu.be/lYOKkoVHWTU guess this fits into here
Link to code: https://replit.com/@TheGameWARloXx/Bad-Apple-but-with-python-turtle-dots-updated#main.py
Takes about 17 minutes to render due to the addition of a 0.35 second gap between frames to keep the framerate consistent. Both the quality, the number of FPS and not skipping every other frame can be easily increased but would take up way too...
heya everyone, any reverse engineers here? i have a simple obfuscated script and i'd like to know how good is the protection and how long it will take someone to break it (i'm testing a obfuscator i made) if you want to give it a try here is the files, dm me with any feedback you have
https://cdn.discordapp.com/attachments/879026043846017044/1077314731469176902/files.zip
Hey @magic wraith!
It looks like you tried to attach file type(s) that we do not allow (.zip). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.
Feel free to ask in #community-meta if you think this is a mistake.
unzipped files here
obf.py: https://paste.pythondiscord.com/aqinobojav.py
main.py:
from obf import string_hash
# task: find the algorithm for string_hash function
print(string_hash('Hello World!'))
print(string_hash('1234567890'))
print(string_hash('⫊ṣՖᔲᗶ'))
thats really cool! if you begin with 2**20, when will it in average reach 0?
I thoght after 20 iterations, but it is less.
the expected number of times starting at 2**20 for it to reach 0 should be around 15.44
Min 1 is enough reach 0 max 20**20 = 4000 ig
the expected number of iterations needed for a number n would be around 1+H_n where H_n is the nth harmonic number
(if the given number is 20
@magic wraith at first glance it looks like a virtual machine?
B.a is the instruction pointer
global A is the stack? (or one of them)
Let me take a look
yeah, a vm with a constant program and a few stacks
A for data, F and G as a form of call stack
the globals manipulation and the large number of instructions makes it kind of annoying to read though
Anyone know a way to make this sliding window algo shorter
81 bytes / chars
import sys;a,w=sys.argv[1:];print([a[i:i+int(w)]for i in range(len(a)-int(w)+1)])
that's true
i've been trying to make the shortest bytecode possible though
well yes
but it doesn't work on every python code
for example async, yield or recursive functions
class x:
class y:
pass
!e py def deco(func): def inner(obj, *args, **kwargs): return obj.__class__(*args, **kwargs) return inner class A: @deco def __init__(self): ... x = A()
@magic wraith :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 3, in inner
004 | File "<string>", line 3, in inner
005 | File "<string>", line 3, in inner
006 | [Previous line repeated 496 more times]
007 | RecursionError: maximum recursion depth exceeded
ruby golfing vs python golfing
i've been seeing ruby can more shorter the codes than python does
Ye, ruby is generally better for code golf
Can you show some examples of golfed code in ruby? I think it is suitable for this channel
puts"Hello world!"
Ruby does not require parentheses in method calls
fun thing about lua is that it also doesn't require parentheses for table literals and strings
Also, one should remember that in Python, a newline is only required after each decorator and before block declarations. So, this is completely valid:
def three():r=range(10);return[1for i in r if i==2][0]
for i in range(4):print(i)
also notice that : has higher precedence than ;
so py if thing:first();second() is equivalent to py if thing: first() second() rather than py if thing: first() second()
!e
import gc
import ctypes
gc.get_referents(list.__dict__)[0]["map"] = lambda _, fn: list(map(fn, _))
ctypes.pythonapi.PyType_Modified(ctypes.py_object(list))
print([1, 2, 3, 4].map(lambda x: x+1))
@odd light :white_check_mark: Your 3.11 eval job has completed with return code 0.
[2, 3, 4, 5]
kek
!e ```py
from fishhook import hook
@hook(list, name='map')
def list_map(self, fn):
return type(self)(map(fn, self))
print([1, 2, 3, 4].map(lambda x: x+1))
@rugged sparrow :white_check_mark: Your 3.11 eval job has completed with return code 0.
[2, 3, 4, 5]
print("".join(chr(ord(i)-0b100111000000000) for i in "么乥乬乬乯丠乷乯乲乬乤丠乵乷乵"))
anyone got a code here that doesn't use variable or things like print()? Basically 100% esoteric
don't think its possible to display stuff without print
!e ```py
open(0, 'w+').write('hello world')
@rugged sparrow :warning: Your 3.11 eval job has completed with return code 0.
[No output]
!e
print("".join(chr(ord(i)-0b100111000000000) for i in "么乥乬乬乯丠乷乯乲乬乤丠乵乷乵"))
@rough moat :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello world uwu
!e
open(0, 'w').write('hello world')
@versed eagle :warning: Your 3.11 eval job has completed with return code 0.
[No output]
that works on my machine^
my guess is that it wont work on this bc it only captures stdin/stderr
but, the 'w+' won't work
stdin is likely overwritten and your code prints to the terminal running python which isn't captured
your code prints to the terminal running python which isn't captured
that's exactly what i just said??
also wdym "overwritten"
stdin = my_stdin # my_stdin is a custom class from snekbox- similar but I added the fact that it prints to the terminal running the script
I need to look at the snekbox source
wdym you "added the fact that it prints to the terminal"
i had already said that.
im confused as to what you're saying
since you're repeating what i've already said
my guess is that it wont work on this bc it only captures stdin/stderr
not sure where this mentions the fact it's printing to the original terminal rather than another stdout
I would rather not argue about this, this is a dumb thing to argue over. would you prefer that I delete all the messages?
My guess is that it's printing to the Snekbox thread instead of the NsJail isolated thread.
not sure where this mentions the fact it's printing to the original terminal rather than another stdout
it says right there, it's not captured. and, as a side note, it's not printing to stdout at all. not sure where that came from
to my knowledge we aren't arguing?
im asking for clarification since i genuinely didnt understand what you're saying
sorry if it seemed like i was arguing with you
that wasnt my intention
i'll try to phrase my questions better in the future
open(0) is referring to the stdout of the parent process Snekbox runs
stdout in Python is referring to the stdout of the child process NsJail executes (and isolates)
stdin is not captured ever
stdout/stderr is only captured from the child process
the parent process is never captured from.
open(0) is referring to the stdout of the parent process Snekbox runs
0is the file descriptor forstdin
not stdout
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello world
that's what it was supposed to be
