#esoteric-python

1 messages · Page 20 of 1

night quarryBOT
#

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

(<built-in function iter>, (<class 'int'>, 0))
fleet bridge
rugged sparrow
rugged sparrow
#

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

night quarryBOT
#

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

(<built-in function iter>, (<function  at 0x7f5c07b404a0>, 0))
rugged sparrow
#

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

astral rover
#

how do you find these things?

rugged sparrow
#

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

serene garnet
#

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='')
gleaming linden
#

Increment?

#

Oh wait

quartz wave
#

round to max digit?

#

carry-round to max digit?

gleaming linden
#

Yeah that's probably right

quartz wave
# quartz wave carry-round to max digit?

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

gleaming linden
#

I can't read code on mobile

gleaming linden
serene garnet
#

wow

serene garnet
gleaming linden
#

oops

serene garnet
#

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

gleaming linden
#

oh that's pretty smart

serene garnet
#

yeah i googled it 🙂

sly root
#

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

night quarryBOT
#

@sly root :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 0.9092974268256817
002 | 0.9092974268256817
gleaming linden
#

!rule english

night quarryBOT
#

4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.

subtle herald
#

!pastebin

finite blaze
turbid dragon
night quarryBOT
#

@turbid dragon :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 0.6931726009934209
002 | 0.07194424699991941
finite blaze
#

any ideas why math.sin is faster?

wide crow
finite blaze
#

ah fair

#

I wonder how it looks in C

wide crow
#

What's more it works for arguments other than 2.

astral rover
wide crow
# finite blaze I wonder how it looks in C

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

but what if i go and pass 10pi radians? lemon_sentimental

wide crow
#

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.

low lynx
#

typically sin and cos Taylor series approximations would shift it down to (-pi/2, pi/2) first I think

vast basin
low lynx
#
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

quartz wave
low lynx
#

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

@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

vast basin
vast basin
#

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.

low lynx
#

ooh you just gave me a good idea

vast basin
#

oh no

low lynx
# vast basin 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))
night quarryBOT
#

@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)
low lynx
#

it's now even more unreadable

vast basin
#

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.

sly root
night quarryBOT
#

@sly root :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 0.2383187820087187
002 | 0.07195955800125375
sly root
#

!e ```py
import timeit

print(timeit.timeit("(2.718281828459045**(100000*1j)).imag"))

print(timeit.timeit("sin(100000)", setup="from math import sin"))

night quarryBOT
#

@sly root :white_check_mark: Your 3.10 eval job has completed with return code 0.

001 | 0.06613369201659225
002 | 0.08648197798174806
sly root
#

.

magic dirge
#

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

#

What might I do so squeeze a little more out of this?

quartz wave
# magic dirge https://hastebin.com/share/penerufeta.py

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

I figured it would have desugared into the same two checks in the bytecode

quartz wave
magic dirge
#

Derp. Totally true

quartz wave
#

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

magic dirge
#

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

fleet bridge
#

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

night quarryBOT
#

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

i love this part: [*map(int,map(''.join,map(map,[next]*n,[i]*n)),[2]*n)]

low lynx
#

map(map, ...) is cursed lmao

gleaming linden
#

So basically just ```py
r = [int(''.join(j), 2) for j in i]

long fulcrum
#

nope

versed eagle
night quarryBOT
#

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

¯_(ツ)_/¯

split salmon
#

!e ```py
x = ["SEGEMENTATION FAULT"]
for _ in range(100_000):
x = map(int, x)

list(x)```

night quarryBOT
#

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

[No output]
split salmon
#

Clean way to exit

split salmon
earnest wing
#

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

split salmon
split salmon
long fulcrum
night quarryBOT
#

@long fulcrum :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 1
002 | 2
003 | 3
long fulcrum
#

¯_(ツ)_/¯

versed eagle
#

i mean yeah
if you unpack it into a tuple

#

which is not the same thing as having it bare

long fulcrum
#

it's literally what you said wouldn't work

versed eagle
#

i said that *map(print,stuff) wouldn't work

long fulcrum
rugged owl
fleet bridge
#
>>> 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
split salmon
#

!e py x = ["wot?"] for _ in range(100_000): x = (_ for _ in x) list(x)

night quarryBOT
#

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

[No output]
split salmon
#

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

night quarryBOT
#

@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

split salmon
#

Lol piping failed ig

night quarryBOT
#

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

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

night quarryBOT
#

@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

split salmon
#

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

night quarryBOT
#

@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

split salmon
#

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

night quarryBOT
#

@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']
split salmon
#

There is no dev shm

night quarryBOT
#

@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'
sick hound
#
exit = lambda:(l:=(p:=__import__("ctypes").cdll.LoadLibrary("libc.so.6")).malloc(16)) and p.free(l)

segfault in python speedrun

sick hound
quartz wave
sick hound
#

sad

#

my approach works on Windows too:

exit = lambda:__import__("ctypes").c_char_p.from_address(0)
quartz wave
fleet bridge
#

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

and it doesn't "segfault" like the .from_address() stuff do

fleet bridge
#

piping is a funny word

rugged sparrow
#

!e ```py
import ctypes;f=lambda:ctypes.string_at(0)

f()

night quarryBOT
#

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

[No output]
dry mirage
fleet bridge
#

deep C-level recursion

#

!e x=[];[*[(x:=zip(x))for _ in [0]*100000][-1]]

night quarryBOT
#

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

[No output]
fleet bridge
#

🧐

#

it crashes on my pc

sick hound
night quarryBOT
#

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

[No output]
versed eagle
#

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

earnest wing
#

+3 using map(id, instead which should segfault

long fulcrum
#

can you do 10e6 there or does it have to be an int?

sick hound
low lynx
#

is 9^9 greater than 10^6?

versed eagle
#

yes

#
>>> 10^6
1000000
>>> 9^9
387420489
low lynx
#

35 then

fleet bridge
#

why 10e6 if you can do 1e9 ?

versed eagle
#

dw chilaxan

#

that segfaulted on my machine

#

its just the bot being weird

rugged sparrow
#
x=[];[[x:=zip(x)for()in[x]*6**7],*x]
``` weird
sick hound
#

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

last locust
#

I mean, it's definitely not the shortest possible

sick hound
#

How come

#

I don’t even understand it that well tbh

versed eagle
#

also using exec is kinda cheating

#

since using a \n in an exec

#

gets around 1 lining

versed eagle
sick hound
#

😂

#

Asked chatgpt so many times if it was sure it would work too

gleaming linden
fleet bridge
low lynx
#

I think you could remove like scissors and do functionality with -1

gleaming linden
#

oh yeah

low lynx
#

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

quartz wave
dry mirage
night quarryBOT
#

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

[No output]
sick hound
#

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

night quarryBOT
#

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

[No output]
sick hound
#

this is the shortest it can get (as done by me)

#

this is 114, including newlines

astral rover
#

i have a good way to do it, import a module compiled with mypyc :)

arctic skiff
sick hound
#

length is 118, 4 longer than mine

arctic skiff
#

!epy (x:=[],[x:=map(int,x) for _ in range(100000)],list(x))

night quarryBOT
#

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

[No output]
arctic skiff
#

!epy (x:=(),[x:=map(int,x) for _ in range(100000)],[*x])

night quarryBOT
#

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

[No output]
arctic skiff
#

!e```py
print(len('(x:=(),[x:=map(int,x) for _ in range(100000)],[*x])'))

night quarryBOT
#

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

51
arctic skiff
#

its @split salmon's method anyways

#

i just made it in 1 line

tranquil ermine
#

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
pure dew
#

don't think you're in the right spot

versed eagle
rugged sparrow
#

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

night quarryBOT
#

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

Objects/object.c lines 720 to 724

if (v == NULL || w == NULL) {
    if (!_PyErr_Occurred(tstate)) {
        PyErr_BadInternalCall();
    }
    return NULL;```
rugged sparrow
#

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 */
    }
dry mirage
#

722 is rich compare?

rugged sparrow
dry mirage
rugged sparrow
#

yea, because bug exhausts its own iterator

dry mirage
#

amazing

#

I guess this just needs another check of it->it_sentinel == NULL after the pyobject call?

rugged sparrow
#

store it->it_sentinel (dangerous, need to keep track of ref counts) or that ^

dry mirage
#

what should even happen here

#

StopIteration?

rugged sparrow
#

yea you can probably fall through to return NULL

#

*i think

meager zinc
night quarryBOT
#

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

[No output]
meager zinc
night quarryBOT
#

@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
rugged sparrow
meager zinc
#

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) }
earnest wing
#

it's a null pointer wrapped in a regular python object pointer

#

it's perfectly fine

#

oops i was thinking of something else

rugged sparrow
rugged sparrow
earnest wing
#

that's access checked by ctypes

#

a.k.a doesn't immediately halt

meager zinc
rugged sparrow
#

thats clever

#

!e ```py
*(i:=iter(lambda x=[1]:x and[x.pop(),*i],[])),

night quarryBOT
#

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

creates a void* from the data at address 0 from my understanding there

meager zinc
#

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

earnest wing
#

because the void* gets used as a PyObject* ?

meager zinc
#

I believe so

#

that's from the wrapper

#

lemme find the source

night quarryBOT
#

Objects/object.c lines 413 to 414

if (v == NULL)
    return PyUnicode_FromString("<NULL>");```
meager zinc
#

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

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)

old socket
gleaming linden
meager zinc
#

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 *));

old socket
meager zinc
#

Idk what a 0000000000000000 PyObject would actually be...? I would presume it would either trigger some error or be something like None

gleaming linden
old socket
#

Is what I was asking

dry mirage
#

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

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

[<NULL>, <NULL>, <NULL>]
meager zinc
# dry mirage it is null?

well the memory gets allocated and it doesn't point to 0, but it does technically count as NULL still.

dry mirage
meager zinc
#

Ah i see

arctic skiff
#

!e ```py
print(len('(x:=(),[x:=map(int,x)for _ in range(99999)],[*x]) '))

night quarryBOT
#

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

50
arctic skiff
arctic skiff
quartz wave
dense nova
#

!e

(x:=(),[x:=map(int,x)for _ in range(99999)],[*x])
print(x == 1)
night quarryBOT
#

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

[No output]
dense nova
#

huh

#

someone explain

arctic skiff
arctic skiff
sick hound
#

Or because it does too much recursion on the C side?

earnest wing
#

yes that seems to be the consensus

sick hound
indigo harbor
#

This place needs to be alive xD

sly ibex
#

i need to practice wolf:(

meager zinc
#

golfing?

sly ibex
#

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```
low lynx
#

you want a golf for this?

sly ibex
#

it doesnt take if the code is not in one single line

low lynx
#

it's about one lining

#

not golf

fleet bridge
#

About golfing too

sly ibex
#

😦

fleet bridge
#

Onelining is easy

versed eagle
#

does this work?

f=lambda s:[*map(str.isupper,s)].index(1)
#

im not sure if it does

low lynx
#
return next(filter(str.isupper,string[::-1]))
#

this is code golf so my use of filter doesn't count

#

don't smite me pls

versed eagle
#

oh wait

#

does it have to be reversed

low lynx
#

it said reversed string so i think so?

sly ibex
#

yeah reversed

fleet bridge
#
f=lambda s:[*map(str.isupper,s[::-1])].index(1)
``` easy fix
versed eagle
#

if it does, then this works

f=lambda s:[*map(str.isupper,s[::-1])].index(1)
versed eagle
low lynx
#
f=lambda s:next(filter(str.isupper,s[::-1]))

is shorter

versed eagle
#

thats nice

#

and probably a good deal faster as well

low lynx
#

next and reduce are the go-tos when you want to one line a for loop imo

#

for the cases it does work

sly ibex
flint hollow
#

probably not golfed very well, but

def f(s): return [*map(lambda x:x.isupper(), s[::-1])].index(True)
``` works
sly ibex
#

ohh wait

versed eagle
low lynx
#

lambda x:x.isupper() is just str.isupper tho

flint hollow
#

me am blind apparently 🤦

versed eagle
#

its ok lol

low lynx
#

since you can call a class' method with just the class and manually pass in self

versed eagle
#

i didnt read half the problem

#

before i started

#

writing stuff

#

so i missed the reversed bit

versed eagle
sly ibex
flint hollow
versed eagle
#

oh true

versed eagle
low lynx
#

oh index

#

then yeah

sly ibex
#

in reference to len

versed eagle
#

huh

low lynx
#

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

versed eagle
#

ooh

#

ordinals

low lynx
#

oh ofc

#

then yeah it's solved for 44 c

flint hollow
#

44? that's 43

low lynx
#

oh i had extra whitespace

#

also damn way better ideas in the solutions

sly ibex
#

unlock the solutions?

low lynx
#

yep i got a 34

sly ibex
#

what

#

what

low lynx
#

||```py
f=lambda s:s[-1]>'Z'and-~f(s[:-1])

versed eagle
#

wow

sly ibex
#

booom yeahh baby

versed eagle
#

that is
a good one

flint hollow
low lynx
#

0==False so it passes the test

#

oh that one is the first one on the solutions lmao

flint hollow
#

ah it doesn't test strictly to 0

low lynx
#

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

verbal spear
#

Is regex allowed?

low lynx
#

regex where?

#

the problem above?

verbal spear
#

Finding first upper

low lynx
#

sure, but importing it is way more characters than it is worth

#

and it's probably longer even still

quartz wave
#

longer than what i thought of

#

but shorter than what you have

low lynx
#

you need to start searching from the back

#

also that's not the most optimized one

quartz wave
#

yeah regex would suck here

low lynx
#

it'd be comparable if you didn't have to import

#

but you do

#

so not worth

fresh helm
#

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

!e ```py
print("hi there".capitalize())

night quarryBOT
#

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

Hi there
quartz wave
#

nvm

#

it disturbs the others

gleaming linden
#

.title() does a similar thing but that counts ' as separate words

#

There's a method in string somewhere that does that

#

!d string.capwords

night quarryBOT
#

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.
fresh helm
#

its one word not multiple

#

so it disturbs la letters

gleaming linden
#

Oh wait I completely misread that

quartz wave
fresh helm
#

i need to take input tho

#

can i club all in one line>

quartz wave
#

one line would look like ```py
a=(a:=input())[0].upper()+a[1:]

fresh helm
#

walrus isnt supported

#

keeps giving error

#

ty tho

quartz wave
fresh helm
#

3.11.1

#

idle still gobs me error

quartz wave
#

it will run fine

fresh helm
#

wait reinstalling

#

👍

#

works

paper shell
#

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

fresh helm
#

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)

paper shell
#

using a mac

#

and jupyter notebook

fresh helm
#

jus do ctrl n paste the contents of the text file and save as text file and input ur relative path

paper shell
#

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

fresh helm
#

do we have an error?
we could do r"/path/to/..." instead of current one

paper shell
#

not a directory error

fresh helm
#

single / could cause an error

paper shell
#

also tried os.chdir('file:///Users/myname /Desktop/text.txt')

fresh helm
#

///?

paper shell
#

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

pure dew
#

yea that's a url not a file path

paper shell
#

how do i get the file path

#

i’m very new to coding so my questions are silly sorry

fresh helm
#

if u have a file explorer right click copy path?

paper shell
#

don’t have a file explorer?

#

it’s just a text file saved on my desktop

fresh helm
#

u can move the text file to current working dir or simply google how to copy path of a file in mac

paper shell
#

kk

pure dew
paper shell
#

not a directory error

pure dew
#

so something like

from pathlib import Path
with Path("/Users/myname/desktop/text.txt").open() as f:
    # do stuff
    ...
paper shell
#

YES!

pure dew
#

also, this really isn't the channel for this question

paper shell
#

what channel

#

is better

tough willow
fresh helm
verbal spear
#

U need r"<filename>" ?

fresh helm
#

yesh

tough willow
# fresh helm

its only a problem with \ paths, there is no issues with /

fresh helm
#

ok sorry did / instead of \

unique heath
#

ihave returned
anyway what are we doing

night quarryBOT
#

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

verbal spear
#

It was done with a oneliner and 77 characters (including spaces)

verbal spear
#

!e for z in"啕⪪䗑⯪坵⺺嵝㨮嵝⺺坵⯪䗑⪪啕":print(f'{ord(z):015b}'.translate({49:"⬜",48:"⬛"}))

night quarryBOT
#

@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

past plank
restive void
#

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

@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
sonic birch
verbal spear
dry mirage
night quarryBOT
#

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

that wouldn't match against a type in a match stmt tho

restive void
rugged sparrow
unique heath
#

!e print(sum(i for i in range(1000)if i%3<1or i%5<1))

how do i golf this even more lmfao

night quarryBOT
#

@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
dry mirage
night quarryBOT
#

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

233168
unique heath
#

awht

#

confosed

#

big fusion

dry mirage
#

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

unique heath
#

um ok

#

HOLY FUCK I JUST REALIZED AND I FEEL SO STUPID NOW

sonic birch
fresh helm
#

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())```
sudden osprey
#

What makes you say the second one is faster?

fresh helm
#

i used the time module

#

and it suggests so

versed eagle
#

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

arctic skiff
#

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

night quarryBOT
#

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

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

night quarryBOT
#

@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
last locust
arctic skiff
#

because !e don't require it

#

!epy ...

night quarryBOT
#

@arctic skiff :warning: Your 3.11 eval job has completed with return code 0.

[No output]
arctic skiff
#

¯_(ツ)_/¯

last locust
#

!epy print("hi")

#

huh, cool

#

I guess it's added as an alias

night quarryBOT
#

@last locust :white_check_mark: Your 3.11 eval job has completed with return code 0.

hi
last locust
#

!src e

night quarryBOT
#
Command: eval

Run Python code and get the results.

Source Code
arctic skiff
#

!src ti

night quarryBOT
#
Command: timeit

Profile Python Code to find execution time.

Source Code
sudden osprey
#

It's special cased in the error handler for !e, probably could for timeit too...

versed eagle
#

rather than trying to make a profiler yourself

night quarryBOT
#

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```
last locust
#

There's special handling for !eval (try_run_eval), but not !timeit

arctic skiff
jaunty flame
#

is there any one who can help me to begin python please

#

i'm new in this "world"

#

and i'm french

arctic skiff
fresh helm
arctic skiff
#
globals().update({'add_ints':lambda *_:(__:=__import__('time').time(),[__import__('time').sleep(___)for ___ in _],int(__import__('time').time()-__))[-1]})```
fresh helm
#

ran it

#

same

#

error even after running

#

ok reinstalled, works now

meager zinc
#

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)

low lynx
#

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

night quarryBOT
#

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

6a28a20a08a20828228220808
low lynx
#

still not worth

meager zinc
#

!e ```py
for n in range(101):print(n,all(n%i for i in range(2,n)))

night quarryBOT
#

@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

quartz wave
low lynx
#

!e

for n in range(101):print(n,bool(0x6a28a20a08a20828228220808>>n&1))
night quarryBOT
#

@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

low lynx
#

wait

#

oh I stored it backwards I'm bad

meager zinc
#

Smart but too long

low lynx
#

yeah

#

honestly if the bool call didn't exist

#

and it actually worked

meager zinc
#

I think you encoded it wrong perhaps

low lynx
#

yeah I encoded it backwards

meager zinc
#

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

gleaming linden
#

can't we do ```py
n=0x...
while n:print(bool(n%2));n//=2

low lynx
#

!e

n = 0x6a28a20a08a20828228220808
r = f'{n:b}'[::-1]
print(f'{int(r, 2):x}', int(r, 2))
night quarryBOT
#

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

808220a20a08228828228a2b 39771395718504928067455191595
meager zinc
#

sure but the question is how long is it ?

low lynx
#

that's the actual one I think

meager zinc
#

it's shorter

#

actually it might be the same

low lynx
#

!e

for n in range(101):print(n,bool(0x808220a20a08228828228a2b>>n&1))
night quarryBOT
#

@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

low lynx
#

wait

meager zinc
#
0x6a28a20a08a20828228220808
0x808220a20a08228828228a2b
#

one shorter

low lynx
#

it's still wrong tho

meager zinc
#

hm

versed eagle
#

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

versed eagle
low lynx
#

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

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

20208828828208a20a08a28ac
meager zinc
#

lemme try something

gleaming linden
#

ah ofc

low lynx
#

!e

for n in range(101):print(n,bool(0x20208828828208a20a08a28ac>>n&1))
night quarryBOT
#

@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

meager zinc
#

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

night quarryBOT
#

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

001 | 00010000000100000100010000010100010000010100000100000100010100010000010100000100010100010100010101100
002 | 00010000000100000100010000010100010000010100000100000100010100010000010100000100010100010100010101100
003 | 00110101000101000101000100000101000001000101000100000100000101000001000101000001000100000100000001000
meager zinc
#

Yeah it provides the same numerical output

#

so idk

low lynx
#

actually wait

#

!e

for n in range(101):print(n,0x20208828828208a20a08a28ac>>n&1>0)
night quarryBOT
#

@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

low lynx
#

is that shorter than the current one?

meager zinc
#

Probably

versed eagle
#

yes

#

by 5 chars

low lynx
#

neat

versed eagle
#

well

#

its shorter than mine

#

idk if its shorter than

#

cereal's

low lynx
#

I'm on mobile someone else do the counting

meager zinc
#
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
versed eagle
#

it is the same

#

as cereals

#

and shorter than mine by 5

low lynx
#

oh damn

versed eagle
#

though, cereals also gets 1 and 0 wrong

#

iirc

meager zinc
#

63 chars

#

No he said that it was the shortest fix

low lynx
#

no cereal's the fix

versed eagle
#

nvm

#

checked it

low lynx
#

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

meager zinc
low lynx
#

go ahead

meager zinc
#

it'll take me a couple minutes brb

versed eagle
#

there's lots of repeating chunks

#

its really close to 2**97

#

if that helps at all

low lynx
#

!e

print(f'{0x20208828828208a20a08a28ac-2**97:x}')
night quarryBOT
#

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

208828828208a20a08a28ac
gleaming linden
#

2**97 is just the msb

low lynx
#

oh wait yeah

#

that won't work

versed eagle
#

i was just
taking the number
and dividing it by stuff

low lynx
#

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

gleaming linden
#

I don't think that's possible

#

the bits don't repeat

versed eagle
#

i have an idea

gleaming linden
#

what if you get rid of all the evens and hardcode 2 in

meager zinc
#

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

pure dew
#

is this where we rediscover IEEE754

vague cairn
#

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

night quarryBOT
#

@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)]
vague cairn
#

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

haughty nova
#

Looks good

vague cairn
#

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.

flint hollow
#

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

@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
haughty nova
vague cairn
#

... that also could be useful, but not what I needed.

haughty nova
#

Yea that's a different thing

#

Thurisatic's code

#

That's what you replied to I assume?

vague cairn
#

yes

haughty nova
#

!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

night quarryBOT
#

@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)]
haughty nova
#

Ok right?

vague cairn
versed eagle
haughty nova
#

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

night quarryBOT
#

@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)]
haughty nova
#

Don't think you can or should foolproof beyond that

vague cairn
#

fair enough.

meager zinc
#

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

vague cairn
#

I wish I remembered which Mapping was the problem. It may have been fixed since 3.5 when I started...

vague cairn
low lynx
#

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

haughty nova
#

I think the name of the function should be changed to

versed eagle
#
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)))
haughty nova
#

Because while it zips

versed eagle
#

you dont need functools

low lynx
haughty nova
#

Zip yields values as an intersection, as a shortest of all iterables

vague cairn
haughty nova
#

Here it is unioning, equal or longer than all iterables

low lynx
#

this is really more dict_zip_longest yeah

low lynx
#

oop sorry about ping

versed eagle
#

its ok lol

#

i sent the wrong

#

version

haughty nova
#

D* algorithm

versed eagle
#

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

@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)]
versed eagle
#

that is

#

whats intended

#

the other one is just

#

entirely wrong

low lynx
#

for k in d should work the same as for k in d.keys() i think

haughty nova
#

Yes

versed eagle
#

ah true

low lynx
#

from a quick search doesn't seem like having it of the form a*b**p-c yields anything better

meager zinc
#

I can't create code that's efficient enough

low lynx
#

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

meager zinc
#

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

low lynx
#

just a**b isn't very restrictive tbh

meager zinc
#

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

low lynx
#

is our number prime or not?

#

nope divisible by 4

#

that's obvious since 0 and 1 are composite ig

low lynx
#

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

vapid finch
#

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
vapid finch
#

Needs to be x:=x+1 if I understand you right

sick hound
#

im confused

#

esoteric hurts my head

vapid finch
night quarryBOT
#

@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 '='?
verbal spear
#

!e x=1
y=1
while x<101:
print(x,y%x+1==x) or exec("x,y = x+1,y*x")

night quarryBOT
#

@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

sick hound
manic prairie
#

hello

low lynx
#

wilson's theorem is pretty slow for a primality test

#

even naive trial division is faster

#

fine for this tho

low lynx
night quarryBOT
#

@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

low lynx
#

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

sly ibex
#

my mouth drop when i see stickie and n0oO0oOob codes

pure dew
#

🤔

vapid finch
#

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

night quarryBOT
#

@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

vapid finch
#

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

coarse void
#

my dude vibin...

muted cipher
#

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

@muted cipher :white_check_mark: Your 3.11 eval job has completed with return code 0.

2.0
muted cipher
#

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

@muted cipher :white_check_mark: Your 3.11 eval job has completed with return code 0.

1.5
muted cipher
#

hmmm

#

ieee 754 go brrr

quartz wave
versed eagle
#

~-3

low lynx
#

0b10

quartz wave
#

1<<1

#

3^1

#

7&~5

#

len(' ')

versed eagle
#

7//3

quartz wave
#

int(chr(50))

versed eagle
#

len((len,len))

muted cipher
pure dew
#

8 ** (1/3)

muted cipher
#

4**.5

quartz wave
#

__name__.__len__().__bool__().__add__(__name__.__len__().__bool__())

low lynx
#

sum(-~a for a, b in zip(iter(int, 1),'xx'))

muted cipher
low lynx
#

i mean you could always just add as many .__call__s as you want

muted cipher
#

ah so my method

#

go to __call__ hell

karmic pumice
#

!e

print((("а" > "a") + ("a" < "а")))
night quarryBOT
#

@karmic pumice :white_check_mark: Your 3.11 eval job has completed with return code 0.

2
quartz wave
low lynx
#

!e

print((("а" > "a") + ("a" < "а")))
print((("a" > "а") + ("a" < "а")))
print((("a" > "а") + ("а" < "a")))
night quarryBOT
#

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

001 | 2
002 | 1
003 | 0
karmic pumice
#

xd

#

imagine actually using it to troll people

tawny helm
#

ok

#

ok

#

ok

meager zinc
#

!e ```py
from inspect import*
print(getframeinfo(currentframe()).lineno)

night quarryBOT
#

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

2
meager zinc
#

!e print(len(((),())))

night quarryBOT
#

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

2
meager zinc
#

!e print(True+True)

night quarryBOT
#

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

2
arctic skiff
#

!e print(2)

night quarryBOT
#

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

2
quartz wave
night quarryBOT
#

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

2
wheat river
#

!e

print((lambda x:(a:=x/2,[a:=1+x/a**2for _ in range(x*5)])[1][-1].__int__())(4))
night quarryBOT
#

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

!e

print((lambda x:(a:=x/2,[a:=(1).__add__(x.__truediv__(a.__pow__(2)))for _ in range(x*5)])[1][-1].__int__())(4))
night quarryBOT
#

@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__'?
wheat river
#

rip

#

!e

from collections import deque

@print
@deque.popleft
@deque
@int.__str__
@int.__sizeof__
@int
@lambda _:_.__doc__
class _:
    '1'
night quarryBOT
#

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

2
wheat river
#

!e

@print
@int
@next
@str.__iter__
@int.__str__
@int.__sizeof__
@int
@lambda _:_.__doc__
class _:
    '1'
night quarryBOT
#

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

2
near siren
#

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

@near siren :white_check_mark: Your 3.11 eval job has completed with return code 0.

2
verbal spear
#

!e import os
print("hi")
print('<style>body{background-color:"red"}</style>')
os.system('touch pic.png')

night quarryBOT
#

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

!e

night quarryBOT
#
Missing required argument

code

#
Command Help

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

!e import os
os.system("dir")

#

!e import os
os.system(' ls - ali')

night quarryBOT
#

@verbal spear :warning: Your 3.11 eval job has completed with return code 0.

[No output]
verbal spear
#

!e import os
print(os.system(' ls - ali'))

night quarryBOT
#

@verbal spear :white_check_mark: Your 3.11 eval job has completed with return code 0.

32512
arctic skiff
#

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

night quarryBOT
#

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

0
tough willow
#

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

night quarryBOT
#

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

0
tough willow
#

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

night quarryBOT
#

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

0
tough willow
#

Ok

fleet bridge
#

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

night quarryBOT
#

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

177459
fleet bridge
#

it has very weird distribution

meager zinc
#

!e ```py
print(
len(
((()
,( ),
() ,()
,(),
(),
()
,
((),)),())
)
)

night quarryBOT
#

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

2
low lynx
#

neat

night quarryBOT
quartz wave
#

still not done

#

after hours

#

so latest took 1h 44m 49s 835 ms to reach that point

versed eagle
#

fun

meager zinc
#

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

pure dew
#

not bad, but you can do the entire calculation inside the transformer class and speed it ut

meager zinc
#

!e assert "​" == ""

night quarryBOT
#

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

anyone here want to fork black with me and make it remove all the spaces

#

or any other formatter

dry mirage
#

!raw 1077068322354507908

night quarryBOT
#
== Raw message ==

!e `​assert "​" == ""`​
smoky scarab
#

!e print(-42.0 .is_integer())

night quarryBOT
#

@smoky scarab :white_check_mark: Your 3.11 eval job has completed with return code 0.

-1
meager zinc
rugged owl
quartz wave
#

‫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

magic wraith
#

I can create one for you if you still need it, seems like a simple function

karmic pumice
night quarryBOT
#

Package to convert stuff to esoteric stuff, maybe something else later.

magic wraith
wheat river
quartz wave
#

j is the amount of randint()s

pure dew
#

the code would also be a lot nicer

#

for big project, yea

wheat river
summer orchid
magic wraith
night quarryBOT
#

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.

next flame
verbal spear
low lynx
arctic skiff
low lynx
#

the expected number of iterations needed for a number n would be around 1+H_n where H_n is the nth harmonic number

arctic skiff
rugged sparrow
#

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

earnest wing
#

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

rugged owl
#

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

i've been trying to make the shortest bytecode possible though

rugged sparrow
#

how are you making the bytecode?

#

did you write your own compiler?

magic wraith
#

well yes

#

but it doesn't work on every python code

#

for example async, yield or recursive functions

drowsy anvil
#
class x:
  class y:
    pass
magic wraith
#

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

night quarryBOT
#

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

ruby golfing vs python golfing

#

i've been seeing ruby can more shorter the codes than python does

proper vault
#

Ye, ruby is generally better for code golf

fleet bridge
#

Can you show some examples of golfed code in ruby? I think it is suitable for this channel

sick hound
#

puts"Hello world!"
Ruby does not require parentheses in method calls

quartz wave
sick hound
#

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)
magic wraith
#

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

odd light
#

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

@odd light :white_check_mark: Your 3.11 eval job has completed with return code 0.

[2, 3, 4, 5]
odd light
#

kek

rugged sparrow
#

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

night quarryBOT
#

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

[2, 3, 4, 5]
rough moat
#

print("".join(chr(ord(i)-0b100111000000000) for i in "么乥乬乬乯丠乷乯乲乬乤丠乵乷乵"))

sturdy rune
#

anyone got a code here that doesn't use variable or things like print()? Basically 100% esoteric

low lynx
#

don't think its possible to display stuff without print

rugged sparrow
night quarryBOT
#

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

[No output]
rugged sparrow
#

huh that should have worked

#

wack

low lynx
#

I phrased that wrong

#

I don't think it's possible to display stuff without any letters

rough moat
#

!e
print("".join(chr(ord(i)-0b100111000000000) for i in "么乥乬乬乯丠乷乯乲乬乤丠乵乷乵"))

night quarryBOT
#

@rough moat :white_check_mark: Your 3.11 eval job has completed with return code 0.

Hello world uwu
versed eagle
night quarryBOT
#

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

[No output]
versed eagle
#

my guess is that it wont work on this bc it only captures stdin/stderr

versed eagle
meager zinc
versed eagle
#

your code prints to the terminal running python which isn't captured
that's exactly what i just said??

also wdym "overwritten"

meager zinc
#

I need to look at the snekbox source

versed eagle
#

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

meager zinc
#

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.

versed eagle
#

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

versed eagle
#

im asking for clarification since i genuinely didnt understand what you're saying

meager zinc
#

okay

#

here's what I'm trying to clarify

versed eagle
#

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

meager zinc
#

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.

versed eagle
#

open(0) is referring to the stdout of the parent process Snekbox runs
0 is the file descriptor for stdin

#

not stdout

meager zinc
#

oh

#

yeah

#

I missed that

#

!e ```py
open(1, 'w').write('hello world')

night quarryBOT
#

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

hello world
meager zinc
#

that's what it was supposed to be