#esoteric-python
1 messages · Page 19 of 1
.
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
What is going on rn
i disagreed, aside from the restrictions imposed by the goal
which i thought was implicit
sorry if i didnt make that clear.
now you are just backtracking
no, i am not
im saying the same thing that i have been saying
plenty of the code i sent after that message contained dunders and underscores and you never clarified
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
#esoteric-python message this entire bug revolves around __new__ which contains underscores
so then the bug is irrelevant
because to use it, you first have to get something that would already be disallowed
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
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
dunders are a core language feature, without them, I would not consider it python
have fun without any of the stdlib btw
then we agree, you would have to limit it to such a small subset that you could not call it python
we do not agree, actually
then what point are you trying to make
you would have to limit it to such a small subset that you could not call it python
i never said that?
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

@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
that is not at all what you were arguing lol
that is exactly what i have been arguing
this entire time
I'm super confused right now but none the less, I am enjoying the show
right here you disagreed when i said limited subset
this is a limited subset
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
what are you arguing then?
.
the OR prevent such access during runtime is where it gets fuzzy
also, please dont call me "dude"
not mad, ik you didn't mean anything by it
but i use she/her
sorry, my bad
I have been reliably informed by my nieces that "dude" is non-gendered
im still gonna respect @versed eagle 's wishes
this thread's name scares me
!e py print('{0.\u005F\u005Fclass\u005F\u005F.\u005F\u005Fbase\u005F\u005F.\u005F\u005Fsubclasses\u005F\u005F}'.format(1)) @versed eagle you can at least read __ values by abusing .format
@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>
*but you only get the resulting value as a string
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
afaik, @burnt pasture 's challenge was to bypass a theoretical system that evals input in a call that looks like this ```py
def safe(inp):
if '_' in inp:raise Exception('invalid')
exec(inp, {'builtins':{}})
I don't think you'd be hooking format or __format__ cause that just get's the string representation of whatever object
I think so at least, I only remember __format__ takes in a specification that you can use to determine what to do

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
poetry is probably reading the .pth's and failing in there
Should I make an issue on the GitHub? I feel like it might not be to relevant though since not a lot of people will be doing stuff like that
depends on how its failing (like if you were building something with a "normal" .pth will if fail there)
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
ah, so poetry install loads site which loads .pth files, and yours fails because the package it references isnt installed yet
i wouldn't bother reporting it as a bug then
Yeop sounds about right, it's just tedious to fix
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
actually, i would report that. Poetry probably shouldn't completely fail like that
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
Here's what it looks like
And yea, after this happens poetry reports that there is no cache directory
Or it errors when trying to get a cache directory? *
thats a weird failure
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
!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("++++++++++[>+++++++>++++++++--->+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."))
@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
what am i doing wrong here 
access after pop
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
How do I make statements inside linear lambda?
For example,
x = 1
print("hi")
x += 1
print(x)
Or sth like this
Lambdas can't have statements in them
But they can have a function call which runs statements
!e
f=lambda:(x:=1)and(print('hi'))or(x:=x+1)and(print(x))
f()
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | hi
002 | 2
f=lambda:(x:=1,print('hi'),x:=x+1,print(x)) condensed
!e```py
(lambda:(x:=1,print('hi'),x:=x+1,print(x)))()
@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | hi
002 | 2
why x:=1 works in lambdas but x=1 doesn't?
expression vs statement
!e
(lambda x=1:(print('hi'),x:=x+1,print(x)))()
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | hi
002 | 2
in a nutshell, you can think of it this way
- expressions can be put inside parentheses ()
- statements cannot, because that causes a syntax error
Alright, thanks
nope, it saves a char @arctic skiff
yeah i see thats why i del
>>> len("""(lambda:(x:=1,print('hi'),x:=x+1,print(x)))()""")
45
>>> len("""(lambda x=1:(print('hi'),x:=x+1,print(x)))()""")
44
!e```py
(x:=1,print('hi'),x:=x+1,print(x))
@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | hi
002 | 2
!epy print(len("""(x:=1,print('hi'),x:=x+1,print(x))"""))
@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.
34
How do I make statements inside linear lambda?
you can't
the point is to do it inside a lambda
yes ik that. you have to use expressions.
but the point is still the same
oh didn't see >
it's meant to be inside a lambda
how could i do this in a for loop in one line?
!e```py
(lambda x:(print('hi'),x:=x+1,print(x)))(1)
@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | hi
002 | 2
!epy print(len("""(lambda x:(print('hi'),x:=x+1,print(x)))(1)"""))
@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.
43
but still x=1 is a arg so its still a part of statement
!e
(lambda x:(print('hi'),print(x:=x+1)))(1)
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | hi
002 | 2
41
!epy (lambda x:(print('hi'),print(x+1)))(1)
oh wait
@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | hi
002 | 2
!e
(lambda x:print(f'hi\n{x+1}'))(1)
@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
since you are using x+1
i used it because you used it here
was gonna keep using walrus until then lol
then i realized we were using lambda and expressions
!epy print('hi\n2')is shortest
@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | hi
002 | 2
not a lambda though
lambda went with lama
what?
!e
(lambda :print("hi\n2"))()
@calm loom :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | hi
002 | 2
🦙
!e
(lambda:print("hi\n2"))()
@rugged owl :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | hi
002 | 2
1 less char 
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
What's the system("") for?
Force color in windows command prompt
!e
from einspect import view
view(1).swap(0)
print(0 > 1)
print(bool(0), bool(1))
print(0 * 0 == 1.0)
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | True
002 | True False
003 | True
🥴 slightly cursed
do the 0 > 1 and 0 * 0 == 1.0 not get const folded?
0 > 1 is not folded
0 * 0 is folded to 0 == 1.0
and since 0 is now 1, it's true
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)
anyone got any ideas to golf this further?
comparisons do not get constant folded
if True and if __debug__ do get const folded unfortunately
!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]))))))
@split salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello world!
"No module found named 'einspect'"?
hm?
Python 3.9.7
!pypi einspect is not a builtin 👀
src/einspect/views/view_cfunction.py line 61
def vectorcall(self) -> vectorcallfunc:```
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
what the fuck
what in the actual fuck
why
because i don't want to make 143 buttons arranged in 10 rows
manually
that do almost the same thing
also this is #esoteric-python isnt it
why not use enumerate?
what
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
for i, v in enumerate(l.split()):
...
and replace all your l.split()[i] with just v
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
condensed version/base for golfing (271) ```py
p=0;i=min(rows,n:=len(L:=l.split()))
while z:=i-p:j=p//rows;p=i;a=f'f2r{j}';g=rows*j;exec(a+'=Frame(f2);'+f'(f2r{j}c%d:=Button({a},font=f,text=L[g+%d],command=lambda:e1.insert(END,L[{g}+%d][1]))).pack(side=LEFT);'z%sum(zip([range(z)]*3),())+a+'.pack()');i=min(n,i+rows)
does exactly the same thing
for i in range(1000):
if i%3==0 or i%5==0: s+=i
how can I oneline something like this?
sum(a for b in c if d)
I just found a pretty interesting page
with a lot of problems to golf
A website dedicated to the fascinating world of mathematics and programming
Or if you want the same approach then for i in range(1000): s+= i * (i % 3 == 0 or i % 5 == 0)
or sum(a*(condition)for a in b)
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
it's only used when internal python C calls target the function iirc
but faster call without making tuples and dicts
tp_vectorcall is preferred any time that a call occurs
!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)
@rugged sparrow :warning: Your 3.11 eval job has completed with return code 0.
[No output]
(for better or for worse)

if you null out PyFuncType->tp_vectorcall to switch to using tp_call then you crash due to recursion
python defined funcs also have a separate tp_call and tp_vectorcall?
also why does that crash from recursion 
it does if you null tp_vectorcall then hook it
because that overwrites with the default tp_call which looks up the py_object in the class mapping and then uses PyObject_Call
isn't tp_vectorcall optional?
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
would it work if you cast __call__ to a PYFUNCTYPE first
or does that still recurse
i believe it still recurses as ctypes uses PyObject_Call or some derivative internally
does PyFunctionType even have tpcall?
oh the type
the object instance at least only has vectorcall? 
one sec ill test
@dry mirage how do i modify tp_vectorcall with einspect? setting view(obj)._pyobject.tp_vectorcall did not work
does that not?
>>> 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__
strange
src/einspect/structs/py_type.py line 121
tp_vectorcall: vectorcallfunc```
it's just a Structure field so 
ah I think that might be the issue
lol if that was an issue then fishhook would not work at all
!e
from einspect import view
fnt = type(lambda: 0)
print(view(fnt).mem_size)
print(fnt.__basicsize__)
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 416
002 | 136
PyTypeObject is a PyVarObject so you can't just use basicsize
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)```
!e
from einspect.structs import PyTypeObject
print(PyTypeObject.tp_vectorcall.offset)
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
400
fishhook/fishhook.py lines 10 to 11
def sizeof(obj):
return type(obj).__sizeof__(obj)```
@dry mirage fishhook.getmem gets the object memory properly for types, that is not the issue
yeah it doesn't seem to be being set in any case
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
maybe it's to do with the PYFUNCTYPE I've assigned to it
maybe
I think I remember running into an issue with ctypes where struct fields that hold a C/PyFuncType pointer don't set properly
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))
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
c_void_p(None)
it's already null? 🥴
isn't tp_vectorcall on the function type for the actual function type and not instances?
so function objects can still have vectorcall
Objects/funcobject.c line 817
PyTypeObject PyFunction_Type = {```
definition doesn't seem to include tp_vectorcall
tp_vectorcall_offset is for the instance (I think?)
maybe
tbh i havent looked at how vectorcall works too much
Objects/funcobject.c line 832
PyVectorcall_Call, /* tp_call */```
or I guess tp_call is just always PyVectorcall_Call
then function calls would actually reach FunctionType->tp_call yeah
cool use of codec
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)
elif month == 12 and day >=22 or month == 1 and day <= 20:
possible to shorten this?
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
Assuming month is between 1 and 12 I think this would work: not(1,20)<(month,day)<(12,22)
@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
does that just set __call__?
I wonder which slot it actually sets
PyFuncType->tp_call?
it sets tp_call
is there even an original implementation of tp_call?
I guess there's no way around it then 
since it needs to call back into itself
wonder if you can hook it for a function instance though
probably
lemme check
!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())
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
0
hm
weird
seems it's a 3.11 optimization or something?
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())
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
0
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;
}```
interesting. seems like i will have to find some other way to hook calls globally
i am still not done with my codec project 🥲
key=reversed
use lambda x: tuple(reversed(x))
@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
Thanks guys.
So basically instead of passing args as py tuple it passes it as an array?
essentially yeah
kwargs as well
usually those are a dict
Sweet
!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'))
@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
python casting v2
Neat use of gt and lt
!e ```py
print(sorted([[1, 2], [2], [0, 1]], key=lambda x: (x[:], x.setitem(0, -1))[0] if len(x) == 1 else x))
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
[[0, 1], [1, 2], [-1]]
this is cursed
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]))
@fathom hemlock :white_check_mark: Your 3.11 eval job has completed with return code 0.
(123) 456-7890
!e
def us_phone_number(n):
return "({}{}{}) {}{}{}-{}{}{}{}".format(*n)
print(us_phone_number([1,2,3,4,5,6,7,8,9,0]))
@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.
(123) 456-7890
!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]))
@earnest wing :white_check_mark: Your 3.11 eval job has completed with return code 0.
(123) 456-7890
!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]))
@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.
(123) 456-7890
!e ```py
a='{}{}{}'.format
f=lambda n:'(%s) %%s-'%a(next(d:=zip([n:=iter(n)]*3)))%a(*next(d))+''.join(map(str,n))
print(f([*range(1,10)]+[0]))
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
(123) 456-7890
@fathom hemlock it's just the basics
here's a better one
that looks so good
!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}')
@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
this is my first time getting pinged in esoteric area
i feel sad and happy at this time rn
appreciate the juxtaposition between the somewhat pythonic add and the utter monstrosity that is full_adder
!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))
@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)
!e ```py
@(lambda a:(lambda:(print("How"),a(),print("does this work?"))[0]))
def func():
print("dafuq")
func()```
@split salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | How
002 | dafuq
003 | does this work?
isnt it an adder implemented using sheffer stroke?
Lmfao
nice
💀
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])
what the [[Hyperlink Blocked]]
nand my beloved
that red book about CPU internals will surely be an interesting read rn 😔
!e ```py
from einspect import impl
from itertools import*
@impl(int)
def matmul(a,b):return a&b^1
for n in product([0,1],repeat=3):print(*n,(lambda a,b,c:(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)))(*n))
@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)
you should implement matmul as a&b^1 for maximum esoteric
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?
does it loop around the borders or no
what 20x20 grid?
like, would grid[18][5] -> grid[19][5] -> grid[0][5] -> grid[1][5] be in a vertical line, for example
random one
or i can provide one if u want to compare your results
yeah let's go with that
also ^
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
alr
only positive numbers
are they all integers
yes
what's the range?
ok so we can ignore rows that are less than 4 big entirely
random.randint(1, 100)?
0-100
exclusive
i can provide a bruteforce base for golfing if u want
!e ```py
import random as r
print([[r.randrange(100) for _ in range(20)] for _ in range(20)])
@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
yes
this is probably (maybe) dynamic programming and likely sliding window
for optimal
but of course we aren't looking for optimal
sliding window is a good idea
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
ok so its just the maximum 4x1 column?
@finite blaze do you have an input with a known correct output
yes
^ input, answer:
||70600674||
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
ok i was too slow
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
is a[j]*b[j+1]*c[j+2]*d[j+3] really smaller than math.prod(x[i:i+4])
hmm good one
what I thought might be easier is to transpose the list and repeat the same stuff as the row calcluations
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
because then it would have a lot of duplicates
nvm wait
the multiplication doesn't work my bad
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
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
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
are we not recursing?
no we aren't
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)
this assumes input as variable g
optimized, 277 ```py
import math
r=0;g=[[*map(int,x.split())]for x in open(0)]
for x in range(20):
for y in range(17):r=max(r,math.prod(g[x][y:y+3]),g[y][x]*g[y+1][x]*g[y+2][x]*g[y+3][x],x>16or g[x][y]*g[x+1][y+1]*g[x+2][y+2]*g[x+3][y+3],x<3or g[x][y]*g[x-1][y+1]*g[x-2][y+2]*g[x-3][y+3])
print(r)
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
yep
I tried using a loop with (-1,1) for the last two but it didn't work for some reason
compressed these, 238 ```py
import math
r=0;g=[[*map(int,x.split())]for x in 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)
nicee
assuming input like this, 210:
import math
r=0;exec(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)
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)
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?
nope
zip() isn't equivalent to nesting
👍
merge all the for k in ts, 226 ```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[y+k][x],x<17and g[x+k][y+k],x>2and g[x-k][y+k])for k in(0,1,2,3)])))
print(r)
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)
I think sheffer strokes are nand gates
oh i found it
it just describes how to get the carry from the addition at the ith bit
sum is (not a)&(not b)&c | (not a)&b&(not c) | a&(not b)&(not c) | a&b&c and carry is b&c | x&c | x&y
no it's a slice
lambdas are prefixed with lambda
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?
Don't be scared. lambda is nearly the same as def.
silence of the lambdas
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>!
LInux users when msvcrt
this only works on windows cpython
me - 3 seconds ago
I know
💀
only works on windows im safe using solaris
ya'll are amazing thanks for being here ❤️
Alright, i guess thats the final version
no
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)
@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
Today I was rummaging through other people's sources and found just such a thing.
The guy invented strptime
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
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
You could probably demorgan some of those conditions
And assign isdisjoint to a variable
I tried doing that
but it doesn't work
d=set.isdisjoint and d(s1,s2) should work
Yes, instance.method(param) is just class_of_instance.method(instance, param)
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
what does "demorgan" mean?
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)
will it work for more conditions?
Yeah
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)
I feel like this can be a recursive function instead of nested loops
yeah, I didn't want to change the initial algorithm that much
i am leaving this for someone else ;p
all the x.d(y) should be d(x,y) btw
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
Won't declaring range as a variable save some chars?
yes, this is just a base golf for now
👍
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?
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)]):
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?
stderr doesnt matter so why not
can we just do print(*R)e or is that a syntax error
I think you can just rename R to N
and it will error on the next iteration because it changes N
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)
has to be c(x) instead of c[x]
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)
and get rid of the V:= walrus
I can't think of anything else
we would probably have to change how we are doing it to get much better
ok
@fleet bridge look what they did to your code 😿
:)
well, i touched it too ;p
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//tv%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
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
o/
gn
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?
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
what is this supposed to do?
I mean this is the most I can do without knowing what the program does
def b(s):
return 1-(len([c for c in s if c in "(["]) != len([c for c in s if c in ")]"]))
I don't think that one works, the program checks if the parentheses are balanced and matching.
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
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
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)
non-parentheses are also allowed in the input
that's what the first S() does
ah, I C now
You guys are cracked, super impressive
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
!e```py
a = []
a.append(a)
print(a)
while True:
a = a[0]
@plush halo :x: Your 3.11 eval job timed out or ran out of memory.
[[...]]
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
I don't think list[any] as a type hint does what you think it does
I know 😩 idk how to specify return type on lambda's
😭
you'd type hint it as a Callable not a list
yeah I didn't really want to type hint the lambda but the return type of the lambda
!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");
@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__'
aww
assignment expression
!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");
@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)
eh still doesn't work
!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))
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
1 <I object at 0x7fc73e770090> 1
can someone explain this behaviour?
(why does print(1) return something different than repr(1))
print() produces output to a file (usually sys.stdout) and returns None, repr() calls the object's __repr__ dunder and returns a string
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))
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
3 1
the question here is "why is the behaviour different when the function pointers are the same"
you swapped sum and print first right?
i dont swap them
its 1 way
!e
from einspect import view
view(sum) << print
view(print) << repr
sum(1, print(1), repr(1))
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
1 1 1
seems fine here
do you switch more than just the pointer?
all im doing is switching the pointer for the functions
what pointer?
the pointer to the c function
16 is like... ob_type?
8 is type iirc
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```
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
ah
!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))
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
1 1 1
ty
the << move will move the entire object minus ob_refcnt
Sorry for the late reply, but there is something wrong no ?
For example if you double the imbalanced input it will output 1 even if it shouldn't
Example : [])[])
You dont have to use unsafe here? 
the objects are the same size
ah, 
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))
@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.
i=[];s=input()
for c in s:i+=')]'['(['.index(c)]if c in'(['else(0*i.pop()if i[-1:]==[c]else'_')if c in')]'else[]
print('01'[not i])
```this one should work at least a bit better.
Works wonders ty !
[print(i)for i in range(51)if~i.bit_count()&1]```
can I golf this further?
!e [print(i)for i in range(51)if~i.bit_count()&1]
@earnest wing :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0
002 | 3
003 | 5
004 | 6
005 | 9
006 | 10
007 | 12
008 | 15
009 | 17
010 | 18
011 | 20
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/usivadilod.txt?noredirect
prints numbers that have an even amount of 1s in its binary version
A slightly different idea, probably can be optimized further:
s=set();[s.add(x)for x in range(51)if~-x&x not in s];print(*s)
I know😢
the print can be changed to *map(print,s),
would have to be inside brackets, parens, or braces
@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
👍 sure
import __hello__
No longer prints "Hello world!" in 3.11
You have to do:
import __hello__
__hello__.main()
This ruined my day.
!e import __hello__
@dry mirage :white_check_mark: Your 3.10 eval job has completed with return code 0.
Hello world!
hm
3.11
!e __import__('__hello__').main()
@last locust :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello world!
Thankfully you can at least still one-line it
That's longer than just
print("Hello world!")
now though.
I wonder why this change happened.
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
This is definitely the wrong channel - see #❓|how-to-get-help
Thanks 👍
this is a good way to figure out if a number is even or odd
yeah especially because it stops working for numbers larger than 15
to check if a number is even or odd you only need to check the least significant bit
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
17
!e bin(__import__('math').__getattribute__('pi').__getattribute__('__str__')().__getattribute__('__len__')()).__getattribute__("__len__")()+__import__("math").__getattribute__("e").__getattribute__('__str__')().__getattribute__('__len__')().__getattribute__('__and__')(1)-7
@limpid spruce :warning: Your 3.11 eval job has completed with return code 0.
[No output]
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)
@limpid spruce :white_check_mark: Your 3.11 eval job has completed with return code 0.
1
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()
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
n//2==n/2
I believe struct.Struct.pack() requires bools for bool fields
ez boolean
Won't work for huge numbers
thats why i say "in most cases"
because there are certainly cases where a bool specifically is needed
since when has that been a concern for esoteric code
but most times an int will work just fine
also it works for any integer less than 18014398509481985 which is pretty "huge" anyway
!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)
@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
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```
@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
hm why -3 doesn't work
weird
ah I messed up my calculations on the max
Maybe your max is not the actual limit
!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```
@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
there
I doubled it accidentally
regardless 9 quadrillion is pretty large
will work in most applications lol
It is in range of int64
this gets you the same rangepy is_even = range(-9007199254740992, 9007199254740992, 2).__contains__
53<64, isn't it?
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
I mean it is technically possible to have large int64, use this algorithm and have problems with it
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
This is approximately 99.95% of all int64 numbers 😄
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__
is_even=range(-int(float('inf'))*2,int(float('inf'))*2).__contains__
int(float('inf')) lol
@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"
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
If you're trying to shorten it then maybe while (0, 0, 0) != (coffe1, coffe2, coffe3)?
while any((coffe1, coffe2, coffe3)) is shorter
wait actually
while coffe1|coffe2|coffe3:
is even shorter
could u explain how this works?
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
Thanks 👍
@fleet bridge @past plank
is_even = lambda x: x % 2 == 0
f=lambda x:x%2<1 done
what about is_even = lambda x: x & 1 ^ 1
you can do this??
please dont ping me for no reason
why mad over a little red dot
is_even=lambda s:~s&1
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
best
!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))
@tough willow :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
why are you returning idk for 0
thats smart
0 is definitely even
Yes
You guys really got me curious about esoteric programming in Python--are there any good resources I can use to learn about it?
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
IFcoltransG made a guide for it. It's not finished, and I think it's been shelved, but it's out there if you want to read what exists so far.
code golfing aoc was like golf boot camp so if you do that next year can recommend
other than that, there aren't any resources that i know of for "learning esoteric python"
mainly it's just exploring the boundaries of the language on your own and seeing what other people do with it
Are you aware of what "esoteric" means
that's a bit rude
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
@versed eagle
The correct use of recursion
can anyone know, why there is a need of lambda function in python
you can sort dicts in a list by a specific key in those dicts
key=lambda x: x["timestamp”] for example
oh, interesting!!
theres many other uses but thats one im certain on
got it, thanks for letting me know...

awesome😂
im sure someone here can educate you more on lambda, im not an expert or anything
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.
please don't
i've asked twice already for people to stop doing that
now im having to ask a third time.
:/
Ok i won't
Ok lol
hm
oh, forgot which channel I was in when I sent this
Hi @versed eagle
You should definitely turn off pings
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
Is there any reason you don't put yourself on dnd or turn of this server pings
Sorry i will Stop
then i would miss pings that have an actual purpose, and neither of those would fix the actual issue here.
people are refusing to stop, after multiple instances of me asking them to stop. instead, they are going out of their way to harass me and disrespect my requests for them to stop.
how many times am i going to have to ask before you actually stop
:/
I stopped
no, you haven't. you're continuing to ping me.
Im not
@zinc aurora is here
The reply automatically pings them, think thats what they are meaning

you can click this so it won't ping on reply
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
okay
i turned it off
you just pinged me again.
you have to turn it off on every reply it don't toggle for every reply
lol
okay

🧍
hi
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?
the names are separated by commas, and are all inside strings?
eval(f"[{open("yourfile").read()}]")
yea 👍
eval(f"[{open('yourfile').read()}]")
.close left the chat
the file gets closed in its destructor
which gets called bc its ob_refcnt will be 0
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?
He is trying to do it via esoteric practices
they are*
not so sure since his solution doesn't look esoteric and he is asking what's wrong with his code
i think they are trying to make a one liner? idk
I don't see why you don't just enumerate instead of indexing
alphabetical value, not character value
off by one error
names = ['AVRAM','JACK','BOB']
print(sum([sum([ord(letter)-64 for letter in name])*(names.index(name)+1)for name in names]))``` I dont have you're file of names so I just used 3 for testing purposes
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 👍🏾
does it look like 'A', 'B', 'C', ...?
yes, it is comma separated
it's this
we don't know that
cereal
ok
yes, yes you do
about to golf this
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))
let him cook...
did this get longer?
yeah i edited it
since i accidentally pasted an older version that didn't account for the off by 1 error
ah
ok so we'll read from stdin now
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))
that would require changing the input
why?
because
wait no nvm
are u sure?
ok we're good then
yeah
wait a min
whats the input for this?
because it has to turn
comma separated into a table
eval(f"[{open('f').read()}]")
it will default to a tuple
kk
if there aren't enclosing braces/brackets
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))
ooh thats a good one
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
no walrus in comprehension iterable
sec
good catch
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
l is not defined
i dont this this works
ye it doesn't work
6010368747 is the value i got out of that
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()))))
trying to think of ways to golf
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
Hey @frail forum!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
that's actually a good one
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
yea
it can't for me
hmmm
Hey @rough moat!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Hey @rough moat!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
bro
i dont think it even lets me paste lmao
i'll just put it on github
yeah hastebin doesn't even work
It works fine for me: https://paste.pythondiscord.com/voqepavigi
!paste has instructions on how to use it
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.
ah thanks, stupid mistake, knew it ;p
: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.
!unmute @nimble crescent
:incoming_envelope: :ok_hand: pardoned infraction mute for @nimble crescent.
Sorry about that. Use this for longer blocks of code: https://paste.pythondiscord.com/
ok, thanks
i think this is the wrong channel for what you want
Im sorry, what would be a better channel?
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)
!e open(4)
@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
When SystemErrors can occur?
!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