#esoteric-python

1 messages · Page 19 of 1

versed eagle
#

so by definition you cant allow full python syntax in the problem

#

.

#

Today I got a question about whether it's possible if you forbid underscores in the malicious code. I figured this channel would be up to the challenge.

#

by definition, if the goal is succeeded, the "full python syntax" cannot be allowed

#

because underscores would have to be disallowed

#

preventing arbitrary code exec was part of preventing underscores

rugged sparrow
#

i said a limit subset of python code right here

#

you disagreed

old socket
#

What is going on rn

versed eagle
#

which i thought was implicit

#

sorry if i didnt make that clear.

rugged sparrow
#

now you are just backtracking

versed eagle
#

im saying the same thing that i have been saying

rugged sparrow
#

plenty of the code i sent after that message contained dunders and underscores and you never clarified

versed eagle
#

because none of those need the underscores to function

#

if you know the sizes of things beforehand, which presumably you would, you can use constants

#

and if you dont know the sizes, you can brute force it

#

given that there aren't really that many likely possibilities

rugged sparrow
versed eagle
#

so then the bug is irrelevant

#

because to use it, you first have to get something that would already be disallowed

rugged sparrow
#

if this has been your argument from the beginning, then we agree, you would have to limit it to such a small subset that you could not call it python

versed eagle
#

the point was to disallow underscores and underscored names

#

that's part of the goal

#

__new__ is an underscored name, and so would be disallowed

rugged sparrow
earnest wing
#

have fun without any of the stdlib btw

versed eagle
rugged sparrow
#

then what point are you trying to make

versed eagle
#

you would have to limit it to such a small subset that you could not call it python
i never said that?

versed eagle
# rugged sparrow then what point are you trying to make

that it is theoretically possible, in the python language (specifically, with cpython) to do AT LEAST one of the following given a piece of code:
determine whether it grants user access to underscore names statically OR prevent such access during runtime

rugged owl
versed eagle
#

@old socket
no im just distracted and trying to do other stuff at the same time, so it takes a long time to type stuff lol

#

no large paragraph here

rugged sparrow
versed eagle
#

this entire time

old socket
#

I'm super confused right now but none the less, I am enjoying the show

rugged sparrow
#

right here you disagreed when i said limited subset

versed eagle
#

i wasn't disagreeing with limited subset

#

i was replying to this

you would have to disable large chunks of the language in order to keep it secure, to the point it would be hard to call it python

#

of course it's limited, underscore names aren't allowed!

#

we've been through this

#

the goal is to prevent access to underscore names

#

by definition, achieving the goal creates a subset of python

rugged sparrow
#

what are you arguing then?

rugged sparrow
versed eagle
rugged sparrow
#

sorry, my bad

split stirrup
#

I have been reliably informed by my nieces that "dude" is non-gendered

rugged sparrow
still charm
#

this thread's name scares me

rugged sparrow
night quarryBOT
#

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

<built-in method __subclasses__ of type object at 0x7f121a099580>
rugged sparrow
#

*but you only get the resulting value as a string

versed eagle
#

from a strictly security standpoint, that wouldn't matter as much as writing to it, but for this challenge that would have to be prevented
could probably be prevented by hooking str.format to not work if it would format into a dunder

rugged sparrow
old socket
#

I think so at least, I only remember __format__ takes in a specification that you can use to determine what to do

rugged owl
old socket
#

Playing with codecs has been very fun, but some annoying stuff I've come across when developing in poetry is that

#

Sometimes if the package you are working on isn't installed, and you add your .pth file

#

It'll corrupt poetry stopping you from installing new packages

#

You need to delete the poetry cache

#

Somehow adding the .pth before installing your codec package will make poetry error with a json decoder error

rugged sparrow
old socket
rugged sparrow
old socket
#

I think it's failing whenever you have add a .pth file that references the current module (the one you are developing) before you do poetry install to add the current module to site-packages

#

So I think it'll error in perhaps "normal" cases but only if someone messes with .pth files

rugged sparrow
#

ah, so poetry install loads site which loads .pth files, and yours fails because the package it references isnt installed yet

rugged sparrow
old socket
#

Just deleting the cache, re-installing env and done

#

But until you do that, you cannot do poetry install ... and some other commands

#

I'm pretty sure poetry debug info is also gonna report that you have no current directory

rugged sparrow
old socket
#

I'll see if I can reproduce right now

#

I'll send the error as well

#

Oh yeop looks like it's reproduce-able, but I forgot the exact steps to get it there under "norma" circumstances

#

So I forced it to error

old socket
#

And yea, after this happens poetry reports that there is no cache directory

#

Or it errors when trying to get a cache directory? *

rugged sparrow
#

thats a weird failure

old socket
#

Yea

#

I want to take a nap, so I'll probably write an issue later

#

But I want to first figure out the exact steps I did to get it normally, cause I reproduced just barely by manually causing the issue to happen

rugged owl
#

!e

def b(c,d=0,data=[0]*30000,o=""):
    c,_=list(c),"".join(c);b={};s=[]
    for i,char in enumerate(c):
        if char=="[":s.append(i)
        elif char=="]":b[s.pop()]=i;b[i]=b[-~s[0]]
    while d<len(c):
        char=c[d];d+=(char==">")-(char=="<");d=0 if d<0 else d
        data[d]=255&(data[d]+(char=="+")-(char=="-")),
        o+=chr(data[d])if char=="."else o;data[d]=ord(input()[0])if char==","else data[d]
        d=b[d]if char in"[]"and data[d]^48else d+1
    return o
print(b("++++++++++[>+++++++>++++++++--->+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."))

night quarryBOT
#

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

001 | <string>:10: SyntaxWarning: invalid decimal literal
002 | Traceback (most recent call last):
003 |   File "<string>", line 12, in <module>
004 |   File "<string>", line 5, in b
005 | IndexError: list index out of range
rugged owl
#

what am i doing wrong here pain

pure dew
#

access after pop

sonic birch
#

Hi, not sure it's the right channel, but.. is it possible having a regex1 check whether it implies regex2? For example regex1=.+.gmail.com and regex2=.+.com so regex1 -> regex2

topaz haven
#

How do I make statements inside linear lambda?

For example,

x = 1
print("hi")
x += 1
print(x)
#

Or sth like this

cloud fossil
#

Lambdas can't have statements in them

#

But they can have a function call which runs statements

low lynx
#

!e

f=lambda:(x:=1)and(print('hi'))or(x:=x+1)and(print(x))
f()
night quarryBOT
#

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

001 | hi
002 | 2
quartz wave
arctic skiff
night quarryBOT
#

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

001 | hi
002 | 2
finite blaze
#

why x:=1 works in lambdas but x=1 doesn't?

earnest wing
#

expression vs statement

versed eagle
night quarryBOT
#

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

001 | hi
002 | 2
earnest wing
#

in a nutshell, you can think of it this way

  • expressions can be put inside parentheses ()
  • statements cannot, because that causes a syntax error
finite blaze
#

Alright, thanks

versed eagle
#

nope, it saves a char @arctic skiff

arctic skiff
versed eagle
#
>>> len("""(lambda:(x:=1,print('hi'),x:=x+1,print(x)))()""")
45
>>> len("""(lambda x=1:(print('hi'),x:=x+1,print(x)))()""")
44 
arctic skiff
#

!e```py
(x:=1,print('hi'),x:=x+1,print(x))

night quarryBOT
#

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

001 | hi
002 | 2
arctic skiff
#

!epy print(len("""(x:=1,print('hi'),x:=x+1,print(x))"""))

night quarryBOT
#

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

34
versed eagle
arctic skiff
versed eagle
#

the point is to do it inside a lambda

versed eagle
#

but the point is still the same

arctic skiff
versed eagle
#

it's meant to be inside a lambda

finite blaze
arctic skiff
night quarryBOT
#

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

001 | hi
002 | 2
arctic skiff
#

!epy print(len("""(lambda x:(print('hi'),x:=x+1,print(x)))(1)"""))

night quarryBOT
#

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

43
arctic skiff
versed eagle
night quarryBOT
#

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

001 | hi
002 | 2
arctic skiff
versed eagle
#

oh wait

night quarryBOT
#

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

001 | hi
002 | 2
versed eagle
#

now the prints

#

can be combined

arctic skiff
#

!epy (lambda x:print('hi\n',x:=x+1))(1)

versed eagle
#

!e

(lambda x:print(f'hi\n{x+1}'))(1)
night quarryBOT
#

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

001 | hi
002 | 2
#

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

001 | hi
002 |  2
arctic skiff
versed eagle
#

was gonna keep using walrus until then lol

arctic skiff
#

!epy print('hi\n2')is shortest

night quarryBOT
#

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

001 | hi
002 | 2
versed eagle
#

not a lambda though

arctic skiff
versed eagle
#

what?

calm loom
#

Llama

#

🦙

versed eagle
#

what llama

#

there's no llama

calm loom
#

!e

(lambda :print("hi\n2"))()
night quarryBOT
#

@calm loom :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | hi
002 | 2
calm loom
rugged owl
night quarryBOT
#

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

001 | hi
002 | 2
rugged owl
#

1 less char EzPepe

rough moat
#
print(__import__("os").system("")or"","\n".join(["\n"]+[f"\x1b[38;5;{[80,181,231,181,80][y]}m█"*15 for y in range(5)]),"\x1b[0m")
#

wont work in !e or whatever

#

it uses ansi color

restive void
#

What's the system("") for?

earnest wing
#

Force color in windows command prompt

dry mirage
#

!e

from einspect import view

view(1).swap(0)

print(0 > 1)
print(bool(0), bool(1))

print(0 * 0 == 1.0)
night quarryBOT
#

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

001 | True
002 | True False
003 | True
dry mirage
#

🥴 slightly cursed

versed eagle
dry mirage
#

0 * 0 is folded to 0 == 1.0

#

and since 0 is now 1, it's true

meager zinc
# rugged owl !e ```py def b(c,d=0,data=[0]*30000,o=""): c,_=list(c),"".join(c);b={};s=[] ...

The smallest that I could come up with (slightly different format, dynamically allocated stack) but here it is (this could probably be better):

def b(p):
    s=[i:=0];c=''
    for o in p:c+=' '*i+[f'i+=1\n{" "*i}if i>=len(s):s+=[0]','i-=1','s[i]+=1','s[i]-=1','print(end=chr(s[i]))','s[i]=ord(__import__("sys").stdin.read(1))','while s[i]:','s','']['><+-.,['.find(o)]+'\n';i+=(92-ord(o))*(o in'][')
    exec(c)
meager zinc
quartz wave
meager zinc
#

if True and if __debug__ do get const folded unfortunately

split salmon
#

!e I made this on phone py __import__('pickle').loads(bytearray(map((lambda x:x-4),__import__('gzip').decompress(bytearray(map((lambda x:x-1 if x!=0xff else x),[1,1,1,92,39,114,106,209,1,145,131,49,206,133,104,59,52,171,26,6,102,198,214,43,198,6,6,154,63,3,10,139,161,11,163,221,179,147,139,161,115,163,221,139,131,221,203,181,159,3,153,94,77,200,12,70,188,135,126,50,160,41,206,79,41,45,225,77,104,51,12,244,212,115,76,148,185,20,2,3,195,26,153,226,108,255,3,100,191,154,235,1,9,140,32][::-1]))))))

night quarryBOT
#

@split salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.

Hello world!
split salmon
dry mirage
split salmon
dry mirage
#

!pypi einspect is not a builtin 👀

night quarryBOT
#

Extended Inspect - view and modify memory structs of runtime objects.

split salmon
#

Sh-t

night quarryBOT
#

src/einspect/views/view_cfunction.py line 61

def vectorcall(self) -> vectorcallfunc:```
acoustic quail
#
for i in range(len(l.split())):
    try: eval(f'f2r{int(i//rows)}')
    except: exec(f'f2r{int(i//rows)} = Frame(f2)')
    exec(f'f2r{int(i//rows)}c{i%rows} = Button(f2r{int(i//rows)}, font = f,\
           text = l.split()[i], command = lambda: e1.insert(END, l.split()[{i}][1]))')
    exec(f'f2r{int(i//rows)}c{i%rows}.pack(side = LEFT)')
    exec(f'f2r{int(i//rows)}.pack()')```a snippet of a thing i'm doing
potent flare
#

what in the actual fuck

#

why

acoustic quail
#

because i don't want to make 143 buttons arranged in 10 rows

#

manually

#

that do almost the same thing

low lynx
#

why not use enumerate?

acoustic quail
#

what

low lynx
#

if you're doing this to be esoteric then sure go ahead and do whatever but you could use a list instead of exec statements

low lynx
acoustic quail
#

i want the value to be saved

#

exec(f' ··· lambda: ··· l.split()[{i}][1])) works as needed

··· lambda: ··· l.split()[ i ][1]) gives
··· lambda: ··· l.split()[142][1]), which works as if all buttons were the last one

quartz wave
#

does exactly the same thing

finite blaze
#
for i in range(1000):
    if i%3==0 or i%5==0: s+=i
#

how can I oneline something like this?

fleet bridge
finite blaze
#

I just found a pretty interesting page

#

with a lot of problems to golf

last locust
gleaming linden
low lynx
#
3*((999//3)*(999//3+1)//2)+5*((999//5)*(999//5+1)//2)-15*((999//15)*(999//15+1)//2)

for a pure mathematical solution

dry mirage
#

it's only used when internal python C calls target the function iirc

#

but faster call without making tuples and dicts

rugged sparrow
#

!e thats why ```py
from fishhook import *

@hook(type(lambda:0))
def call(self, *args, **kwargs):
print(self, args, kwargs)
return orig(self, *args, **kwargs)

def foo(a):pass

foo(1)

night quarryBOT
#

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

[No output]
rugged sparrow
#

(for better or for worse)

dry mirage
rugged sparrow
#

if you null out PyFuncType->tp_vectorcall to switch to using tp_call then you crash due to recursion

dry mirage
#

python defined funcs also have a separate tp_call and tp_vectorcall?

#

also why does that crash from recursion firT

rugged sparrow
#

because that overwrites with the default tp_call which looks up the py_object in the class mapping and then uses PyObject_Call

dry mirage
#

isn't tp_vectorcall optional?

rugged sparrow
#

the recursion issue will only trigger if you use fishhook to hook PyFuncType.__call__ and then null PyFuncType.tp_vectorcall

#

at least it did in 3.8 when i was first developing fishhook

dry mirage
#

or does that still recurse

rugged sparrow
#

i believe it still recurses as ctypes uses PyObject_Call or some derivative internally

dry mirage
#

oh the type

#

the object instance at least only has vectorcall? pithink

rugged sparrow
#

one sec ill test

#

@dry mirage how do i modify tp_vectorcall with einspect? setting view(obj)._pyobject.tp_vectorcall did not work

dry mirage
#

does that not?

rugged sparrow
#
>>> from fishhook import getmem
>>> funcmem = getmem(type(lambda:0))
>>> from einspect import view
>>> PyFuncType = view(type(lambda:0))._pyobject
>>> from ctypes import cast
>>> s1 = funcmem.tolist()
>>> PyFuncType.tp_vectorcall = cast(0, type(PyFuncType.tp_vectorcall))
>>> s2 = funcmem.tolist()
>>> s1 == s2
True
#

getmem just takes an object and returns a memoryview from id(obj) -> id(obj) + obj.__basicsize__

sick hound
#

thoughts?

night quarryBOT
#

src/einspect/structs/py_type.py line 121

tp_vectorcall: vectorcallfunc```
dry mirage
#

it's just a Structure field so pithink

dry mirage
rugged sparrow
#

lol if that was an issue then fishhook would not work at all

dry mirage
#

!e

from einspect import view

fnt = type(lambda: 0)

print(view(fnt).mem_size)
print(fnt.__basicsize__)
night quarryBOT
#

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

001 | 416
002 | 136
dry mirage
#

PyTypeObject is a PyVarObject so you can't just use basicsize

rugged sparrow
#

*it gets the basic size of the type

night quarryBOT
#

fishhook/fishhook.py lines 15 to 28

def getmem(obj_or_addr, size=None, fmt='P'):
    if size is None:
        if isinstance(obj_or_addr, type):
            # type(cls).__sizeof__(cls) calls a function with a heaptype member
            # if cls is currently unlocked and member happens to overlap with other data
            # crash occurs
            # we avoid this by hardcoding TYPE_BASICSIZE
            size = TYPE_BASICSIZE
        else:
            size = sizeof(obj_or_addr)
        addr = id(obj_or_addr)
    else:
        addr = obj_or_addr
    return memoryview((c_char*size).from_address(addr)).cast('c').cast(fmt)```
dry mirage
#

!e

from einspect.structs import PyTypeObject

print(PyTypeObject.tp_vectorcall.offset)
night quarryBOT
#

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

400
night quarryBOT
#

fishhook/fishhook.py lines 10 to 11

def sizeof(obj):
    return type(obj).__sizeof__(obj)```
rugged sparrow
#

@dry mirage fishhook.getmem gets the object memory properly for types, that is not the issue

dry mirage
#

yeah it doesn't seem to be being set in any case

rugged sparrow
#

if it did not then it would not be able allocate the structs + insert the structs that it needs to in order for it to actually work

dry mirage
#

maybe it's to do with the PYFUNCTYPE I've assigned to it

rugged sparrow
#

maybe

#

I think I remember running into an issue with ctypes where struct fields that hold a C/PyFuncType pointer don't set properly

dry mirage
#

wait what

#

!e

from ctypes import *
from einspect import view

fnt = type(lambda: 0)
obj = view(fnt)._pyobject

print(cast(obj.tp_vectorcall, c_void_p))
night quarryBOT
#

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

c_void_p(None)
dry mirage
#

it's already null? 🥴

rugged sparrow
#

huh

#

maybe it is special cased now inside of the call.c

dry mirage
#

so function objects can still have vectorcall

night quarryBOT
#

Objects/funcobject.c line 817

PyTypeObject PyFunction_Type = {```
dry mirage
#

definition doesn't seem to include tp_vectorcall

#

tp_vectorcall_offset is for the instance (I think?)

rugged sparrow
#

tbh i havent looked at how vectorcall works too much

night quarryBOT
#

Objects/funcobject.c line 832

PyVectorcall_Call,                          /* tp_call */```
dry mirage
#

or I guess tp_call is just always PyVectorcall_Call

rugged sparrow
#
  • would need to remove has_vectorcall from tp_flags
#

then it would break

dry mirage
royal sun
rugged sparrow
finite blaze
#

My solution for another projecteuler problem

"""
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two 3-digit numbers.
"""
r=0;[r:=x*y for x in range(1000)for y in range(x+1,1000)if str(x*y)==str(x*y)[::-1]and x*y>r];print(r)
sly ibex
#
    elif month == 12 and day >=22 or month == 1 and day <= 20:

possible to shorten this?

tough willow
#
 elif any(all(month==12,day>=22),all(month==1,day<=20))
#elif month == 12 and day >=22 or month == 1 and day <= 20:
#

@sly ibex

sudden osprey
rugged sparrow
#

@dry mirage ```py

from fishhook import hook, orig, find_offset, getmem
PyFuncType = getmem(type(lambda:0))
flag_offset = find_offset(PyFuncType, type(lambda:0).flags)
PyFuncType[flag_offset] &= ~(1 << 11) # Py_TPFLAGS_HAVE_VECTORCALL

@hook(type(lambda:0))
... def call(self, *a, **k):
... print(self, a, k)
... return orig(self, *a, **k)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/usr/local/lib/python3.10/site-packages/fishhook/fishhook.py", line 302, in wrapper
File "/usr/local/lib/python3.10/site-packages/fishhook/fishhook.py", line 147, in force_setattr
RecursionError: maximum recursion depth exceeded while calling a Python object``` this is what i figured would happen

dry mirage
#

I wonder which slot it actually sets

#

PyFuncType->tp_call?

rugged sparrow
#

it sets tp_call

dry mirage
#

is there even an original implementation of tp_call?

rugged sparrow
#

yea

#

PyObject_Vectorcall i think is set there

dry mirage
#

I guess there's no way around it then pithink

#

since it needs to call back into itself

#

wonder if you can hook it for a function instance though

rugged sparrow
#

lemme check

dry mirage
#

!e

from einspect import view

fn = lambda: 0
v = view(fn)

def new_call(func, args, n_args, kw_names):
     return "hi"

with v.unsafe():
    v.vectorcall = new_call

print(fn())
night quarryBOT
#

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

0
dry mirage
#

hm

rugged sparrow
#

weird

dry mirage
#

PyFunctionObjects don't seem to actually get their vectorcall called

#

!e

from einspect import view

fn = lambda: 0

obj = view(fn)._pyobject
obj.vectorcall = type(obj.vectorcall)()

print(fn())
night quarryBOT
#

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

0
dry mirage
#

In 3.10 you get a

TypeError: 'function' object does not support vectorcall
night quarryBOT
#

Objects/call.c lines 283 to 288

if (func == NULL) {
    _PyErr_Format(tstate, PyExc_TypeError,
                  "'%.200s' object does not support vectorcall",
                  Py_TYPE(callable)->tp_name);
    return NULL;
}```
rugged sparrow
quartz wave
dry mirage
#

key=reversed

dry mirage
#

hm

#

yeah it's only iterable

low lynx
#

use lambda x: tuple(reversed(x))

night quarryBOT
#

@solar tulip :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 |   1
002 | H 1
003 | b 1
004 | e 1
005 | W 3
006 | d 3
007 | r 3
008 | o 4
009 | l 5
010 | a 7
solar tulip
#

Thanks guys.

wheat river
dry mirage
#

kwargs as well

#

usually those are a dict

wheat river
#

Sweet

pearl socket
#

!e

import re
class _int_t:
    def __init__(self, ln, s):
        self.ln = ln // 8
        self.s = s
    def __gt__(self, other):
        return int.from_bytes(other[0:self.ln], 'little', signed=self.s)
class _reinterpret_cast:
    def __lt__(self, other):
        return True
def create(name):
    unsigned = name[0] == 'u'
    name = name.lstrip('u').replace('_t', '')
    types = ['byte', 'short', 'int', 'long']
    if name.startswith('int'):
        length = re.findall(r'\d+', name)
        if len(length) > 0:
            length = int(length[0])
        else:
            length = 2 ** types.index(name)
    else:
        length = 2 ** types.index(name)
    return _int_t(length, unsigned)
for t in [
    'uint8_t', 'uint16_t', 'uint32_t', 'uint64_t',
    'int8_t', 'int16_t', 'int32_t', 'int64_t',
    'ubyte', 'ushort', 'uint', 'ulong',
    'byte', 'short', 'long'
]:
    globals()[t] = create(t)
reinterpret_cast = _reinterpret_cast()

if __name__ == '__main__':
    print(reinterpret_cast<uint32_t>(b'pytn'))
    print(reinterpret_cast<int32_t>(b'cast'))
    print(reinterpret_cast<uint16_t>(b'to'))
    print(reinterpret_cast<int16_t>(b'in'))
    print(reinterpret_cast<uint8_t>(b't'))
    print(reinterpret_cast<int8_t>(b's'))
night quarryBOT
#

@pearl socket :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 1853127024
002 | 1953718627
003 | 28532
004 | 28265
005 | 116
006 | 115
pearl socket
#

python casting v2

rugged owl
#

Neat use of gt and lt

quartz wave
#

!e ```py
print(sorted([[1, 2], [2], [0, 1]], key=lambda x: (x[:], x.setitem(0, -1))[0] if len(x) == 1 else x))

night quarryBOT
#

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

[[0, 1], [1, 2], [-1]]
quartz wave
#

this is cursed

fathom hemlock
#

guys is this worth of esoteric python?

def phone_number(n):
    return f"({''.join(map(str, n[:3]))}) {''.join(map(str, n[3:6]))}-{''.join(map(str, n[6:]))}"
#

!e

def phone_number(n):
    return f"({''.join(map(str, n[:3]))}) {''.join(map(str, n[3:6]))}-{''.join(map(str, n[6:]))}"
print(phone_number([1,2,3,4,5,6,7,8,9,0]))
night quarryBOT
#

@fathom hemlock :white_check_mark: Your 3.11 eval job has completed with return code 0.

(123) 456-7890
restive void
#

!e

def us_phone_number(n):
    return "({}{}{}) {}{}{}-{}{}{}{}".format(*n)
print(us_phone_number([1,2,3,4,5,6,7,8,9,0]))
night quarryBOT
#

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

(123) 456-7890
earnest wing
#

!e

def us_phone_number(n):
    return "(%d%d%d) %d%d%d-%d%d%d%d"%(*n,)
print(us_phone_number([1,2,3,4,5,6,7,8,9,0]))
night quarryBOT
#

@earnest wing :white_check_mark: Your 3.11 eval job has completed with return code 0.

(123) 456-7890
restive void
#

!e

def us_phone_number(n):
    n = int("".join(map(str, n)))
    return f"({n//10**7}) {n%10**7//10**4}-{n%10**4}"
print(us_phone_number([1,2,3,4,5,6,7,8,9,0]))
night quarryBOT
#

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

(123) 456-7890
quartz wave
night quarryBOT
#

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

(123) 456-7890
quartz wave
fathom hemlock
#

that looks so good

low lynx
#

!e inspired by @maiden blade

from einspect import impl

@impl(int)
def __matmul__(self, other):
    return int(not(self&other))

def full_adder(a, b, c):
    return a@b@(c@(a@b@a@(a@b@b))),a@b@a@(a@b@b)@c@(a@b@a@(a@b@b))@(c@(c@(a@b@a@(a@b@b))))

def add(a, b):
    c, *n = 0,
    while a|b:
        c, i = full_adder(a & 1, b & 1, c)
        n += [i]
        a >>= 1
        b >>= 1
    return [c, *n[::-1]]

print(add(1, 2), f'{3:b}')
print(add(7, 54), f'{61:b}')
print(add(100, 100), f'{200:b}')
night quarryBOT
#

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

001 | [0, 1, 1] 11
002 | [0, 1, 1, 1, 1, 0, 1] 111101
003 | [1, 1, 0, 0, 1, 0, 0, 0] 11001000
maiden blade
#

this is my first time getting pinged in esoteric area

i feel sad and happy at this time rn

low lynx
#

appreciate the juxtaposition between the somewhat pythonic add and the utter monstrosity that is full_adder

low lynx
#

!e version with less brackets

from einspect import impl
from itertools import product

@impl(int)
def __matmul__(self, other):
    return int(not(self&other))

def full_adder(a: int, b: int, c: int):
    return a@b@(a@b@a@(a@b@b)@c),a@b@a@(a@b@b)@c@(a@b@a@(a@b@b))@(a@b@a@(a@b@b)@c@c)

for n in product(range(2), repeat=3):
    print(*n, full_adder(*n))
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)
split salmon
#

!e ```py
@(lambda a:(lambda:(print("How"),a(),print("does this work?"))[0]))
def func():
print("dafuq")

func()```

night quarryBOT
#

@split salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | How
002 | dafuq
003 | does this work?
fleet bridge
arctic skiff
#

15875 chars long

karmic pumice
#

nice

calm loom
#

💀

acoustic quail
#

apparently i did this today but forgorpy a, b, c = int(input()), int(input()), int(input()) print([(q + c + 1 if q < 0 and q + c >= 0 else q + c) for q in [(a - b - 1 if a > 0 and a - b <= 0 else a - b)]][0])

arctic skiff
acoustic quail
#

what the [[Hyperlink Blocked]]

quartz wave
meager zinc
night quarryBOT
#

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

you should implement matmul as a&b^1 for maximum esoteric

finite blaze
#

Anyone up for a golfing challange?

What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?

versed eagle
#

does it loop around the borders or no

versed eagle
#

like, would grid[18][5] -> grid[19][5] -> grid[0][5] -> grid[1][5] be in a vertical line, for example

finite blaze
#

or i can provide one if u want to compare your results

quartz wave
finite blaze
#
g = [[8, 2, 22, 97, 38, 15, 00, 40, 00, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8],
[49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 00],
[81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65],
[52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32, 56, 71, 37, 2, 36, 91],
[22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80],
[24, 47, 32, 60, 99, 3, 45, 2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50],
[32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70],
[67, 26, 20, 68, 2, 62, 12, 20, 95, 63, 94, 39, 63, 8, 40, 91, 66, 49, 94, 21],
[24, 55, 58, 5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72],
[21, 36, 23, 9, 75, 00, 76, 44, 20, 45, 35, 14, 00, 61, 33, 97, 34, 31, 33, 95],
[78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 3, 80, 4, 62, 16, 14, 9, 53, 56, 92],
[16, 39, 5, 42, 96, 35, 31, 47, 55, 58, 88, 24, 00, 17, 54, 24, 36, 29, 85, 57],
[86, 56, 00, 48, 35, 71, 89, 7, 5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58],
[19, 80, 81, 68, 5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 4, 89, 55, 40],
[4, 52, 8, 83, 97, 35, 99, 16, 7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66],
[88, 36, 68, 87, 57, 62, 20, 72, 3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69],
[4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36],
[20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4, 36, 16],
[20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54],
[1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48]]
finite blaze
#

nope

versed eagle
#

alr

meager zinc
#

what would it be then?

#

also are there any negative numbers?

finite blaze
#

only positive numbers

versed eagle
#

are they all integers

finite blaze
#

yes

quartz wave
#

what's the range?

meager zinc
#

ok so we can ignore rows that are less than 4 big entirely

quartz wave
#

random.randint(1, 100)?

finite blaze
quartz wave
#

inclusive?

finite blaze
#

exclusive

quartz wave
#

ok

#

are we gonna go with brute force first

meager zinc
#

ok im dumb

#

or something

finite blaze
#

i can provide a bruteforce base for golfing if u want

quartz wave
#

!e ```py
import random as r
print([[r.randrange(100) for _ in range(20)] for _ in range(20)])

night quarryBOT
#

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

[[83, 32, 84, 36, 65, 99, 80, 26, 87, 22, 50, 20, 7, 23, 80, 82, 92, 42, 29, 45], [16, 73, 61, 60, 32, 22, 96, 9, 16, 52, 28, 46, 6, 51, 87, 52, 4, 36, 29, 77], [29, 79, 45, 61, 18, 95, 82, 93, 52, 83, 23, 4, 35, 21, 85, 66, 17, 76, 58, 71], [16, 86, 77, 50, 7, 52, 73, 30, 56, 77, 13, 65, 75, 84, 27, 96, 64, 66, 31, 52], [10, 9, 87, 95, 48, 87, 43, 95, 88, 20, 70, 95, 15, 79, 38, 32, 41, 65, 26, 31], [0, 47, 83, 18, 14, 24, 97, 83, 13, 13, 10, 69, 56, 39, 46, 54, 26, 6, 45, 49], [4, 64, 61, 25, 18, 64, 5, 95, 15, 32, 31, 55, 34, 8, 93, 17, 90, 64, 19, 26], [16, 15, 84, 13, 71, 80, 82, 20, 62, 36, 97, 24, 5, 37, 5, 91, 84, 79, 30, 0], [13, 67, 57, 11, 9, 94, 53, 63, 72, 14, 30, 45, 43, 9, 86, 33, 76, 2, 36, 87], [4, 4, 9, 85, 70, 44, 46, 67, 89, 68, 32, 60, 64, 89, 48, 72, 45, 14, 99, 72], [96, 60, 10, 38, 0, 76, 47, 56, 40, 77, 34, 96, 17, 66, 6, 97, 37, 86, 49, 24], [85, 28, 72, 92, 17, 70, 86, 35, 21, 57, 46, 92, 8, 83, 8, 96, 61, 32, 0, 89], [42, 21, 41, 13, 17, 16, 27, 69, 91, 7, 7
... (truncated - too long)

Full output: https://paste.pythondiscord.com/oyuxuwesed.txt?noredirect

meager zinc
#

this is probably (maybe) dynamic programming and likely sliding window

#

for optimal

#

but of course we aren't looking for optimal

quartz wave
meager zinc
#

this is also embarrassingly parallel

#

harold are you making a base or do I need to

versed eagle
#

im making something

#

but you should probably make your own since im gonna be a bit

#

im busy and distracted so it'll be a while before i have something working

meager zinc
#

ok so its just the maximum 4x1 column?

versed eagle
#

@finite blaze do you have an input with a known correct output

meager zinc
#

oh no all directions

#

I see

finite blaze
#

yes

versed eagle
#

so that we can test whatever we have

#

once we get something

finite blaze
#

||70600674||

quartz wave
#

base, 302 ```py
import math
p=math.prod;R=range(17)
def f(x):
r=0
for A in x+[*zip(*x)]:r=max(r,*map(p,zip(A,A[1:],A[2:],A[3:])))
for i in R:
a,b,c,d=x[i:i+4]
for j in R:n=r=max(r,a[j]*b[j+1]*c[j+2]*d[j+3])
for i in R:
a,b,c,d=x[i:i+4]
for j in range(19,2,-1):n=r=max(r,a[j]*b[j-1]*c[j-2]*d[j-3])
return r

meager zinc
#

ok i was too slow

quartz wave
#

don't assign math.prod() to a variable, 298 ```py
import math
R=range(17)
def f(x):
r=0
for A in x+[*zip(*x)]:r=max(r,*map(math.prod,zip(A,A[1:],A[2:],A[3:])))
for i in R:
a,b,c,d=x[i:i+4]
for j in R:n=r=max(r,a[j]*b[j+1]*c[j+2]*d[j+3])
for i in R:
a,b,c,d=x[i:i+4]
for j in range(19,2,-1):n=r=max(r,a[j]*b[j-1]*c[j-2]*d[j-3])
return r

#

inline second for, 262 ```py
import math
R=range(17)
def f(x):
r=0
for A in x+[*zip(*x)]:r=max(r,*map(math.prod,zip(A,A[1:],A[2:],A[3:])))
for i in R:
a,b,c,d=x[i:i+4]
for j in R:r=max(r,a[j]*b[j+1]*c[j+2]*d[j+3])
for j in range(19,2,-1):r=max(r,a[j]*b[j-1]*c[j-2]*d[j-3])
return r

meager zinc
#

is a[j]*b[j+1]*c[j+2]*d[j+3] really smaller than math.prod(x[i:i+4])

meager zinc
#

what I thought might be easier is to transpose the list and repeat the same stuff as the row calcluations

quartz wave
#

various optimizations, 224 ```py
import math
p=math.prod;R=range(17)
def f(x):
r=max(sum([[*map(p,zip(A,A[1:],A[2:],A[3:]))]for A in x+[zip(x)]],[]))
for i in R:X=x[i:i+4];r=max(r,
[p(X[j:j+4])for j in R],
[p(X[j-4:j])for j in range(20,3,-1)])
return r

meager zinc
#

because then it would have a lot of duplicates

quartz wave
#

‫nvm wait

meager zinc
#

the multiplication doesn't work my bad

quartz wave
#

revert, 258 ```py
import math
p=math.prod;R=range(17)
def f(x):
r=max(sum([[*map(p,zip(A,A[1:],A[2:],A[3:]))]for A in x+[*zip(x)]],[]))
for i in R:a,b,c,d=x[i:i+4];r=max(r,
[a[j]*b[j+1]*c[j+2]d[j+3]for j in R],[a[j]*b[j-1]*c[j-2]*d[j-3]for j in range(19,2,-1)])
return r

finite blaze
#
import math
r=0
for x in range(0,20):
 for y in range(0,17):
  d=a=0
  v=math.prod(g[x][y:y+3])
  h=g[y][x]*g[y+1][x]*g[y+2][x]*g[y+3][x]
  if x<17:d=g[x][y]*g[x+1][y+1]*g[x+2][y+2]*g[x+3][y+3]
  if x>2:a=g[x][y]*g[x-1][y+1]*g[x-2][y+2]*g[x-3][y+3]
  r=max([v,h,d,a,r])
print(r)

and thats my base with barely any optimisations, 278 chars

meager zinc
#

interesting

#

using r=max([v,h,d,a,r])

quartz wave
#

a little optimization, 256 ```py
import math
p=math.prod;R=range(17);t=0,1,2,3
def f(x):
r=max(sum([[*map(p,zip(A,A[1:],A[2:],A[3:]))]for A in x+[*zip(*x)]],[]))
for i in R:X=x[i:i+4];r=max([r]+[p(X[k][j+k]for k in t)for j in R]+[p(X[k][j-k]for k in t)for j in range(19,2,-1)])
return r

#

wait why do we have a function

meager zinc
#

are we not recursing?

quartz wave
#

no we aren't

meager zinc
#

no wearent

#

ok we can remove it

quartz wave
#

so now we manually take input

#

here's test input reformatted ```
8 2 22 97 38 15 0 40 0 75 4 5 7 78 52 12 50 77 91 8
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 4 56 62 0
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 3 49 13 36 65
52 70 95 23 4 60 11 42 69 24 68 56 1 32 56 71 37 2 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 3 45 2 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 2 62 12 20 95 63 94 39 63 8 40 91 66 49 94 21
24 55 58 5 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 9 75 0 76 44 20 45 35 14 0 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 3 80 4 62 16 14 9 53 56 92
16 39 5 42 96 35 31 47 55 58 88 24 0 17 54 24 36 29 85 57
86 56 0 48 35 71 89 7 5 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 5 94 47 69 28 73 92 13 86 52 17 77 4 89 55 40
4 52 8 83 97 35 99 16 7 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 3 46 33 67 46 55 12 32 63 93 53 69
4 42 16 73 38 25 39 11 24 94 72 18 8 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 4 36 16
20 73 35 29 78 31 90 1 74 31 49 71 48 86 81 16 23 57 5 54
1 70 54 71 83 51 54 69 16 92 33 48 61 43 52 1 89 19 67 48

#

reformat, 285 ```py
import math
p=math.prod;R=range(17);t=0,1,2,3;x=[[*map(int,x.split())]for x in open(0)]
r=max(sum([[*map(p,zip(A,A[1:],A[2:],A[3:]))]for A in x+[*zip(*x)]],[]))
for i in R:X=x[i:i+4];r=max([r]+[p(X[k][j+k]for k in t)for j in R]+[p(X[k][j-k]for k in t)for j in range(19,2,-1)])
print(r)

meager zinc
finite blaze
#

yep, I guess we could ignore the array part

#

and just count the algorithm

quartz wave
meager zinc
#

there's bound to be some way ot compress all these:
g[y][x]*g[y+1][x]*g[y+2][x]*g[y+3][x]
g[x][y]*g[x+1][y+1]*g[x+2][y+2]*g[x+3][y+3]
g[x][y]*g[x-1][y+1]*g[x-2][y+2]*g[x-3][y+3]

#

they are very similar but ever so slightly differnet

quartz wave
#

yep

meager zinc
#

I tried using a loop with (-1,1) for the last two but it didn't work for some reason

quartz wave
meager zinc
#

nicee

meager zinc
#

or, similar but as a list (212):

import math
r=0;g=eval(open(0));t=0,1,2,3;p=math.prod
for x in range(20):
 for y in range(17):r=max(r,p(g[x][y:y+3]),p(g[y+k][x]for k in t),x>16or p(g[x+k][y+k]for k in t),x<3or p(g[x-k][y+k]for k in t))
print(r)
finite blaze
#
import math
r=0;exec(open(0));t=0,1,2,3;p=math.prod
for x,y in zip(range(20),range(17):r=max(r,p(g[x][y:y+3]),p(g[y+k][x]for k in t),x>16or p(g[x+k][y+k]for k in t),x<3or p(g[x-k][y+k]for k in t))
print(r)
#

maybe something like this?

quartz wave
#

zip() isn't equivalent to nesting

finite blaze
#

👍

quartz wave
#

walrus, 225 ```py
import math
r=0;g=[[*map(int,x.split())]for x in open(0)];p=math.prod
for x in range(20):
for y in range(17):r=max(r,p(g[x][y:y+3]),map(p,zip([(g[d:=y+k][x],x<17and g[x+k][d],x>2and g[x-k][d])for k in(0,1,2,3)])))
print(r)

low lynx
quartz wave
#

‫it just describes how to get the carry from the addition at the ith bit

glass stone
#

wow ya'll crazy

#

when you say y:y+3 is that a lambda?

quartz wave
quartz wave
#

lambdas are prefixed with lambda

glass stone
#

neat. I can tell r is important but that is all I can make sense of

#

thought so, i am scacred of lambdas so i don't use them ever but trying to make sense of that nested for loop

#

is that a list comprehension or more slicing

#

it hurts my brain to look at is it safe to run for my ubuntu?

vapid finch
glass stone
#

silence of the lambdas

meager zinc
# glass stone thought so, i am scacred of lambdas so i don't use them ever but trying to make ...

mwhahaha (this only works on windows cpython, btw)

(lambda: (lambda _:(lambda __:(lambda ___:(lambda ____:[(lambda _____:__.fputs(f'Hello {(x:=(lambda:_).__name__):.8}'.encode(),_____)&__.fflush(_____)&__.fclose(_____)&__._exit(o:=0))(__._fdopen(____,'w'))for __._fdopen.restype in(_.POINTER(_.c_char),)][o])(__._open_osfhandle(___,8)))(__._get_osfhandle(-~0)))(_.CDLL(_.util.find_library('msvcrt'))))(__import__('ctypes.util')))()

Output:

Hello <lambda>!
old socket
#

LInux users when msvcrt

meager zinc
#

this only works on windows cpython
me - 3 seconds ago

old socket
#

I know

rain herald
#

💀

glass stone
#

only works on windows im safe using solaris

#

ya'll are amazing thanks for being here ❤️

finite blaze
low lynx
#

221, assigned range to a variable

import math
r=0;g=[[*map(int,x.split())]for x in open(0)];p=math.prod;R=range
for x in R(20):
 for y in R(17):r=max(r,p(g[x][y:y+3]),*map(p,zip(*[(g[d:=y+k][x],x<17and g[x+k][d],x>2and g[x-k][d])for k in R(4)])))
print(r)
night quarryBOT
#

@olive bramble Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!

Our server rules can be found here: https://pythondiscord.com/pages/rules

crisp fog
#

Today I was rummaging through other people's sources and found just such a thing.
The guy invented strptime

fleet bridge
#

my brute-force solution for simple school problem (find 5 numbers that sum up to 2017 and have no common digits): ```py
t = 2017
for n1 in range(1000, t):
s1 = set(t1 := str(n1))
if len(s1) != len(t1): continue
for n2 in range(n1):
s2 = set(t2 := str(n2))
if len(s2) != len(t2): continue
if not s1.isdisjoint(s2): continue
for n3 in range(n2):
s3 = set(t3 := str(n3))
if len(s3) != len(t3): continue
if not s1.isdisjoint(s3): continue
if not s2.isdisjoint(s3): continue
for n4 in range(n3):
s4 = set(t4 := str(n4))
if len(s4) != len(t4): continue
if not s1.isdisjoint(s4): continue
if not s2.isdisjoint(s4): continue
if not s3.isdisjoint(s4): continue
for n5 in range(n4):
s5 = set(t5 := str(n5))
if len(s5) != len(t5): continue
if not s1.isdisjoint(s5): continue
if not s2.isdisjoint(s5): continue
if not s3.isdisjoint(s5): continue
if not s4.isdisjoint(s5): continue
if n1 + n2 + n3 + n4 + n5 == t:
print(n1, n2, n3, n4, n5)

#

all lines here (except first and two last) have some optimisations or are optimisations themselves

finite blaze
# fleet bridge my brute-force solution for simple school problem (find 5 numbers that sum up to...
t=2017;l=len;s=set;R=range;S=str
for n1 in R(1000,t):
 s1=s(t1:=S(n1))
 if l(s1)!=l(t1):continue
 for n2 in R(n1):
  s2=s(t2:=S(n2))
  if l(s2)!=l(t2):continue
  if not s1.isdisjoint(s2):continue
  for n3 in R(n2):
   s3=s(t3:=S(n3))
   if not s1.isdisjoint(s3) or not s2.isdisjoint(s3)or l(s3)!=l(t3):continue
   for n4 in R(n3):
    s4=s(t4:=S(n4))
    if not s1.isdisjoint(s4)or not s2.isdisjoint(s4)or not s3.isdisjoint(s4)or l(s4)!=l(t4):continue
    for n5 in R(n4):
     s5=s(t5:=S(n5))
     if not s1.isdisjoint(s5)or not s2.isdisjoint(s5)or not s3.isdisjoint(s5)or not s4.isdisjoint(s5)or l(s5)!=l(t5):continue
     if n1+n2+n3+n4+n5==t:print(n1,n2,n3,n4,n5) 

^ some really basic optimisations. without changing how the algorithm works
1170 to 668 chars

gleaming linden
#

You could probably demorgan some of those conditions

#

And assign isdisjoint to a variable

finite blaze
#

but it doesn't work

gleaming linden
#

d=set.isdisjoint and d(s1,s2) should work

finite blaze
#

oh you can do things like this

#

good to know

gleaming linden
#

Yes, instance.method(param) is just class_of_instance.method(instance, param)

finite blaze
#

noted

#
t=2017;l=len;s=set;R=range;S=str;d=set.isdisjoint
for n1 in R(1000,t):
 s1=s(t1:=S(n1))
 if l(s1)!=l(t1):continue
 for n2 in R(n1):
  s2=s(t2:=S(n2))
  if l(s2)!=l(t2) or not s1.d(s2):continue
  for n3 in R(n2):
   s3=s(t3:=S(n3))
   if not s1.d(s3) or not s2.d(s3)or l(s3)!=l(t3):continue
   for n4 in R(n3):
    s4=s(t4:=S(n4))
    if not s1.d(s4)or not s2.d(s4)or not s3.d(s4)or l(s4)!=l(t4):continue
    for n5 in R(n4):
     s5=s(t5:=S(n5))
     if not s1.d(s5)or not s2.d(s5)or not s3.d(s5)or not s4.d(s5)or l(s5)!=l(t5):continue
     if n1+n2+n3+n4+n5==t:print(n1,n2,n3,n4,n5) 

down to 584 chars

gleaming linden
#

Demorgan

#

not a or not b is not(a and b)

finite blaze
#

what does "demorgan" mean?

gleaming linden
#

Basically just a and b is the same as not(not a or not b) and a or b is the same as not(not a and not b)

finite blaze
#

will it work for more conditions?

gleaming linden
#

Yeah

finite blaze
#

like not a or not b or not c or not d

#

okay, cool

#

down to 567

#
t=2017;l=len;s=set;R=range;S=str;d=set.isdisjoint
for n1 in R(1000,t):
 s1=s(t1:=S(n1))
 if l(s1)!=l(t1):continue
 for n2 in R(n1):
  s2=s(t2:=S(n2))
  if l(s2)!=l(t2)or not s1.d(s2):continue
  for n3 in R(n2):
   s3=s(t3:=S(n3))
   if not(s1.d(s3)and s2.d(s3))or l(s3)!=l(t3):continue
   for n4 in R(n3):
    s4=s(t4:=S(n4))
    if not(s1.d(s4)and s2.d(s4)and s3.d(s4))or l(s4)!=l(t4):continue
    for n5 in R(n4):
     s5=s(t5:=S(n5))
     if not(s1.d(s5)and s2.d(s5)and s3.d(s5)and s4.d(s5))or l(s5)!=l(t5):continue
     if n1+n2+n3+n4+n5==t:print(n1,n2,n3,n4,n5) 
gleaming linden
#

I feel like this can be a recursive function instead of nested loops

finite blaze
#

yeah, I didn't want to change the initial algorithm that much

#

i am leaving this for someone else ;p

gleaming linden
gleaming linden
# finite blaze i am leaving this for someone else ;p
from itertools import*
for N in range(11):
 for C in combinations(range(10),N):
  for P in product(range(4),repeat=N):
   c=P.count
   if not 5==c(0)>=c(1)>=c(2)>=c(3):continue
   if sum(a:=[d*10**v for v,d in zip(P,C)])==2017:
    R=[0]*5
    for d,v in zip(a,P):
     R[[*map(lambda x:0==x//10**v%10,R)].index(1)]+=d
    print(*R);e
#

basically goes through every possible combination of digits, then goes through every permutation of powers of 10 for each digit (for place values) and checks if the sum is 2017

#

the result includes a 0 though, not sure if that counts

finite blaze
gleaming linden
#

yes, this is just a base golf for now

finite blaze
#

👍

meager zinc
# gleaming linden ```py from itertools import* for N in range(11): for C in combinations(range(10...

you should assign range to a variable:

from itertools import*
r=range
for N in r(11):
 for C in combinations(r(10),N):
  for P in product(r(4),repeat=N):
   c=P.count
   if not 5==c(0)>=c(1)>=c(2)>=c(3):continue
   if sum(a:=[d*10**v for v,d in zip(P,C)])==2017:
    R=[0]*5
    for d,v in zip(a,P):
     R[[*map(lambda x:0==x//10**v%10,R)].index(1)]+=d
    print(*R);e

also, instead of using not + continue can we just use elif?

#

or use and not?

gleaming linden
#

you can combine the ifs

#

if c(3)<=c(2)<=c(1)<=c(0)==5<2017==sum(V:=[j*10**i for i,j in zip(P,C)]):

meager zinc
#
from itertools import*
r=range
for N in r(11):
 for C in combinations(r(10),N):
  for P in product(r(4),repeat=N):
   c=P.count
   if sum(a:=[d*10**v for v,d in zip(P,C)])==2017and not 5==c(0)>=c(1)>=c(2)>=c(3):
    R=[0]*5
    for d,v in zip(a,P):
     R[[*map(lambda x:0==x//10**v%10,R)].index(1)]+=d
    print(*R);e
#

we can also remove a bunch of indentation

#
from itertools import*
r=range
for N in r(11):
 for C in combinations(r(10),N):
  for P in product(r(4),repeat=N):
   c=P.count
   if c[3]<=c[2]<=c[1]<=c[0]==5<2017==sum(V:=[j*10**i for i,j in zip(P,C)]):
    R=[0]*5
    for d,v in zip(a,P):R[[*map(lambda x:0==x//10**v%10,R)].index(1)]+=d
    print(*R);e
#

what does the last ;e do?

gleaming linden
#

it causes an error

#

so the code terminates

meager zinc
#

oh to short circuit?

#

lol I see

gleaming linden
#

stderr doesnt matter so why not

meager zinc
#

can we just do print(*R)e or is that a syntax error

gleaming linden
#

I think you can just rename R to N

#

and it will error on the next iteration because it changes N

meager zinc
#

smart

#
from itertools import*
r=range
for N in r(11):
 for C in combinations(r(10),N):
  for P in product(r(4),repeat=N):
   c=P.count
   if c[3]<=c[2]<=c[1]<=c[0]==5<2017==sum(V:=[j*10**i for i,j in zip(P,C)]):
    N=[0]*5
    for d,v in zip(a,P):N[[*map(lambda x:0==x//10**v%10,N)].index(1)]+=d
    print(*N)
gleaming linden
#

has to be c(x) instead of c[x]

meager zinc
#

no difference in characters, but more esoteric

from itertools import*
r=range
for N in r(11):
 for C in combinations(r(t:=10),N):
  for P in product(r(4),repeat=N):
   c=P.count
   if c(3)<=c(2)<=c(1)<=c(0)==5<2017==sum([j*t**i for i,j in zip(P,C)]):
    N=[0]*5
    for d,v in zip(a,P):N[[*map(lambda x:0==x//t**v%t,N)].index(1)]+=d
    print(*N)
gleaming linden
#

and get rid of the V:= walrus

meager zinc
#

I can't think of anything else

#

we would probably have to change how we are doing it to get much better

gleaming linden
#

I'm rewriting the end conversion bit

#

to use groupby

meager zinc
#

ok

finite blaze
#

@fleet bridge look what they did to your code 😿

meager zinc
#

:)

finite blaze
#

well, i touched it too ;p

meager zinc
#

wait what is variable a?

#

oh I see

#

we removed the walrus

#

at some point

#

fixed```py
from itertools import*
r=range
for N in r(11):
for C in combinations(r(t:=10),N):
for P in product(r(4),repeat=N):
c=P.count
if c(3)<=c(2)<=c(1)<=c(0)==5<2017==sum(a:=[j*ti for i,j in zip(P,C)]):
N=[0]*5
for d,v in zip(a,P):N[[*map(lambda x:0==x//t
v%t,N)].index(1)]+=d
print(*N)

#

note that it outputs:

1942 63 5 7 0
1932 74 5 6 0
Traceback (most recent call last):
    for P in product(r(4),repeat=N):
TypeError: 'list' object cannot be interpreted as an integer
gleaming linden
#

oh, interesting

#

I can't get groupby to work because you need to sort somewhere for groupby to work

#

I'll go sleep now, gn everyone

finite blaze
#

o/

meager zinc
#

gn

finite blaze
#
sum = 0
for y in range(len(g)-1,0,-1): 
    for x in range(0,len(g[y-1])):
        g[y-1][x]+=max(g[y][x], g[y][x+1])

^ trying to oneline this

[g[y-1][x]+=max(g[y][x], g[y][x+1])for x in range(0,len(g[y-1])) for y in range(len(g)-1,0,-1)]
#

but it doesnt work, += invalid syntax

#

any ideas what i might be doing wrong here?

fleet bridge
#

i love you guys

#

you are amazing

wispy ivy
#

Hello, can any of the smart brain here golf the code below ? I really don't mind about readability I want to see how short this code can become

def balance(s):
    stack = []
    for c in s:
        if c in "([":
            stack.append(c)
        elif c in ")]":
            if not stack:
                return 0
            if c == ")" and stack[-1] != "(":
                return 0
            if c == "]" and stack[-1] != "[":
                return 0
            stack.pop()
    return 1 if not stack else 0

s = input()
print(balance(s))

Ty, if you ever take the time to work on it

finite blaze
rugged owl
proper vault
#

I don't think that one works, the program checks if the parentheses are balanced and matching.

wispy ivy
#

Sorry the program is given a string of parentheses of two different types is balanced, meaning that the opening and corresponding closing parentheses are properly nested
And print 1 if it is and 0 if it's not

proper vault
#
i=[];s=input()
for c in s:i+=')]'['(['.index(c)]if c in'(['else(0*i.pop()if i[-1:] ==[c]else c)if c in')]'else[]
print('01'[not i])
```this seems to work
#

you could probably do better using and and or instead of .. if .. else ..

#

but I CBA to figure that out

earnest wing
#
import re
S=re.sub
try:compile(S("\[","[0",S("[^\[\]\(\)]","",input())),"","exec")
except:exit("0")
print(1)
#

if ()[] are matching, then they are valid python syntax as long as [] is replaced with [something]

#

(because you can't index without args)

proper vault
earnest wing
#

that's what the first S() does

proper vault
#

ah, I C now

earnest wing
#

at least in theory

#

haven't tested this

wispy ivy
#

You guys are cracked, super impressive

earnest wing
#

ah i forgot compile requires other args

#

this should work tm

#

it'll throw syntax warnings and clobber the return code fyi

#

so I recommend python3 -Wignore

#

xd

plush halo
#

!e```py
a = []
a.append(a)
print(a)
while True:
a = a[0]

night quarryBOT
#

@plush halo :x: Your 3.11 eval job timed out or ran out of memory.

[[...]]
static marsh
#

This is like the first time I've tried this stuff in python but how is it lol ```py
import sys;

class String():
init: None = lambda self, _str: setattr(self, '_str', _str);
string: list[int] = property(lambda self: [ord(self._str[i]) for i in range(len(self._str))], lambda self, v: setattr(self, '_str', ''.join(chr(i) for i in v)));
getitem: str = lambda self, i: [''.join(map(lambda *args, **kwargs: chr(*args, **kwargs), [self.string[i]]))][0];
iter: list[any] = lambda self: [self.string].iter();
str: str = lambda self: ''.join([''.join(i) for i in [self.getitem(i) for i in range(self.string.len())]]);
add = lambda self, other: ['teehee', self][exec(('String'!=type(other).name)
"raise Exception('type must be String')")==self.setattr('string', ([v for v in self.string]+other.string))];

out: String = String("Hello, ") + String("World!") + String(" Hello2");
sys.stdout.write(f"{out}\n");

#

I got some help from cereal

#

it was fun to make

#

ngl

low lynx
#

I don't think list[any] as a type hint does what you think it does

static marsh
#

😭

low lynx
#

you'd type hint it as a Callable not a list

static marsh
#

yeah I didn't really want to type hint the lambda but the return type of the lambda

quartz wave
# static marsh I know 😩 idk how to specify return type on lambda's

!e ```py
import sys;

class String:
(init := lambda self, _str: setattr(self, '_str', _str)).annotations|={'return':None};
(string := property(lambda self: [ord(self._str[i]) for i in range(len(self._str))], lambda self, v: setattr(self, '_str', ''.join(chr(i) for i in v)))).annotations|={'return':list[int]};
(getitem := lambda self, i: [''.join(map(lambda *args, **kwargs: chr(*args, **kwargs), [self.string[i]]))][0]).annotations|={'return':str};
(iter := lambda self: [self.string].iter()).annotations|={'return':list[any]};
(str := lambda self: ''.join([''.join(i) for i in [self.getitem(i) for i in range(self.string.len())]])).annotations|={'return':str};
add = lambda self, other: ['teehee', self][exec(('String'!=type(other).name)
"raise Exception('type must be String')")==self.setattr('string', ([v for v in self.string]+other.string))];

out: String = String("Hello, ") + String("World!") + String(" Hello2");
sys.stdout.write(f"{out}\n");

night quarryBOT
#

@quartz wave :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 |   File "<string>", line 5, in String
004 | AttributeError: 'property' object has no attribute '__annotations__'
quartz wave
#

aww

static marsh
#

oh ahh

#

I see

#

what does the walrus thingy do

#

I have no clue

low lynx
#

assignment expression

sick hound
# quartz wave !e ```py import sys; class String: (__init__ := lambda self, _str: setattr(...

!e you forgot .getter ```py
import sys;

class String:
(init := lambda self, _str: setattr(self, '_str', _str)).annotations|={'return':None};
(string := property(lambda self: [ord(self._str[i]) for i in range(len(self._str))], lambda self, v: setattr(self, '_str', ''.join(chr(i) for i in v)))).getter().annotations|={'return':list[int]};
(getitem := lambda self, i: [''.join(map(lambda *args, **kwargs: chr(*args, **kwargs), [self.string[i]]))][0]).annotations|={'return':str};
(iter := lambda self: [self.string].iter()).annotations|={'return':list[any]};
(str := lambda self: ''.join([''.join(i) for i in [self.getitem(i) for i in range(self.string.len())]])).annotations|={'return':str};
add = lambda self, other: ['teehee', self][exec(('String'!=type(other).name)
"raise Exception('type must be String')")==self.setattr('string', ([v for v in self.string]+other.string))];

out: String = String("Hello, ") + String("World!") + String(" Hello2");
sys.stdout.write(f"{out}\n");

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 |   File "<string>", line 5, in String
004 | TypeError: property.getter() takes exactly one argument (0 given)
sick hound
#

eh still doesn't work

versed eagle
#

!e

(c:=__import__("ctypes"),gfp:=lambda f:id(f)+16,cvp_fa:=lambda o:c.c_voidp.from_address(o),sw_f:=(lambda f,F,s={}:(s.__setitem__(f, cvp_fa(gfp(f)).value),cvp_fa(gfp(f)).__setattr__("value", s.get(F,0)or cvp_fa(gfp(F)).value),None)[~0]))
sw_f(sum,print)
sw_f(print,repr)
sum(1, print(1), repr(1))
night quarryBOT
#

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

1 <I object at 0x7fc73e770090> 1
versed eagle
#

can someone explain this behaviour?

#

(why does print(1) return something different than repr(1))

sick hound
versed eagle
#

i know what the functions do

#

im asking because i've swapped the function pointer for print

#

to be the function pointer for repr

#

so now they should be the same

#

!e

(c:=__import__("ctypes"),gfp:=lambda f:id(f)+16,cvp_fa:=lambda o:c.c_voidp.from_address(o),sw_f:=(lambda f,F,s={}:(s.__setitem__(f, cvp_fa(gfp(f)).value),cvp_fa(gfp(f)).__setattr__("value",s.get(F,0)or cvp_fa(gfp(F)).value),None)[~0]))
sw_f(sum,print)
sw_f(max,min)
sw_f(min,max)
sum(min(1, 2, 3), max(1, 2, 3))
night quarryBOT
#

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

3 1
versed eagle
#

see here, I've swapped min and max

#

as well as using sum for print

versed eagle
dry mirage
versed eagle
#

i dont swap them
its 1 way

dry mirage
#

so swapping print and repr later should make repr work as sum?

#

oh

dry mirage
night quarryBOT
#

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

1 1 1
dry mirage
#

seems fine here

versed eagle
#

do you switch more than just the pointer?

#

all im doing is switching the pointer for the functions

dry mirage
#

what pointer?

versed eagle
#

the pointer to the c function

dry mirage
#

where?

#

I mean in the struct

versed eagle
#

uh
the offset i used is 16

#

dont remember how i got to that number

dry mirage
#

16 is like... ob_type?

versed eagle
#

8 is type iirc

night quarryBOT
#

src/einspect/structs/py_cfunction.py lines 15 to 21

@struct
class PyCFunctionObject(PyObject[_T, None, None]):
    m_ml: ptr[PyMethodDef]  # Description of the C function to call
    m_self: ptr[PyObject]  # Passed as 'self' arg to the C func, can be NULL
    m_module: ptr[PyObject]  # The __module__ attribute, can be anything
    m_weakreflist: ptr[PyObject]  # List of weak references
    vectorcall: vectorcallfunc```
dry mirage
#

oh it's the m_ml then

#

yeah you have to change vectorcall as well

#

sum and print both take *args

#

but repr only takes 1 arg

#

so you need to change its vectorcall as well

versed eagle
#

ah

dry mirage
#

!e

from einspect import view

view(sum).ml.ml_meth = view(print).ml.ml_meth
view(print).ml.ml_meth = view(repr).ml.ml_meth
view(print)._pyobject.vectorcall = view(repr)._pyobject.vectorcall

sum(1, print(1), repr(1))
night quarryBOT
#

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

1 1 1
versed eagle
#

ty

dry mirage
wispy ivy
proper vault
#

ah, yeah, seems broken

#

mb

rugged owl
dry mirage
rugged owl
#

ah, dumb_ishrion

dry mirage
#

well, also neither have an instance dict, and they're all gc types

#

!e so a normal func to a builtin func would be unsafe

from einspect import view

view(repr) << (lambda x: int(x))
night quarryBOT
#

@dry mirage :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 |   File "/snekbox/user_base/lib/python3.11/site-packages/einspect/views/view_base.py", line 392, in __lshift__
004 |     return self.move_from(other)
005 |            ^^^^^^^^^^^^^^^^^^^^^
006 |   File "/snekbox/user_base/lib/python3.11/site-packages/einspect/views/view_base.py", line 302, in move_from
007 |     check_move(self, other)
008 |   File "/snekbox/user_base/lib/python3.11/site-packages/einspect/views/_moves.py", line 56, in check_move
009 |     raise UnsafeError(
010 | einspect.errors.UnsafeError: memory move of instance dict at offset 88 from 'function' to 'builtin_function_or_method' is out of bounds. Enter an unsafe context to allow this.
proper vault
long fulcrum
#
[print(i)for i in range(51)if~i.bit_count()&1]```
can I golf this further?
earnest wing
#

!e [print(i)for i in range(51)if~i.bit_count()&1]

night quarryBOT
long fulcrum
#

prints numbers that have an even amount of 1s in its binary version

twin reef
long fulcrum
#

thats 25 chars longer though

#

i had to add ,sep="\n"

twin reef
#

I know😢

long fulcrum
#

the print can be changed to *map(print,s),

versed eagle
rugged sparrow
#

@dry mirage want to help me work on making fishhook.asm work on windows later tonight?

#

I also want to add in a patchfinder to let it apply assembly hooks into the middle of functions

glacial lantern
#
import __hello__

No longer prints "Hello world!" in 3.11
You have to do:

import __hello__
__hello__.main()

This ruined my day.

dry mirage
#

!e import __hello__

night quarryBOT
#

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

Hello world!
dry mirage
#

hm

glacial lantern
#

3.11

last locust
night quarryBOT
#

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

Hello world!
last locust
#

Thankfully you can at least still one-line it

glacial lantern
#

That's longer than just

print("Hello world!")

now though.
I wonder why this change happened.

glad belfry
#

I am not sure where to place this issue

#

I only just started working with python about 2 months ago

#

I've created a small save backup tool

#

and I am trying to use pyinstaller to create an exe for it

#

but it keeps missing one particular module over and over

#

so the exe never works

#

and despite some heavy googling the past hour

#

I don't feel I am any closer to grasping what is going on exactly

#

the module in question is checksumdir

#

this is how I am making the exe currently, although I have tried quite a few different variations

#

such as one file

#

I'm not really sure what else info wise to add

#

to help out

#

I just haven't had pyinstaller give me a fuss over packages not being there that are before

meager zinc
glad belfry
#

Thanks 👍

limpid spruce
#

this is a good way to figure out if a number is even or odd

past plank
versed eagle
#

to check if a number is even or odd you only need to check the least significant bit

fleet bridge
#

Too boring

#

!e print(len(str(__import__('math').pi)))

night quarryBOT
#

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

17
limpid spruce
#

!e bin(__import__('math').__getattribute__('pi').__getattribute__('__str__')().__getattribute__('__len__')()).__getattribute__("__len__")()+__import__("math").__getattribute__("e").__getattribute__('__str__')().__getattribute__('__len__')().__getattribute__('__and__')(1)-7

night quarryBOT
#

@limpid spruce :warning: Your 3.11 eval job has completed with return code 0.

[No output]
limpid spruce
#

xd

#

!e print(bin(__import__('math').__getattribute__('pi').__getattribute__('__str__')().__getattribute__('__len__')()).__getattribute__("__len__")()+__import__("math").__getattribute__("e").__getattribute__('__str__')().__getattribute__('__len__')().__getattribute__('__and__')(1)-7)

night quarryBOT
#

@limpid spruce :white_check_mark: Your 3.11 eval job has completed with return code 0.

1
past plank
#

just using __getattribute__ instead of directly dot-accessing a member isn't really esoteric

#

just longer

#

same for .__str__() and .__len__() instead of just str() and len()

versed eagle
#

if we're not using num%2 or num&1, i like not not int(bin(num)[~0])

#

in most cases it won't actually matter whether you have an int or a bool, so you can most likely drop the not not if you want to

past plank
#

n//2==n/2

fleet bridge
#

I believe struct.Struct.pack() requires bools for bool fields

past plank
fleet bridge
versed eagle
#

because there are certainly cases where a bool specifically is needed

past plank
versed eagle
#

but most times an int will work just fine

past plank
fleet bridge
#

!e

def is_even(n): return n/2==n//2

assert is_even(0)
assert not is_even(1)
assert is_even(2)
assert not is_even(3**1000)
assert is_even(3**1000+1)
night quarryBOT
#

@fleet bridge :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 6, in <module>
003 |   File "<string>", line 1, in is_even
004 | OverflowError: integer division result too large for a float
fleet bridge
#

Oh

#

3**1000 is overkill

past plank
#

yeah

#

!e ```py
def is_even(n): return n/2==n//2

max = 18014398509481984

print(is_even(max))
print(is_even(max-1))
print(is_even(max-2))
print(is_even(max-3))

print(is_even(max+1)) # no work
print(is_even(max+2)) # no work
print(is_even(max+3)) # no work```

night quarryBOT
#

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

001 | True
002 | False
003 | True
004 | True
005 | True
006 | False
007 | False
past plank
#

hm why -3 doesn't work

fleet bridge
#

weird

past plank
#

ah I messed up my calculations on the max

fleet bridge
#

Maybe your max is not the actual limit

past plank
#

!e ```py
def is_even(n): return n/2==n//2

max = 18014398509481984 // 2

print(is_even(max))
print(is_even(max-1))
print(is_even(max-2))
print(is_even(max-3))

print(is_even(max+1)) # no work
print(is_even(max+2)) # no work
print(is_even(max+3)) # no work```

night quarryBOT
#

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

001 | True
002 | False
003 | True
004 | False
005 | True
006 | True
007 | False
past plank
#

there

#

I doubled it accidentally

#

regardless 9 quadrillion is pretty large

#

will work in most applications lol

fleet bridge
#

It is in range of int64

past plank
#

this gets you the same rangepy is_even = range(-9007199254740992, 9007199254740992, 2).__contains__

past plank
#

it's 53 bits of double precision

fleet bridge
#

53<64, isn't it?

past plank
#

because x / 2 needs to be able to represent that number at a 0.5 resolution

#

and python uses IEEE754 doubles

#

you get 0.5 resolution at 54 bits, but x/2 so x needs to be <=53 bits

fleet bridge
#

I mean it is technically possible to have large int64, use this algorithm and have problems with it

past plank
#

yeah

#

any number larger than 2**53 but less than 2**64 is going to have issues

#

and so will numbers larger than 2^64 obviously

fleet bridge
past plank
#

yeah

#

and approximately 100% of all numbers

#

but regardless, the majority of computations occur with numbers less than 9 quadrillion

#

you can always just do py is_even = range(-ARBITRARILY_LARGE_INTEGER*2, ARBITRARILY_LARGE_INTEGER*2, 2).__contains__

fleet bridge
#

is_even=range(-int(float('inf'))*2,int(float('inf'))*2).__contains__

past plank
#

int(float('inf')) lol

sick hound
#
@lambda a:(u:=(i:=a.__code__).co_code,setattr(a,"__code__",i.replace(co_code=b"".join({u[e+e]}<{*b"et"}!=u[e-~e]==i.co_names.index(a.__name__)and b"q\0"or u[e+e:2+e+e]for e in range(len(u)//2)))),a)[2]
#

handy decorator for "tail" call "optimisation"

sly ibex
#

question
i have this
coffe1 = 20
coffe2 = 50
coffe3 = 20
there's any way to say
while coffe1 != 0 or coffe2 != 0 or coffe3 !=0? this part

last locust
versed eagle
#

wait actually

#

while coffe1|coffe2|coffe3:

#

is even shorter

finite blaze
versed eagle
#

it's bitwise or

#

each output bit will be set to 1 if either of the input bits are 1

#

if both of the input bits are 0, then the output bit is 0

#

if all of the bits in each of the inputs are 0, then the bitwise or will return 0

#

0 == False

#

if all the numbers are 0, then it will be False, and the while loop will end

finite blaze
#

Thanks 👍

pure dew
#

@fleet bridge @past plank
is_even = lambda x: x % 2 == 0

quartz wave
#

f=lambda x:x%2<1 done

versed eagle
#

what about is_even = lambda x: x & 1 ^ 1

sick hound
versed eagle
#

please dont ping me for no reason

sick hound
versed eagle
#

i literally just asked you to not ping me for no reason.

#

please stop.

low lynx
meager zinc
#
def is_even(number):
  if number == 0:
    return "idk"
  if number == 1:
    return False
  if number == 2:
    return True
  if number == 3:
    return False
  if number == 4:
    return True
  raise OverflowError
tough willow
#

!e ```py
def is_even(number):
if number == 0:
return "idk"
if number == 1:
return False
if number == 2:
return True
if number == 3:
return False
if number == 4:
return True
return is_even(number-4)

print(is_even(123))

night quarryBOT
#

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

False
low lynx
#

why are you returning idk for 0

low lynx
#

0 is definitely even

tough willow
#

Yes

violet pollen
#

You guys really got me curious about esoteric programming in Python--are there any good resources I can use to learn about it?

low lynx
#

i kinda just started golfing stuff and then learning stuff by looking at other people's golfs

#

if you have an interesting problem to golf send it here and you can see how other people golf

#

there's a bunch of golfs online as well

versed eagle
low lynx
#

code golfing aoc was like golf boot camp so if you do that next year can recommend

versed eagle
#

mainly it's just exploring the boundaries of the language on your own and seeing what other people do with it

violet pollen
#

ahh, i see

#

thank you :)

past plank
versed eagle
#

and dapper is fairly active in this channel
it's safe to say that they know what esoteric means
as such, questioning them in a relatively antagonistic way like that is rude
please dont do that <3

arctic skiff
arctic skiff
lean warren
#

can anyone know, why there is a need of lambda function in python

sick hound
#

key=lambda x: x["timestamp”] for example

lean warren
#

oh, interesting!!

sick hound
#

theres many other uses but thats one im certain on

lean warren
#

got it, thanks for letting me know...

sick hound
lean warren
sick hound
#

im sure someone here can educate you more on lambda, im not an expert or anything

restive void
#

There's no strict need for lambdas, you could always just use a named function. It just makes some simple throwaway functions (e.g. for use as key functions as shown above) easier to write.

versed eagle
#

now im having to ask a third time.

#

:/

versed eagle
#

You've done it again.

#

Please stop.

#

Please.

arctic skiff
calm loom
#

hm

pure dew
tough willow
#

Hi @versed eagle

arctic skiff
#

You should definitely turn off pings

versed eagle
# tough willow Hi <@696824456697479240>

I have asked 4 times to not be pinged. Every single time, my request has been subsequently ignored. can you please just stop. this harassment doesn't gain you anything. there's no point. please stop

arctic skiff
versed eagle
versed eagle
#

:/

versed eagle
#

no, you haven't. you're continuing to ping me.

tough willow
#

Im not

rugged owl
tough willow
#

okay sorry @versed eagle i didnt know that

#

i will stop

arctic skiff
versed eagle
# arctic skiff <@683001325440860340> is here

i know. im trying to refrain from involving others, because that shouldn't be necessary
people should be mature enough to realise that what they're doing is a problem, and stop on their own

tough willow
#

okay

versed eagle
arctic skiff
arctic skiff
rugged owl
violet pollen
#

🧍

tough willow
#

hi

finite blaze
#

Hey, I have a big txt file with names like this: "TOM","TIMMY","MAX".....
what would be the shortest way to store these names in a list?

versed eagle
#

the names are separated by commas, and are all inside strings?

finite blaze
versed eagle
#

eval(f"[{open("yourfile").read()}]")

finite blaze
#

hmm interesting

#

ah i understand

#

smart smart, thanks

#

but it doesn't work ;p

versed eagle
#

ah

#

switch the quotes

#

i accidentally used the wrong type

#

of quotes

finite blaze
#

yea 👍

versed eagle
#

eval(f"[{open('yourfile').read()}]")

arctic skiff
versed eagle
#

the file gets closed in its destructor

#

which gets called bc its ob_refcnt will be 0

finite blaze
#

hmm i have this little challange

#
text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.

For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.

What is the total of all the name scores in the file?
#
names = sorted(eval(f"[{open('022.txt').read()}]"))
print(sum([sum(ord(letter) - 64 for letter in name) * names.index(name) for name in names]))
#

thats what i am doing right now

#

870873746 is my result but page won't accept it

#

any ideas what i might be missing?

serene stratus
rugged owl
#

they are*

serene stratus
#

not so sure since his solution doesn't look esoteric and he is asking what's wrong with his code

violet pollen
#

i think they are trying to make a one liner? idk

low lynx
#

I don't see why you don't just enumerate instead of indexing

pure dew
#

alphabetical value, not character value

versed eagle
frail forum
#

python indexes start at 0 instead of 1

#

it was multiplying the score of the first name by 0 causing the score itself to be 0 which was probably your problem

#

upon 2 more minutes of research i have gotten the names file

#

the correct score should be 871198282 👍🏾

quartz wave
frail forum
versed eagle
quartz wave
versed eagle
#

cereal

quartz wave
#

ok

frail forum
quartz wave
#

about to golf this

versed eagle
#

so far what we have is

N=sorted(eval(f"[{open('f').read()}]"))
print(sum(sum(ord(l)-64for l in n)*-~N.index(n)for n in N))
frail forum
#

let him cook...

versed eagle
#

yeah i edited it
since i accidentally pasted an older version that didn't account for the off by 1 error

frail forum
#

ah

quartz wave
#

so open(0)

#

90 ```py
N=sorted(eval(open(0).read()))
print(sum(sum(ord(l)-64for l in n)*-~N.index(n)for n in N))

versed eagle
#

that would require changing the input

quartz wave
#

why?

frail forum
#

because

versed eagle
#

wait no nvm

frail forum
#

are u sure?

quartz wave
#

ok we're good then

versed eagle
#

yeah

quartz wave
#

wait a min

frail forum
#

because it has to turn

#

comma separated into a table

#

eval(f"[{open('f').read()}]")

versed eagle
#

it will default to a tuple

frail forum
#

kk

versed eagle
#

if there aren't enclosing braces/brackets

quartz wave
#

89 assuming all unique ```py
N=sorted(eval(open(t:=0).read()))
print(sum(sum(ord(l)-64for l in n)*(t:=t+1)for n in N))

versed eagle
#

ooh thats a good one

frail forum
#

will in that case

#
print(sum(sum(ord(l)-64for l in n)*(t:=t+1)for n in sorted(eval(open(t:=0).read()))))```
#

85

quartz wave
frail forum
#

sec

frail forum
quartz wave
#

although 86 ```py
t=0;print(sum(len(n)(t:=t+1)+tsum(map(ord,n))for n in sorted(eval(open(0).read()))))

#

nvm

#

wait

frail forum
#

l is not defined

quartz wave
#

ye it doesn't work

frail forum
#

6010368747 is the value i got out of that

quartz wave
#

86 again ```py
t=0;print(sum(sum(ord(l)-64for l in n)*(t:=t+1)for n in sorted(eval(open(0).read()))))

frail forum
#

trying to think of ways to golf

versed eagle
#

found a shortening, i think

#

instead of eval(open(0).read()), eval(*open(0))
if we assume the input contains no newlines

#

which i think is a fair assumption

frail forum
#

there are no newlines

#

you are correct

#

this is a problem from project euler#022

night quarryBOT
#

Hey @frail forum!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

frail forum
#

this is the names file

quartz wave
#

that reduces it to a good 80 ```py
t=0;print(sum(sum(ord(l)-64for l in n)*(t:=t+1)for n in sorted(eval(*open(0)))))

#

but can eval() handle a 46447 length file

frail forum
#

yea

quartz wave
#

it can't for me

frail forum
#

hmmm

quartz wave
#

nvm it can

#

the warnings were causing the problem

night quarryBOT
rough moat
#

lol

#

its a megabyte

night quarryBOT
#

Hey @rough moat!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

rough moat
#

bro

#

i dont think it even lets me paste lmao

#

i'll just put it on github

#

yeah hastebin doesn't even work

last locust
#

!paste has instructions on how to use it

night quarryBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

rough moat
#

it didnt work for me

#

idk

finite blaze
night quarryBOT
#

:incoming_envelope: :ok_hand: applied mute to @nimble crescent until <t:1675958919:f> (10 minutes) (reason: newlines rule: sent 106 newlines in 10s).

The <@&831776746206265384> have been alerted for review.

river idol
#

!unmute @nimble crescent

night quarryBOT
#

:incoming_envelope: :ok_hand: pardoned infraction mute for @nimble crescent.

river idol
nimble crescent
#

ok, thanks

versed eagle
#

i think this is the wrong channel for what you want

nimble crescent
#

Im sorry, what would be a better channel?

versed eagle
#

my guess would be #networks
or you could do one of those new thread things they have

rugged sparrow
#

I have a challenge for yall. try to find the most creative way of getting python to raise a SystemError (raise/throw directly are not allowed lol)

fleet bridge
#

!e open(4)

night quarryBOT
#

@fleet bridge :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 | OSError: [Errno 9] Bad file descriptor
fleet bridge
#

When SystemErrors can occur?

rugged sparrow
#

!e ```py
exec('''
corrupt = iter(int, 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 should create a system error

#

weird that it isn't