#esoteric-python
1 messages · Page 93 of 1
@fiery hare :x: Your eval job has completed with return code 1.
001 | <string>:1: SyntaxWarning: 'bool' object is not callable; perhaps you missed a comma?
002 | Traceback (most recent call last):
003 | File "<string>", line 1, in <module>
004 | TypeError: 'bool' object is not callable
wow triggered
!e print(True+True)
@runic ruin :white_check_mark: Your eval job has completed with return code 0.
2
!e print((True+True)**((True+True)*(True+True)))
@runic ruin :white_check_mark: Your eval job has completed with return code 0.
16
!e print(((True+True)**((True+True)*(True+True)))**((True+True)**((True+True)*(True+True))))
@runic ruin :white_check_mark: Your eval job has completed with return code 0.
18446744073709551616
!e print(16**16)
@runic ruin :white_check_mark: Your eval job has completed with return code 0.
18446744073709551616
I should probably move to #bot-commands, sorry
Ah yes, the gzipped code
def m(mat) :
row_flag, col_flag = False, False
for i in range(0, len(mat)) :
for j in range(0, len(mat)) :
if (i == 0 and mat[i][j] == 1) : row_flag = True
if (j == 0 and mat[i][j] == 1) : col_flag = True
if (mat[i][j] == 1) : mat[0][j],mat[i][0] = 1,1
for i in range(1, len(mat)) :
for j in range(1, len(mat) + 1) :
if (mat[0][j] == 1 or mat[i][0] == 1):mat[i][j] = 1
if (row_flag == True) :
for i in range(0, len(mat)) : mat[0][i] = 1
if (col_flag == True) :
for i in range(0, len(mat)) : mat[i][0] = 1
def prt(mat) :
for i in range(0, len(mat)) :
for j in range(0, len(mat) + 1) : print( mat[i][j], end = "" )
print()
#Test Case
mat = [ [1, 0, 0, 1],
[0, 0, 1, 0],
[0, 0, 0, 0] ]
m(mat)
prt(mat) ``` how can i reduce this function.
what should it do?
Q: how do you shuffle a list?
A:
!e
import random
class Holder:
def __init__(self, x):
self.x = x
def __lt__(self, other):
return random.choice((True, False))
def unhold(self):
return self.x
def shuffle(iterable):
return list(map(Holder.unhold, sorted(map(Holder, iterable))))
print(shuffle([1, 2, 3, 4, 5]))
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
[1, 4, 2, 5, 3]
@boreal slate this or something more?
def m(mat) :
rows = [any(x) for x in mat]
cols = [any(x) for x in zip(*mat)]
mat[:] = [[int(j or i) for j in cols] for i in rows]
!e
from contextlib import contextmanager
class Config:
def __init__(self, data=()):
self.data = dict(data)
def __getitem__(self, key):
return self.data.get(key)
def __setitem__(self, key, value):
if value is None:
del self.data[key]
else:
self.data[key] = value
def using(self, key, value):
@contextmanager
def manager():
try:
old = self[key]
self[key] = value
yield
finally:
self[key] = old
return manager()
def __getattr__(self, attr):
if not attr.endswith("_being"):
raise AttributeError(Attr)
key = attr[:-6]
return lambda v: self.using(key, v)
def __repr__(self):
return f"Config({self.data})"
config = Config()
def inject_pi(fn):
def new_fn(*args, **kwargs):
with config.pi_being(3.14):
return fn(*args, **kwargs)
return new_fn
@inject_pi
def circumference(r):
return config["pi"] * r
print(circumference(10))
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
31.400000000000002
@sonic ginkgo I took some inspiration from #☕help-coffee
@formal sandal 
see, it reads like plain English
with config.pi_being(3.14):
"with config.pi being 3.14..."
just like SQL, right
Looks like most of the mock/monkeypatch context managers.
from unittest.mock import patch
with patch.dict(config.data, {'pi': 3.14}):
...
We need to build scalable ™️ , extensible ™️ , flexible ™️ software, so we will take pi from a configuration file!
well we can't have our software breaking if the laws of mathematics change so pi becomes something different
lmao
Any technology, sufficiently advanced...
rather "I have yet to see any problem, however complicated, which, when looked at in the right way did not become still more complicated."
rather "I have yet to see any problem, however complicated, which, when looked at in the right way did not become still more complicated."
@formal sandal "Why solve today's problems when we can create some for tomorrow?"
Anthem of regex
print(*(s[i^1]for i in range(len(s))),sep='')
That could perhaps be shrunk by reusing the len somehow.
print(*(s[i^1]for i in range(len(s))),sep='')
print(''.join(s[i^1]for i in range(len(s))))
not actually shorter, right?
That's better.
print(''.join(a[(i-b)^1]for i in range(len(a)))) to skip on creating s.
that doesn't work
well it doesn't lemme test it again
i think it doesn't work cuz it has a newline at the end
@snow beacon doesn't work with longer and different inputs
Do you have an example of an input that fails, and the differing outputs you get for it?
MPORQTSVUXWZYBADCFEHGJILKN @snow beacon
Is it the M and the N?
YDAFCHEJGLINKPMROTQVSXUZWB this is the output
Which one is the intended output?
I'm a little lost. Which bits are inputs and which are outputs?
MPORQTSVUXWZYBADCFEHGJILKN the input
YDAFCHEJGLINKPMROTQVSXUZWB the output got
ABCDEFGHIJKLMNOPQRSTUVWXYZ the correct output @snow beacon
Thank you. I'll look into it when I get back to my computer.
Oh, I see where you got the question from.
Or maybe where you put it after putting it here?
can i ask you some more questions about the code you just gave @sonic ginkgo
@cedar inlet sure but maybe this isnt the best place? i guess general is too busy..
i wouldnt consider what i wrote esoteric
ill do that
👍
is_prime = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997}.__contains__``` i made an optimized prime checking algorithm for numbers below 1000
I made a primality checker for <100 by encoding them as the bits of an integer.
is_prime = __import__("sympy").isprime
i made an optimized prime checking algorithm
oh wait, it can be even shorter
from sympy import isprime as is_prime
nevermind, this is still shorter:
is_prime=__import__("sympy").isprime
optimised for what?
minimum readability?
I think it's implied in this channel 🙂
!e
import sys
class Builder:
def __init__(self, elements=None):
if elements is None:
self.elements = []
else:
self.elements = elements
def add(self, element):
if (rc := sys.getrefcount(self)) <= 3:
print(f"Psst, nobody knows you're mutating me! refcount: {rc}")
self.elements.append(element)
return self
else:
return Builder(self.elements + [element])
def __repr__(self):
return f"Builder({self.elements})"
b = Builder().add(1).add(2).add(3)
print(b)
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 | Psst, nobody knows you're mutating me! refcount: 3
002 | Psst, nobody knows you're mutating me! refcount: 3
003 | Psst, nobody knows you're mutating me! refcount: 3
004 | Builder([1, 2, 3])
Optimization for the Builder pattern thingy 😄
!e ```py
import sys
class Builder:
def init(self, elements=None):
if elements is None:
self.elements = []
else:
self.elements = elements
def add(self, element):
if (rc := sys.getrefcount(self)) <= 3:
print(f"Psst, nobody knows you're mutating me! refcount: {rc}")
self.elements.append(element)
return self
else:
return Builder(self.elements + [element])
def __repr__(self):
return f"Builder({self.elements})"
b = Builder()
x = b.elements
print(b.add(1))
print(x)```
@stark fable :white_check_mark: Your eval job has completed with return code 0.
001 | Builder([1])
002 | []
...huh
well, you could do del b, then there'll be a bug
!e ```py
import sys
class Builder:
def init(self, elements=None):
if elements is None:
self.elements = []
else:
self.elements = elements
def add(self, element):
if (rc := sys.getrefcount(self)) <= 3:
print(f"Psst, nobody knows you're mutating me! refcount: {rc}")
self.elements.append(element)
return self
else:
return Builder(self.elements + [element])
def __repr__(self):
return f"Builder({self.elements})"
b = Builder()
x = b.elements
a = b.add
del b
print(a(1))
print(x)```
@stark fable :white_check_mark: Your eval job has completed with return code 0.
001 | Psst, nobody knows you're mutating me! refcount: 3
002 | Builder([1])
003 | [1]
there
lol
converts dict of lists into list of dicts:
list(map(dict, map(functools.partial(zip, mapping.keys()), zip(*mapping.values()))))
mapping = {"a": [1, 2], "b": [3, 4]} -> [{"a": 1, "b": 2"}, {"a": 3, "b": 4}]
good
does this channel follow pep
a pep probably
xd
@stray rampart you are truly the special one
a pep demands worship
@sick hound we sometimes implement rejected PEPs in pure python
I think some people also get the impression that PEP is interchangeable with "PEP 8"
i never understood pep numbering
i thought pep 8 was pep 8 cause it happened pretty early in python
and there's https://www.python.org/dev/peps/pep-3119/ which happened in 2007
but something like https://www.python.org/dev/peps/pep-0484/ happened in 2014
so r they just random numbers?
!e ```py
from ctypes import *
c_void_p.from_address(id(int)+(27*8)).value = cast(CFUNCTYPE(py_object, py_object)(lambda s:(yield from range(s))),c_void_p).value
print([*10])
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
^ PEP 276
maybe by altering field of static structure of int type with ctypes
!e ```py
from ctypes import *
c_void_p.from_address(id(int)+(168)).value = cast(CFUNCTYPE(py_object,py_object,py_object)(lambda s,o:so[0]), c_void_p).value
print(10(5))
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | <string>:3: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
002 | 50
'int' object is not callable;
Yeah, exactly, you smart ass interpreter!
how can i overwrite dunder methods of functions? (specifically __mul__) ive been reading the PyFunction struct but im not sure what im looking for
Hmm, not sure it's possible to override __mul__ on functions - they don't have it, and it looks like adding it doesn't make them use it. Can't you use a callable class instead?
i wanted to implement composition. i know i can do it with a class but thats not so much like a function any more
i know its possible to do it with __matmul__ using BRM
you'd need to edit the struct for the function type
@stray rampart they're mostly ascending numbers
anything starting with 3000 means for python3
@stark fable do you mean ctypes fuckery, or recompiling cpython with a different struct? if you mean the former, i couldnt see a way to from looking at the struct
ctypes fuckery
nope
hm, im not sure if im looking at the right file then. what else can be changed? https://github.com/python/cpython/blob/d905df766c367c350f20c46ccd99d4da19ed57d8/Include/funcobject.h
!e ```py
from ctypes import *
def func_mult(self, other):
for _ in range(other):
self()
num_methods = (c_void_p36)()
num_methods[2] = cast(CFUNCTYPE([py_object]*3)(func_mult),c_void_p)
ptr = cast(pointer(num_methods), c_void_p)
c_void_p.from_address(id(type(lambda:0)) + (12 * 8)).value = ptr.value
(lambda:print(1)) * 5```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 1
003 | 1
004 | 1
005 | 1
@gentle pagoda ^ theres an example
@rugged sparrow wow thats so cool, ill need to check the source again to understand how it works lol. thanks! :)
ping me if you want me to explain any of it
yeah im pretty lost actually 😅 what does multiplying a voidptr do? py num_methods = (c_void_p * 36)()
ok so c_void_p * 36 creates a class for a 36 item array of c_void_p
then i instantiate it, creating an empty 36 item array that i can use
(the 36 items is because internally the PyNumberMethods struct can be interpreted as an array of func pointers)
func pointers are all 8 bytes
could that lead to issues or not? i dont know much about C implementation details
because in https://docs.python.org/3/c-api/typeobj.html#c.PyNumberMethods they are all function pointers, its a struct of a single type
and thus can be used as an array
ah okay
yah c typedef struct { long a; long b; long c; } is the same as ```c
long arr[3];
im pretty sure the compiler can add arbitrary padding around the struct fields
and the array elements
well an instance of that struct would be
they will to the nearest alignment
not as much in arrays tho afaik
and in python 9 times out of 10 things will be aligned to 8
no prob
so then we index the second element which is nb_multiply
yup
make a CFUNCTYPE from the mul function, cast it to a fuction pointer
CFUNCTYPE(*[py_object]*3) is actually CFUNCTYPE(py_object, py_object, py_object)
yep
(rettype, arg1type, arg2type)
yea
then we get a pointer to num_methods
cast it to c_void_p to make it easier use the address
(12 * 8) is the offset on the PyType struct that has the pointer to PyNumberMethods
so we insert the pointer to our array there
c_void_p.from_address(id(type) + (12 * 8)) lets us access those 8 bytes as a c_void_p (which will be null if the type has no number methods)
if a function pointer in num_methods is NULL does that trigger TypeError: unsupported operand type(s) for +: 'function' and 'int'?
yup
acc that might first cause a lookup on the base class before it fails
prob does
thanks! that makes sense now :)
yeah thats super helpful, ill try some other stuff
:D
this is just so neat ```py
test = (lambda x: x + 1) * (lambda x: x * 2)
test(3)
7```
noice
Is there a way to hook into getting a global variable (with ctypes or something)? For example, if the variable is not found, it would be looked up in some specific dict.
hm, yes, so just change the type pointer to my subclass of dict
Does global lookup actually looks up stuff in the globals()?
!e ```py
from ctypes import *
class Dict(dict):
singleton = object()
def getitem(self, item):
if self.get(item, singleton) == singleton:
return 'a'
else:
return self.get(item)
py_object.from_address(id(globals()) + 8).value = Dict
print(abc)```
@rugged sparrow :x: Your eval job has completed with return code 139 (SIGSEGV).
001 | Traceback (most recent call last):
002 | File "<string>", line 12, in <module>
003 | File "<string>", line 6, in __getitem__
004 | SystemError: Objects/dictobject.c:1434: bad argument to internal function
oh it didnt like that lol
don't touch me there! -- python internals
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
raise
maybe like this? 
try it
doesn't work 😦
could always hook dict.__getitem__ directly
mwahahahaha
Well, that __getitem__ broke my IPython session 😦
nuuu
I tried to exit and got a segmentation fault
classic
the problem is that globals is checked before __builtins__
@rugged sparrow well i tried replacing tp_new but im not entirely sure i have the index right. i think its 42, but its not calling my function
for what class?
functions
oh ok, rip
!e ```py
from ctypes import *
c_void_p.from_address(id(type(lambda:0)) + (40 * 8)).value = None
(lambda:0)```
@rugged sparrow :warning: Your eval job has completed with return code 0.
[No output]
i wanted to implement currying, so that would need to hook function creation or calling
would any of the accessible functions allow me to hook into that behavior?
you'd need to go thru the source code
could i replace the function type entirely with a wrapper class?
Definitely not safely
could i change the baseclass to have different behavior?
Try it
!e ```py
print(0==type('',(object,),{"eq":(lambda*x:True)})())
@distant wave :white_check_mark: Your eval job has completed with return code 0.
True
def jumping_frog(a,b):
i=0
ans=1
while i<a:
if(b[i]==0):
return ("no chance :-(")
elif b[i-1]>b[i] and i>0:
ans+=1
i-=1
else:
i+=b[i]
ans+=1
return ans``` how can i reduce this code?
What is the code meant to do? It's hard to conceptualise everything without comments.
Hey, is it possible to write this in one list comp?
walk_commands() is an object with the name and aliases attribute
[c.name for c in self.bot.walk_commands()] + [' '.join(c.aliases) for c in self.bot.walk_commands() if c.aliases]
without it becoming a list of tuples
as aliases could be ['']
Maybe something like : ```py
[x for x in (c.name, " ".join(c.aliases)) for c in self.bot.walk_commands() if x]
oh I always put it in the wrong order
[x for c in self.bot.walk_commands() for x in (c.name, " ".join(c.aliases)) if x]
I think
Yep that works, thanks a lot :)
don't know if it is more clear though 😛 But this channel is often about clean code ^^
But this channel is often about clean code
Did you mean about unclear code, though?
oh yeah a negation is clearly missing here ×)
solution=lambda n:all(k%i for i in range(2,int(k**.5)+1))if(k:=n**.5)==k//1<n else 0``` how can i make this code faster it returns True if the number has 3 factors and false if it has less than 3 factors
Why do you square-root k, when it's already a square root?
i had got this formula from a math website on google, don't remember exactly
the goal is to see if squre root is prime
or is this one different
the way you described it, you want to check for 2 factors, not 3 factors
exactly 2 factors → n is prime
exactly 3 factors → n is prime squared
i want to check if they have 3 factors , return true or false accordingly
yes
right
i don;t know how to make it faster
from bisect import bisect_left
# sqrt(1000000000) = 31622
__primes = sieve(31622)
def is_prime(n):
# if prime is already in the list, just pick it
if n <= 31622:
i = bisect_left(__primes, n)
return i != len(__primes) and __primes[i] == n
# Divide by each known prime
limit = int(n ** .5)
for p in __primes:
if p > limit: return True
if n % p == 0: return False
# fall back on trial division if n > 1 billion
for f in range(31627, limit, 6): # 31627 is the next prime
if n % f == 0 or n % (f + 4) == 0:
return False
return True
```first result for primality test
i can't use modules i am trying without them
should i give me a test case i have made one
i just have a json file let me share that in a while, i am away from pc now, will share in a while
totally
https://hastebin.com/jecomivifi.json @vestal solstice
https://en.wikipedia.org/wiki/Pollard's_rho_algorithm#Python_code_sample solves all tests in 9 seconds but makes 1 mistake on 1749728409529
unlucky
hey
or I should say lucky that you included it, or I would think it's a good solution
how much faster do you need it?
the whole thing under 10 seconds?
yes the entire thing
it doesn't really work though
yours takes 1 second for everything and works x)
wait yours is complicated?
yes i think
my friends couldn't understand it
want to create it fast but readable
If it has three factors, it must be a prime number squared. I don't know what to do with that information.
migrated from #internals-and-peps
!e
do=lambda x:x
@do
def f():
x <- getLine
y <- getLine
putStrLn (show(x) ++ ", " ++ show(y))
@formal sandal :warning: Your eval job has completed with return code 0.
[No output]
finally 🧪🥼
now the challenge is to transform it into
def f():
return getLine.__bind__(lambda x: getLine.__bind__(lambda y: putStrLn(show(x) + ", " + show(y))))
In [9]: class Test:
...: def __neg__(self):
...: return self
...: def __gt__(self, other):
...: print(f'binding {other}')
...:
...: class Var:
...: def __init__(self, name):
...: self.name = name
...: def __repr__(self):
...: return self.name
...:
...: x = Var('x')
...: getLine = Test()
...: x <- getLine
binding x
well, that's the obvious part
oh, if you just want to transform it with the decorator i suppose you can just do some ast hack
In [12]: from prettiest_ast import ppast
...: from inspect import getsource
...:
...: def do(func):
...: ppast(getsource(func))
...: return func
...:
...: @do
...: def f():
...: x <- getLine
...: y <- getLine
...: putStrLn (show(x) ++ ", " ++ show(y))
...:
FunctionDef
├──f
├──arguments
├──Expr
│ ╰──Compare
│ ├──Name
│ │ ├──x
│ │ ╰──Load
│ ├──Lt
│ ╰──UnaryOp
│ ├──USub
│ ╰──Name
│ ├──getLine
│ ╰──Load
├──Expr
│ ╰──Compare
│ ├──Name
│ │ ├──y
│ │ ╰──Load
│ ├──Lt
│ ╰──UnaryOp
│ ├──USub
│ ╰──Name
│ ├──getLine
│ ╰──Load
...
this was a bigger ast than i expected
that's what she said
that's what she said
!e
from functools import lru_cache
def LruSet(max_depth):
_HACK = False
@lru_cache(maxsize=max_depth)
def has(element):
return _HACK
def push(element):
nonlocal _HACK
_HACK = True
has(element)
_HACK = False
return (has, push)
has, push = LruSet(3)
push(1)
push(2)
push(3)
push(4)
push(5)
print(has(5), has(4), has(3), has(2), has(1))
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
True True True False False
why is everything here so weird
if it's not weird, it doesn't belong here lol
oh..
!e
import string; print(''.join((z := ' ' + string.ascii_lowercase + '.,')[z.index(i)-2] for i in 'yj.bkubgxgt.vjkpibjgtgbuqbygktf'))
@fiery hare :white_check_mark: Your eval job has completed with return code 0.
why is everything here so weird
@sick hound
!e
t = (lambda data,encode=True:(lambda f,*args:f(f,*args))((lambda self,b64,iters,quine:(bytes.decode,lambda string:f"{quine}{ascii(quine)}))(\'{b64.b64encode(string).decode()}\',False)")[encode](bytes(map(lambda base,key:(base+(encode or~encode)*key)%256,(b64.b64decode,str.encode)[encode](data),iters.cycle(self.__code__.co_code))))),*map(__import__,('base64','itertools')),'(lambda data,encode=True:(lambda f,*args:f(f,*args))((lambda self,b64,iters,quine:(bytes.decode,lambda string:f"{quine}{ascii(quine)}))(\\\'{b64.b64encode(string).decode()}\\\',False)")[encode](bytes(map(lambda base,key:(base+(encode or~encode)*key)%256,(b64.b64decode,str.encode)[encode](data),iters.cycle(self.__code__.co_code))))),*map(__import__,(\'base64\',\'itertools\')),'))('62jjIfBzp2bcZ9Z62Grtds0i8GiLZZRz4yL+aM9zyA==',False)
print(t)
@snow beacon :white_check_mark: Your eval job has completed with return code 0.
why is everything here so weird
(From my obfuscator for the challenge a while ago.)
The code just appends the last set of brackets (('62jjIfBzp2bcZ9Z62Grtds0i8GiLZZRz4yL+aM9zyA==',False)) to its own source code.
ah
I think this might break on different Python versions, because it depends on the exact bytecode the code gets compiled to. By break, I mean code generated in one version won't be compatible with other Python versions.
!e ```py
t = (lambda data,encode=True:(lambda f,*args:f(f,*args))((lambda self,b64,iters,quine:(bytes.decode,lambda string:f"{quine}{ascii(quine)}))('{b64.b64encode(string).decode()}',False)")[encode](bytes(map(lambda base,key:(base+(encode or~encode)*key)%256,(b64.b64decode,str.encode)encode,iters.cycle(self.code.co_code))))),*map(import,('base64','itertools')),'(lambda data,encode=True:(lambda f,*args:f(f,*args))((lambda self,b64,iters,quine:(bytes.decode,lambda string:f"{quine}{ascii(quine)}))(\'{b64.b64encode(string).decode()}\',False)")[encode](bytes(map(lambda base,key:(base+(encode or~encode)*key)%256,(b64.b64decode,str.encode)encode,iters.cycle(self.code.co_code))))),*map(import,('base64','itertools')),'))('62jjIfBzp2bcZ9Z62Grtds0i8GiLZZRz4yL+aM9zyA==',False)
print(t)````
@sick hound :x: Your eval job has completed with return code 1.
001 | File "<string>", line 2
002 | print(t)`
003 | ^
004 | SyntaxError: invalid syntax
!e
t = (lambda data,encode=True:(lambda f,*args:f(f,*args))((lambda self,b64,iters,quine:(bytes.decode,lambda string:f"{quine}{ascii(quine)}))('{b64.b64encode(string).decode()}',False)")[encode](bytes(map(lambda base,key:(base+(encode or~encode)*key)%256,(b64.b64decode,str.encode)encode,iters.cycle(self.code.co_code))))),*map(import,('base64','itertools')),'(lambda data,encode=True:(lambda f,*args:f(f,*args))((lambda self,b64,iters,quine:(bytes.decode,lambda string:f"{quine}{ascii(quine)}))(\'{b64.b64encode(string).decode()}\',False)")[encode](bytes(map(lambda base,key:(base+(encode or~encode)*key)%256,(b64.b64decode,str.encode)encode,iters.cycle(self.code.co_code))))),*map(import,('base64','itertools')),'))('62jjIfBzp2bcZ9Z62Grtds0i8GiLZZRz4yL+aM9zyA==',False)
print(t)
@sick hound :white_check_mark: Your eval job has completed with return code 0.
why is everything here so weird
You had an extra ` at the end of the message that had the error.
Also, you can click the
emoji to remove the clutter of the syntax error.
It's calling the function with data = the base64 encoded ciphertext and encode = False. That means it calls bytes.decode on the result of performing some code-related manipulations with the bytes of decoding the data. The encoding means taking the bytecode of the function itself, and using it as the key of an adapted Vigenère cipher. The decoder's code includes the encoder: you just replace the last call with a string, rather than a string and a False. It will print out code like the above, which you can slot into anywhere Python would expect a string.
That's why it has a quine in it.
how to build a binary tree
!e
Node=lambda x,y:type("BinaryTree",(),{"left":x,"right":y,"__repr__":lambda s:f"<{s.left}>-<{s.right}>"})()
Leaf=lambda x:type("BinaryTree",(),{"__repr__":lambda s:f"<{s}>","contents":x})()
print(Node(Node(0, 1), Leaf(2)))# // <!-- Builds a binary tree containing ((0,1), 2) --!>
@snow beacon :x: Your 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 1, in <lambda>
004 | File "<string>", line 2, in <lambda>
005 | File "<string>", line 2, in <lambda>
006 | File "<string>", line 2, in <lambda>
007 | [Previous line repeated 329 more times]
008 | RecursionError: maximum recursion depth exceeded while calling a Python object
That's not meant to happen...
!e
Node=lambda x,y:type("BinaryTree",(),{"left":x,"right":y,"__repr__":lambda s:f"<{s.left}>-<{s.right}>"})()
Leaf=lambda x:type("BinaryTree",(),{"__repr__":lambda s:f"<{s.contents}>","contents":x})()
print(Node(Node(Leaf(0), Leaf(1)), Leaf(2)))# // <!-- Builds a binary tree containing ((0,1), 2) --!>
@snow beacon :white_check_mark: Your eval job has completed with return code 0.
<<<0>>-<<1>>>-<<2>>
Much better.
Oh, maybe you'd be better served in one of the help channels.
Try posting your question in one of the available ones.
This channel is for doing things in the weirdest way possible.
Oh oki
Please do not learn any lessons from what I wrote above.
#algos-and-data-structs might be able to help too @sick hound
Idk what are binary trees for tho
I watched a few videos and they talked about weights, so that means that u have to balance ur binary tree for some reason?
But I'm thinking of making a perfect binary tree if that matters
ILikePython:abs;olutely="!"
This is valid syntax
funny ^^
^^^
huh, I don't get why the ILikePython:abs works. I get the rest, and using anything but a predefined name, like the built-in "abs" here won't work. Is it some unusual side effect of the parser?
@rugged sparrow :warning: Your eval job has completed with return code 0.
[No output]
oh damn, I forgot you can do that on module level
(s := []).append(s)
could you do this in one line before the walrus operator?
locals().setdefault('s', []).append(s)
That doesn't work inside a function, unfortunately.
locals outside a function is basically globals, which is mutable.
Inside a function, the locals dict is read-only.
thanks
Oh hey, it works in a function if you make it globals instead, although it of course sets a global variable rather than a local one.
so not really
There's alwayspy s = (lambda x:x.append(x) or x)([])which is — alas! — not an expression.
s = [s.append(s) or s for s in [[]]][0]```
s,=[s.append(s)or s for s in [[]]] a bit shorter
It does have less square brackets in a row though.
does python have tco?
I have a new challenge for you guys, parser overflows with the least characters possible
Here’s my submission
!e exec('('*999)
@thin trout :x: Your eval job has completed with return code 1.
001 | s_push: parser stack overflow
002 | Traceback (most recent call last):
003 | File "<string>", line 1, in <module>
004 | MemoryError
I can't top that.
hey , I should reduce this code from 7 lines to only 2 , can someone help me :
def fac(*x):
for a in range(len(x)):
r = 1
for i in range(list(x).pop(a)):
r+= r * i
print("\nLa factorielle de",x[a],"est :",r)
fac(x-1,y-1)
@cedar thicket use the included factorial operator
f=lambda n,o=1:[(o:=o*i)for i in range(1,n+1)][-1]
this probably isn't esoteric enough but I always liked it
a = 256
b = 256
c = 257
d = 257
#Guess the answers before running
a == b
a is b
c == d
c is d```
could we golf this further?
from turtle import*
getscreen()
Turtle()
[(forward(30),right(x))for x in[270,90,90]*3]
obv a one liner is
[__import__("turtle").getscreen(),__import__("turtle").Turtle(),[(__import__("turtle").forward(30), __import__("turtle").right(angle)) for angle in [270,90,90]*3]]
but eh, that only increases the char count
oh and what that does is draw a cross, like so
I am pretty sure you can omit getscreen()
Turtle()
@rugged sparrow it's -5 to 256, not -256 to 256
>>> x = -5
>>> y = -5
>>> x is y
True
>>> x = -6
>>> y = -6
>>> x is y
False```
oh i thought it was -256 for some reason
@cursive plover py (lambda t:[(t.forward(30),t.right(x))for x in[270,90,90]*4])(__import__('turtle'))
if all we want is short,
from turtle import*
for x in[270,90,90]*4:forward(30);right(x)
list comps are not shorter than real loops
yeah the realisation
1 letter shorter
from turtle import*
for x in[3,1,1]*3:forward(30);right(x*90)
this is 14 letters instead of 35 so it's 21 letters shorter py exec(''.join(map(chr,[102, 114, 111, 109, 32, 116, 117, 114, 116, 108, 101, 32, 105, 109, 112, 111, 114, 116, 42, 10, 102, 111, 114, 32, 120, 32, 105, 110, 91, 51, 44, 49, 44, 49, 93, 42, 51, 58, 102, 111, 114, 119, 97, 114, 100, 40, 51, 48, 41, 59, 114, 105, 103, 104, 116, 40, 120, 42, 57, 48, 41])))
@stark fable how even did you get that
>>> ''.join(map(chr,[102, 114, 111, 109, 32, 116, 117, 114, 116, 108, 101, 32, 105, 109, 112, 111, 114, 116, 42, 10, 102, 111, 114, 32, 120, 32, 105, 110, 91, 51, 44, 49, 44, 49, 93, 42, 51, 58, 102, 111, 114, 119, 97, 114, 100, 40, 51, 48, 41, 59, 114, 105, 103, 104, 116, 40, 120, 42, 57, 48, 41]))
'from turtle import*\nfor x in[3,1,1]*3:forward(30);right(x*90)'```
what?
it's just this code py from turtle import* for x in[3,1,1]*3:forward(30);right(x*90)
it execs that code
yeah but how'd ya get the numbers
>>> list(map(ord, '''from turtle import*
... for x in[3,1,1]*3:forward(30);right(x*90)'''))
[102, 114, 111, 109, 32, 116, 117, 114, 116, 108, 101, 32, 105, 109, 112, 111, 114, 116, 42, 10, 102, 111, 114, 32, 120, 32, 105, 110, 91, 51, 44, 49, 44, 49, 93, 42, 51, 58, 102, 111, 114, 119, 97, 114, 100, 40, 51, 48, 41, 59, 114, 105, 103, 104, 116, 40, 120, 42, 57, 48, 41]```
ah, I see
plz , a script which can calculate the factorial of a number in 1 line (without using math.factorial)
hm,
print(__import__('functools').reduce(lambda a,b:a*b,range(1,int(input())+1)))
@cedar thicket f=lambda n,o=1:[(o:=o*i)for i in range(1,n+1)][-1]
f = lambda n: (lambda f, n=n: f(f, n))(lambda f, n: f(f, n-1)*n if n > 1 else n)
@cedar thicket
f=lambda n,o=1:[(o:=o*i)for i in range(1,n+1)][-1]
@rugged sparrow Sorry !! but it should take a tuple as arg 😩
how about a little contest for generating a 100 thousand long password? only speed matters, using chars a-z.
i suggest using this snippet to test the code using the python bot so your pc doesnt influence the runtime
from timeit import timeit
n = 1000
# write a function f
def f():
return -1
_runtime = timeit(f, number=n)
print(_runtime / n)
f = lambda: "b"*100000
That's exactly what I wanted to do 😛
@cedar thicket a tuple of what?
What do you consider random?
And how long should they be ?
I would argue that since random distribution is not rated, that solution is valid
@cedar thicket a tuple of what?
@rugged sparrow of int !!
ok i wrote you a factorial function you can implement it
!e ```py
from timeit import timeit
from time import time_ns
n = 1000
write a function f
def f():
t = time_ns()
letters = "qwertyuiopasdfghjklzxcvbnm"
password = ''.join([letters[((i*t) ^ t + t) % 26] for i in range(100)])
return password
_runtime = timeit(f, number=n)
print(_runtime / n)
@copper thunder :white_check_mark: Your eval job has completed with return code 0.
5.273654405027628e-05
ok i wrote you a factorial function you can implement it
@rugged sparrow this one is with the math.factorial methode : fac=lambda*x:[print("La factorielle de",i,"est:",m.factorial(i)) for i in list(x)]
I need it without any predefined methode
so use the one i sent
howdy
how much random is random? 🤔
What's the measure of randomness here?
Equal distribution, randomly sampled
what kind of randomness?
computers generally don't produce or have access to proper random randomness which afaik you can only really get from quantum mechanics
is random random enough? what about implementing your own PRNG?
should it use an external source like urandom or random.org or generate the "randomness" internally with algorithms that just kind of look random?
What ever works for you
Pseudo random is good enough
If a human can recognize the pattern then it's not random enough
If a human can recognize the pattern then it's not random enough
well whether the human can recognize it depends on who the human is and how much experience they have with identifying patterns in a string of 100,000 characters

Lol
if you use an algorithm that is definitely pseudo-random but is also simple enough that someone comes along who can compute it in their head well enough to recognize the pattern in the password...
It was just meant as a fun exercise :(
But yes, if you find out that some other pseudo random algo is faster, go for it
For instance on the gpu this one is pretty popular for it's simplicity: glsl frac(sin(dot(uv,float2(12.9898,78.233)))*43758.5453123);
In this case for 2d inputs
!e ```py
from timeit import timeit
from time import time_ns
n = 1000
write a function f
def f():
t = time_ns()
letters = "qwertyuiopasdfghjklzxcvbnm"
password = ''.join([letters[((i*t) ^ t + t) % 26] for i in range(100000)])
return password
_runtime = timeit(f, number=n)
print(_runtime / n)
@copper thunder :warning: Your eval job timed out or ran out of memory.
[No output]
It really can be any of the two 🤔 Anyone has a guess without trying the code with a generator instead of a list ?
help?
that's what people usually scream when they scroll through this channel 🙂
see #❓|how-to-get-help @tidal mica
@sick hound yes, that's the general idea 🙂
lmao
@thin trout :warning: Your eval job has completed with return code 0.
[No output]
yes
So if a name isn’t found, it will default to it?
Or builtins have the priority over the current scopes
In [12]: (__builtins__ := defaultdict(lambda: 'Hello')).update(vars(__import__('builtins')))
In [13]: test
Out[13]: 'Hello'
In [14]: int
Out[14]: int
I mean, if you do foo = 'bar', will foo still point to 'bar'?
Noice
__builtins__ = None```
We worked out you can recover a few of the important things if you delete all builtins.
__builtins__ = ().__class__.__base__.__subclasses__()[80].acquire.__globals__['sys'].modules['builtins']``` :P
del __builtins__
del ().__class__.__base__.__subclasses__()[80].acquire.__globals__['sys'].modules['builtins']``` what about now?
what the fuck
oh shit that completely fucks it
>>> del __builtins__
>>> del ().__class__.__base__.__subclasses__()[80].acquire.__globals__['sys'].modules['builtins']
>>> print
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: lost builtins module
>>>
Where is that RuntimeError coming from?
Python 3.8.5 (default, Sep 5 2020, 10:50:12)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.18.1 -- An enhanced Interactive Python. Type '?' for help.
In [1]: del __builtins__
In [2]: del ().__class__.__base__.__subclasses__()[80].acquire.__globals__['sys'].modules['builtins']
In [3]: print
Out[3]: <function print>```Seems to work for me.
Probably an IPython thing.
>>> del __builtins__
>>> del ().__class__.__base__.__subclasses__()[80].acquire.__globals__['sys'].modules['builtins']
>>> print
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: lost builtins module
>>> print
<built-in function print>
@sick hound
del __builtins__
globals()["__builtins__"].clear()
@next flame does it automatically recover from that?
yeah
We might need to keep the module around, just delete its contents.
I think that's what the globals()["__builtins__"].clear() thing does.
The problem is that most of the important classes are still in memory.
def z(s, y):
return ''.join([chr(ord(x) + y) for x in s])
def g(s):
return getattr(__builtins__, z(s, 1), 2)
def a(j, f):
return g("fds`ssq")(j, f)
def d(o):
return a(__import__(z("a`rd53", 1)), z("^20`a_k`a", 4))(o).decode("utf-8")
x = (g("hmots")(d("SG93IG11Y2ggd291bGQgeW91IGxpa2UgbWUgdG8gY291bnQgdXAgdG8/IA==")))
g(d("b3FobXM="))(a(', ', 'join')([g("rsq")(x) for x in g('q`mfd')(g("hms")(x))]))```
as you can see, I write only the cleanest of code
I didn't give much thought to that, but might be a good idea to run code from esoteric-python in some isolated environment because you don't always know what is actually executed 😛
!e
А = 0
print(A)
@cloud garden :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | NameError: name 'A' is not defined
Unicode shenanigans, I presume?
!charinfo А
\u0410 : CYRILLIC CAPITAL LETTER A - А
!charinfo A
\u0041 : LATIN CAPITAL LETTER A - A
hmmmmmmmmmm
!e
Truе = False
print(Truе)
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
False
@twilit grotto yes, this joke is literally a billion years old
I guess I'm not cool enough
@twilit grotto all the cool kids already know the cyrillic alphabet by heart 
@sick hound nah, you can't redefine
True
False
None
ah
I just replaced one letter with a cyrillic one
>>> import random
>>>
>>> def true():
... if random.randint(0, 1) == 1:
... return True
... return False
...
>>> true()
True
>>> true()
False
>>>
if only that could be capitalized
and you defenitly could make that smaller
Well, I'm afraid you can't overwrite True's data because it's in a read-only memory section
big sad
@formal sandal not if you use memprotect to change that
the mprotect Linux syscall and the virtualprotect func on windows
I just call both memprotect
oh, well, sorry for nitpicking, that's just what google showed me
Nah you're good
I might write code tonight that just sets pythons entire address space to rwx to allow for shenanigans
So you'll have to write a C extension, right?
Nope
Ctypes will do it
Cause I can just get a handle to libc for Linux then call mprotect
On windows I can just use windll
print('hi guys')
@formal sandal True isnt a protected memory region
!e py from ctypes import * import sys (c_char*sys.getsizeof(True)).from_address(id(True))[:] = b'\x00' * sys.getsizeof(True) #wipe the memory of the object print(True) #segfault
@rugged sparrow :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
welp
I'm pretty sure snekbox is on linux
!e print(hex(id(True)))
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
0x7f90fe271540
wtf
!e import ctypes;print(ctypes.sizeof(ctypes.c_ssize_t()))
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
8
def solution(a, b, k):
if a == b: return 1
y = (int(i,35) % 2 for i in(a,b))
if len(set(y)) < 2:
l = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
d = 1 if abs(int(a[1]) - int(b[1])) == abs(l.index(a[0]) - l.index(b[0])) else 2
return d <= k
return 0
anybody know if i can make my code faster? i'm trying to see if a bishop in position a can reach to position b in k moves. the input for a and b will be in this format "a1" (so basically column letter and then the number of the square the bishop is in). and k will be an int
& 1 is almost always going to be faster than % 2.
Also, you may want to use a dictionary rather than using .index so much.
You can also split y into two parts and do y1 != y2 rather than converting to a set and taking the length.
The bot uses Linux
@snow beacon thanks dude!
@formal sandal that package (https://pypi.org/project/five/) is the most useful thing I've ever seen
I recently discovered the unpack-single-element-in-sequence "operator" ,= (foo ,= [23]; assert foo == 23 ). Are there any other things in this category? (things that look like seperate operators or similar concepts, but are just quirks, or based on intentional misformatting, etc.)
😄
yes, it's the "pistol operator"
like the --> operator in C https://stackoverflow.com/questions/1642028/what-is-the-operator-in-c
I don't know anything like that, but I could search
There's also "custom operator" syntax:
hello <div> world
this is parsed as hello < div > world and will be evaluated as hello < div and div > world
but this will break down because of chained comparison stuff
So hello @div@ world or hello +div+ world also work
Also this:
def f():
x <- getLine
y <- getLine
putStrLn (x ++ ", " ++ y)
return ()
^ valid Python syntax (although... might be hard to implement, definitely would require screwing with ctypes)
main = do
x <- getLine
y <- getLine
putStrLn (x ++ ", " ++ y)
return ()
^ valid Haskell, actually works
@restive void
so I guess <-, ++ and -- count.
call @me
You can also do some interesting "operator" mashing with _
<=_=>, -_._-, ++_++
I wrote an entire story in a different channel
Don't forget the dumbbell clear operator:
x = [a for a in range(10)]
x [:]=[]
assert x == []
maybe I can find it
letter ,= xs
"you better give me your element, xs"
"or else..."
ys ;x//= H==i, xs
"return my element. right now."
ys ;x//= H==i, xs
ys ;x//=K< H==i, xs
ys ;x//= - H==i, xs
ys ;x//= - H==i, xs
ys ;x//= - H==i, xs
ys ;x//= H==i, xs
ys ;x//= H==i, - xs
ys ;x//= H==i, # xs
ys ;x//= H==i, # xs
"never"
ys**(z,)
ys**(z, z)
ys**(z, z, z)
ys**(z,)
ys**(z, z) ,Xs
ys**(z, z, z) ,Xs
ys**(z,) ,Xs
ys**(z, z,) ,Xs
ys**(z, z, z),X . s
ys ,t- Xs
ys ,t- Xs
ys ,t-Xs
t<ys<---Xs
t<ys<Xs
Xs -t, # ys
Xs -t, # ys
Xs -t, # ys
Xs -t, # ys
"that's for my brother"
all valid python syntax
except for some indents
is that assembly but in python
@wanton tundra
@wanton tundra Nah, you can do "assembly but in python" by writing directly in CPython bytecode
just what i would expect from this channel
So you know how in Scratch or similar visual programming tools blocks with different purposes have ports with different shape. But what if a language had a full-blown type system based around block shapes? For example, you could combine basic types to make compound types:
And, perhaps, this system could be operated with physical objects as a fun educational tool
However, this might have problems with physical representation because of generic types.
For simple stuff, you can make a type into which you can insert a special "type peg":
But this will not work on generic functions like map : (A -> B) -> List[A] -> List[B] or first : Pair[A, B] -> A.
Anyhow, this might be a fun language to implement in Python.
Like Scratch, but with an artificially overcomplicated type system.
Although implementing it physically would be more fun: instead of throwing an exception you could simply explode a block
That's the idea 🙂
@formal sandal ev3 codeblocks do this
@formal sandal I'm pretty sure your example can be done without using ctypes, just by implementing some dunder methods. But cool ideas!
For example, I once implemented shell-like piping without any ctypes hackery: https://github.com/L3viathan/pypes
ev3 codeblocks do this
Sorta doubt this
@restive void but if you used ctypes you wouldn't have needed to use neg or O
@rugged sparrow how so? I need some way to say "evaluate now", don't I?
@restive void No, ctypes will be needed. Because you can't apply unary plus to strings.
You could look at the current frame for the context to know when to exec
https://kernemporium.github.io/articles/en/auto_unpacking/m.html is it esoteric python ?
Deobfuscation with qiling
Interesting, but not really a good fit for this channel
This channel is for weird python stuff @heavy mango
Did a message here just disappear or am I going mad?
Anyway, what's an obfuscated method to concatenate two lists?
concat=lambda x,y: [
x
for x in [x[:]]
for yv in [[y]]
for _ in y
for a,*b in yv
for _ in [x.append(a)]
for yv[0] in [b]
][-1]```
I don't get the main topic of this channel-
._. yeah seemed very weird
@constant_singleton()
class THISThreadManagerTYPE1999:
pass
print(THIS_THREAD_MANAGER_TYPE_1999)
Just wrote a new decorator
plays hell with ide inference though
Well, note that it changes the name
THISThreadManagerTYPE1999 -> THIS_THREAD_MANAGER_TYPE_1999
Also takes *args/**kwargs, but yeah
using
re.compile(r"([A-Z][a-z]+)|([0-9]+)")
for the conversion
but why not write the name in SCREAMING_SNAKE_CASE in the first place? 🙂
the trick is to use it with re.split
Because it feels really weird to write
class THREAD_MANAGER:
well, it will give proper typechecker support 🙂
def constant_singleton(cls: Type[T]) -> T:
...
this is true
and the conversion is not that obvious tbh
"where the hell does THREAD_MANAGER come from???"
I actually found doing the typevar annotation confused my editor more than not
This is true
Well, how else to get T?
T = TypeVar("T")
def singleton(cls: Type[T]) -> T:
except it's more awkward because it's got an outer wrapper to pass in arguments
def singleton(*args, **kwargs) -> Callable:
T = TypeVar("T")
def wrap(cls: Type[T]) -> T:
return cls(*args, **kwargs)
return wrap
Or does TypeVar go on the outside here?
I'm pretty sure mypy or similar actually check globals, so that might break things
I'm pretty sure it goes outside
this works for me
I think your editor doesn't like it because Callable is too broad (do the inner type annotations even matter?
this works
perfect, thanks
Actually, pyright will infer the type of the function 😛
So I don't need to repeat the annotation
yeah, same here
@formal sandal not to bother you, but do you know of a way to assert matching type signatures for functions
can you show an example?
This:
import typing
def precall(
func: typing.Callable[[],
typing.Any],
) -> typing.Callable[
[typing.Callable[T, R]],
typing.Callable[T, R],
]:
pass
it accepts a function (A), and returns a function (B) that accepts another function (C), and returns a function with the same type signature as C
ty
wait
That's precisely what I'm looking for
If it's A -> (B -> (C -> C)), then you can make a type variable that is bound to Callable
import typing
C = typing.TypeVar("C", bound=typing.Callable)
def precall(
func: typing.Callable[[],
typing.Any],
) -> typing.Callable[[C], C]:
pass
or maybe you need to use abc.Callable, i don't remember
maybe we need a new channel for gradual typing 🤔
ParamSpec can't really save me
also this is probably wrong, but not too far off, I hope:
P = typing.ParamSpec("P")
W = typing.ParamSpec("W")
WR = typing.TypeVar("WR")
def meta_precall(
*args: P.args,
**kwargs: P.kwargs,
) -> typing.Callable[
[[typing.Callable[typing.Concatenate[Tuple[W.args], P.args, Dict[W.kwargs], P.kwargs]],
bool,
],
typing.Callable[
[typing.Callable[W, WR],
WR,
],
]:
...
You make me sad
from functools import reduce;_,o=map(int,input().split()),input();exec(f"print(reduce(lambda x,y:x{o}y,_))")
One line calculator with multiple arguments
Don't know how I can get any smaller than this
import functools as f;_,o=map(int,input().split()),input();exec(f"print(f.reduce(lambda x,y:x{o}y,_))")```
@sick hound
i tried every variant import i could think of and that was the shortest overall py from functools import reduce;_,o=map(int,input().split()),input();exec(f"print(reduce(lambda x,y:x{o}y,_))") from functools import reduce as r;_,o=map(int,input().split()),input();exec(f"print(r(lambda x,y:x{o}y,_))") import functools;_,o=map(int,input().split()),input();exec(f"print(functools.reduce(lambda x,y:x{o}y,_))") import functools as f;_,o=map(int,input().split()),input();exec(f"print(f.reduce(lambda x,y:x{o}y,_))")
you can shorten it a bit more if you're ok with flipping around the order that things need to be inputted py import functools as f;o=input();exec(f"print(f.reduce(lambda x,y:x{o}y,map(int,input().split())))")
Woah
Damn
Wait, can we have input inside f-string
Can’t try it right now, don’t have my laptop or computer
I’ll try it later I guess
oh, yep, that makes it even shorter actually py import functools as f;exec(f"print(f.reduce(lambda x,y:x{input()}y,map(int,input().split())))")
print(eval(input().join(input().split())))
``` if you are ok with flipping the order
good point yeah that works
Hi, can someone explain why I can't do def f(n): return eval('all(n % i != 0 for i in [2,3,5])') to get a function that returns that n is not divisible by 2, 3 or 5? When I do f(10) I get "NameError: name 'n' is not defined". However def g(n): return eval('n > 10') works fine to define a function that returns that n is greater than 10 and so g(10) returns False
And yes I explicitly want to use eval since I actually need to evaluate user provided strings
Use dis.dis and compile to inspect the produced bytecode.
1 0 LOAD_NAME 0 (all)
2 LOAD_CONST 0 (<code object <genexpr> at 0x7f46f61c2030, file "4234234", line 1>)
4 LOAD_CONST 1 ('<genexpr>')
6 MAKE_FUNCTION 0
8 LOAD_CONST 2 ((2, 3, 5))
10 GET_ITER
12 CALL_FUNCTION 1
14 CALL_FUNCTION 1
16 RETURN_VALUE
Disassembly of <code object <genexpr> at 0x7f46f61c2030, file "4234234", line 1>:
1 0 LOAD_FAST 0 (.0)
>> 2 FOR_ITER 18 (to 22)
4 STORE_FAST 1 (i)
6 LOAD_GLOBAL 0 (n)
8 LOAD_FAST 1 (i)
10 BINARY_MODULO
12 LOAD_CONST 0 (0)
14 COMPARE_OP 3 (!=)
16 YIELD_VALUE
18 POP_TOP
20 JUMP_ABSOLUTE 2
>> 22 LOAD_CONST 1 (None)
24 RETURN_VALUE
vs
1 0 LOAD_NAME 0 (n)
2 LOAD_CONST 0 (0)
4 COMPARE_OP 2 (==)
6 JUMP_IF_TRUE_OR_POP 18
8 LOAD_NAME 1 (h)
10 LOAD_NAME 0 (n)
12 LOAD_CONST 1 (1)
14 BINARY_SUBTRACT
16 CALL_FUNCTION 1
>> 18 RETURN_VALUE
Apparently, the names in the outermost scope are looked up using LOAD_NAME because the scope can't really be resolved at runtime.
@dense marlin By 'user-provided' you mean that
a) responsible owner of the machine will type in the strings; or
b) random person will send the string via an HTTP request?
Well, as you can see, a generator expression is actually a function call, and accessing n happens inside the body of that function, and it decided that it's actually a global variable. You can pass n together with the globals dict (using a ChainMap, for example).
!d eval
eval(expression[, globals[, locals]])```
The arguments are a string and optional globals and locals. If provided, *globals* must be a dictionary. If provided, *locals* can be any mapping object.... [read more](https://docs.python.org/3/library/functions.html#eval)
I don't know if you can use a ChainMap here 🤔
And if the answer to <#esoteric-python message> is b), you absolutely shouldn't be using eval, obviously
You can do ```py
eval('lambda n=n:...')()
Also, if all you need are built ins rather than globals, you can just pass a dict literal as global
@next flame @formal sandal a) "responsible owner of the machine will type in the strings"
it's extremely unlikely that you actually need to use eval
can someone tell me how to make a code in python a window i can access and use?
Someone in one of the help channels will be able to.
What this channel about?
general python
Huh
it's not really for general python
it's for weird weird stuff you can do with python
like asking how to make your code shorter and shiz
testing1=lambda n:n*(x:=len(str(n)))-int('1'*x)
any clue how i can shorten this or make it faster?
Hmmm
now don't clutter up the chat so ppl can see this @sick hound please ❤️
@half sigil I'm not sure plus is cluttering the chat with a single message. Two concurrent conversations in a topical chat are fine.
Oh, ha, let me try: izzy, don't clutter up the chat with jokes. We are a very serious channel doing very serious code for serious people.
okay?
(A joke.)
@snow beacon Stop cluttering this chat with telling other people not to clutter the chat. We will lose all hope of seeing the question again 🙀
testing1=lambda n:n*(x:=len(str(n)))-int('1'*x)any clue how i can shorten this or make it faster?
@half sigil It seems like you're trying to take in a number, multiply it by its length, then subtract the int of '1'*len_of_num
And then it gives some random number?
What is this supposed to do
If you tell us about what it's supposed to do, someone will probably try to find a better way of doing it
nothing really
just a small challenge
i just have to write up an algo to solve these
making it shorter and making it faster are orthogonal and often contradicting goals
@half sigil Had nothing to do, so I searched up time complexities of type conversions in python
I'll have to look more into source code, but str to int and vice-versa takes O(n^2) Not right, ignore everything below. Got the wrong info
int('1'*x)
And there's a better way of doing this
Since it's just 11111s
1 = 10**0
11 = 10**1 + 10**0
111 = 10**2 + 10**1 + 10**0
1111 = 10**3 + 10**2 + 10**1 + 10**0
You can notice this pattern
We can just use a quick for loop for this
def ret1p(n):
cur = 0
for i in range(n):
cur += pow(10, i)
return cur
I used pow here since apparently, it uses fast exponentiation
And I was too lazy to implement it myself
Then we can also replace this
len(str(n)))
You're just trying to find the amount of digits in the number
Wait a second
Hold up
I just thought of something
It might be faster to do py def ret1p(n): cur = 0 for _ in range(n): cur *= 10 cur += 1 return cur
you can use log to find number of digits
YEah I just thought of that
log10
Trying to see what the time complexity of math.log is
you might not get faster than just doing a number of integer divisions of 10
which is O(log n), but not a lot of overhead
i think the complexity of log is probably in that ballpark for arbitrary reals
from time import time
from math import floor, log
def decorator(func):
def wrapper(*args, **kwargs):
times = []
for _ in range(10):
start = time(); func(*args, **kwargs); end = time()
times.append(end - start)
print(func.__name__, sum(times)/len(times))
return wrapper
def ret1p(n):
cur = 0
for i in range(n):
cur += pow(10, i)
return cur
def int_len(n):
return floor(log(n, 10)+1)
@decorator
def original(n):
return n*(x := len(str(n))) - int('1' * x)
@decorator
def optimized(n):
return n*(x := len(str(n))) - ret1p(x)
n = 234923479837459887234742743723478
original(n)
optimized(n)
you didn't call int_len
Both are using functions, so it doesn't really matter
Even with it
It's quite a bit slower
That's surprising
Maybe conversions aren't O(n^2)
I'm not sure why they would be
Python is open-source.
Wait a second
Ah man
When I asked people here in the server to confirm if conversions were O(n^2), no one replied
Seems like I was building code on the wrong premise
Oh well
Makes sense
In [5]: def naive_log(n):
...: digits = 0
...: while n:
...: digits += 1
...: n //= 10
...: return digits
...:
In [7]: def smart_log(n):
...: return int(log(n, 10)) + 1
...:
In [8]: %%timeit
...: naive_log(267624335836053506)
...:
1.77 µs ± 108 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [10]: %%timeit
...: smart_log(267624335836053506)
...:
441 ns ± 1.46 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Holy
Asymptotic complexity doesn't matter when one part is C and one is Python.
The constant factors are important.
Jupyter has in-built timeit?
Wondering how I can implement chess pieces’ movements in as little bit of text as possible. Maybe I’ll try that tomorrow
Izzy was looking into esoteric code for bishop movement recently.
yeye
anyone here know how to declare a struct using ctypes that would map to the following c structure
typedef struct {
MyObj *item[]; //length is `size`
long size;
} MyStruct
``` where `*item[]`'s length depends on `size` and `size` can change
does ctypes have any way of handling elements that can change size?
@rugged sparrow #c-extensions Would be a better place for this
@rugged sparrow that is not valid C https://godbolt.org/z/6qjhEx
isnt the c convention for variable length arrays in structs to put the size first
you have the
struct A {
long size;
char * a[];
};```syntax
@proper vault it is functionally the same as https://github.com/python/cpython/blob/b664a1df4ee71d3760ab937653b10997081b1794/Include/cpython/listobject.h#L9 (which is what i am trying to represent)
C cannot have structs with inconsistent size without that syntax. So I would expect neither can CTypes and you have to deal with raw pointers
i was able to do py class ListStruct(Structure): _fields_ = [ *PyObject_VarHead, ('ob_item', POINTER(py_object)), ('allocated', c_ssize_t) ]
but it doesnt have the safety of treating ob_item as an array
maybe i could customize how ob_item was accessed to add that
you cannot get that safety in C afaik, so I would be surprised if python could
!e ```py
from ctypes import *
PyObject_Head = [
('ob_refcnt', c_ssize_t),
('ob_type', py_object)
]
PyObject_VarHead = [
*PyObject_Head,
('ob_size', c_ssize_t)
]
class ListStruct(Structure):
fields = [
*PyObject_VarHead,
('ob_item', POINTER(py_object)),
('allocated', c_ssize_t)
]
x = [1]
ListStruct.from_address(id(x)).ob_item[0] = 2
print(x)
print(ListStruct.from_address(id(x)).allocated)
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | [2]
002 | 1
This guy's blog is esoteric heaven
q = lambda l,s,e:s<e and (lambda p:(q(l,s,p-1),q(l,p+1,e)))((lambda o=[l[e],s-1,e,0,0,0,0,0,0]:\
(o.__setitem__(6,lambda: (o.__setitem__(4,0),o.__setitem__(5,lambda:(not o[4] and not o[3])\
and ((lambda:(o.__setitem__(1,o[1]+1),(o[1]==o[2]) and (o.__setitem__(3,1),o.__setitem__(4,\
1)) or (l[o[1]]>o[0] and (l.__setitem__(o[2],l[o[1]]),o.__setitem__(4,1)))))(),o[5]())),\
o[5]())),o.__setitem__(7,lambda:(o.__setitem__(4,0),o.__setitem__(5,lambda:(not o[4] and\
not o[3]) and (o.__setitem__(2,o[2]-1),(o[2]==o[1]) and (o.__setitem__(3,1),o.__setitem__\
(4,1)) or (l[o[2]]<o[0] and (l.__setitem__(o[1],l[o[2]]),o.__setitem__(4,1))),o[5]())),\
o[5]())),o.__setitem__(8,lambda:not o[3] and (o[6](),o[7](),o[8]())),o[8](),l.__setitem__(\
o[2],o[0]),o[2])[-1])())
quicksort = q
Never seen something this scary in python
how many lambda's is that lmfao
Nine, it looks to be.
good god
hey guys i am kinda new to this dose annyone wanna help me out with learning this a bit better?
What do you mean by 'this'?
Is that all one godless line?
There's enough of god in the λ-calculus.
That's quicksort in 1 line
my sleep paralysis demon
Who made sort in one line?
i don't understand anything that's happening there lol
Python 3.9 lets you use arbitrary expressions as decorators.
I'm sure that won't lead to any confusing esoteric code at all.
Here's my proposal for parser combinators using decorator expressions:
@one_of("0123456789")[4]
def discrim(digits: str) -> int: # annotations for convenience
return int(digits)
@none_of(" \n\r\t")[1:] - sym("#") + discrim()
def discord_user(name: str, discrim: int):
...
I don't know the exact rules for usernames but you get the gist
does the new decorator syntax support multiline expressions as decorators?
Hi ! I'm sorry i'm new to the server, what is esoteric python?
Everything you wouldn’t want to see in python
I wouldn't want to see mandated docstrings, yet that's not esoteric! @thin trout
class ByOneIncrementer
{
public:
static int incrementByOne(int numberToIncrementByOne) const
/*
* @param int numberToIncrementByOne The number to increment by HOST_CELLS_PER_PIXEL
* @return int the decremented number
*
* Increment the `numberToIncrementByOne` by $loc{ en:one | de:ein | fr:un | ru:один } and return
* the incremented `numberToIncrementByOne`.
*/
{
const int numberToIncrementByOneIncrementedByOne = numberToIncrementByOne - 1;
Logger::getLogger("root").debug("Incrementing %d by %d", numberToIncrementByOne, 3);
Postgres::execute("DROP TABLE students;");
return numberToIncrementByOne;
}
};
What is little boby table doing in here
fixed
@distant wave :white_check_mark: Your eval job has completed with return code 0.
001 | {1: {...}}
002 | {1: {...}}
@flat crown
its somewhere over 2000
hm
!e ```py
import sys
sys.setrecursionlimit(9009)
a = {}
a[1] = a
print(a)
print(eval("a" + "[1]"*9001))
what is esoteric python
@distant wave :white_check_mark: Your eval job has completed with return code 0.
001 | {1: {...}}
002 | {1: {...}}
its over 9000 dictionary accesses lol
bruhhhh
Golfing, Python VM languages, obfuscation, code gore and other general Python weirdness
(lambda: "esoteric python")()
code gore?
ty
wasnt there someone who did quicksort in one line with a shit ton of lambdas
One I wrote myself
P = typing.ParamSpec("P")
W = typing.ParamSpec("W")
WR = typing.TypeVar("WR")
def meta_precall(
*args: P.args,
**kwargs: P.kwargs,
) -> typing.Callable[
[[typing.Callable[typing.Concatenate[Tuple[W.args], P.args, Dict[W.kwargs], P.kwargs]],
bool,
],
typing.Callable[
[typing.Callable[W, WR],
WR,
],
]:
...
It's a triple decorator's type signature
or this, for recovering from an erased__builtins__
The second one isn't esoteric, it is just too much typing haha
both the typing typing and the typing typing
Can this code be made even a incey wincey smaller?
a=lambda x:[i for i in x if i%2]
interesting way to filter out the even numbers, and leave odd ones
No, that's the smallest you can get
Wait
Oh wait
@sick hound Are you trying to get the even numbers?
Because that gives the odd numbers
You have to do
a=lambda x:[i for i in x if i%2==0]
To get even numbers
you can save a char with i%2-1
if you do ~i%2it should work better as you can skip the space after if
don't golf individual parts
it all should rely on each other
e.g. if you're always using it as a(x): you could do a=lambda:[i for i in x if i%2] and a() saving 3 chars
makes sense
@sick hound No i was trying to get the odd numbers itself
~i&1 ideally should be faster o.o
I don’t think it was, yeah
what does ~ do?
-x-1 I'm pretty sure
good example of its usage is subtraction, since x - y is really x + (~y + 1)
@cloud garden https://en.wikipedia.org/wiki/Bit_manipulation#:~:text=Bit manipulation is the act,%2C encryption algorithms%2C and optimization.
https://graphics.stanford.edu/~seander/bithacks.html
Bit manipulation is the act of algorithmically manipulating bits or other pieces of data shorter than a word. Computer programming tasks that require bit manipulation include low-level device control, error detection and correction algorithms, data compression, encryption algo...
Good resources
Thank you
good example of its usage is subtraction, since
x - yis reallyx + (~y + 1)
so isx + (~y)the same asx + -(y + 1)?
yes, it is
while condition or next(iter([1, 0])):
...
make a condition True one more time in a while loop
while do
interesting
that doesn't actually work though
right, next(iter([1, 0])) is always 1
I take that back, not interesting at all
!e ```py
condition = True
l = [0,1]
while condition or l.pop():
print('a')
condition = False
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | a
002 | a
that works
!e
condition = True
true_condition = True
while (condition := not condition) or true_condition:
print("hi")
true_condition = False
@twin reef :white_check_mark: Your eval job has completed with return code 0.
001 | hi
002 | hi
That works too
hi
Found an awesome challenge over at HackTheBox, and I think you guys would enjoy it
The goal is to find a string in format HTB{some_string} on http://165.232.106.154:32169/
Good luck y'all
http://p-nand-q.com/programming/obfuscation/python/quicksort.html
@sick hound This makes me want to write an obfuscator just for the heck of it
good start so far
If you wanna do a more "traditional" obfuscator you could use lambdas instead
Would convert those 4 lines into 1
@grave rover
that's the goal eventually
Interesting
Anyone knows how to use Pygments to make a lexer. I'm confused.
btw if anyone wants to help with this obfuscator, let me know
this part also friggin sucks
But how do you emulate raising exceptions?
