#esoteric-python
1 messages · Page 81 of 1
The sacrifices one must make for concision.
@marsh void it's looks like it's kind of like forbiddenfruit
oh ok
readme says its specifically for making 2+2=5 lol
Talking about forbiddenfruit, have you tried to evaluate a snippet with it?
I did and it worked oddly
And have you tried like numpy, or scipy, or networkx?
||** **||
apparently this is a thing now
or well
again
sending markup without content :^)
chilaxan@Macbook-Air[~/Desktop/python]: python3 -i struct_testing.py
>>> x = {'a': 100}
>>> x.a
100
>>> ```
i did a thing
that looks too much like js
¯_(ツ)_/¯
it is cool though, no doubt about that
dict_struct = PyTypeObject.from_address(id(dict))
def dict_getattr(self, key):
try:
return type(self).__getattribute__(self, key)
except AttributeError as attr_err:
try:
return type(self).__getitem__(self, key)
except:pass
traceback.print_exception(type(attr_err), attr_err, attr_err.__traceback__)
return None
dict_getattr_p = get_cfunc(dict_struct.tp_getattro)(dict_getattr)
dict_struct.tp_getattro = dict_getattr_p
``` uses the struct code from doublescript
imma make setattr work next
it does break dir
>>> x = {'a':1}
>>> del x.a
ValueError: PyObject is NULL
>>> ``` i got setattr to work
but thats a bit weird
yikes C errors
yea...
take key as a void pointer
check for null
if not null cast to py object
might work?
to work on a serious project or my code injection, hmm...
@brazen geyser i only get that error with del
i dont think its toooo important to fix
yes, because del passes NULL as attr into tp_setattro
ohhh it does
and then ctypes tries to work with this as a py_object
which for some reason can't take NULL i guess
idk
def dict_setattr(self, key, val):
if callable(val):
val = type(type('',(),{'a':lambda s:0})().a)(val, self)
type(self).__setitem__(self, key, val)
return 0``` this is my setattr
it's gotta be done at the function pointer level
rather than using a py_object for value argument youd use a c_void_p
i wonder how safe this is with regards to ref counting though
iirc py_object automatically inc/dec refs as needed
rn i clone my cfunc args from the orig func
lel
go for it
you still have to have a ref to the orig func to do it so it still needs a bunch of boilerplate
def get_cfunc(cfunc):
return CFUNCTYPE(cfunc._restype_, *cfunc._argtypes_)```
the void_p seems to get cat back to py_object automatically
due to the definition in _fields_
yea that error is raised before ctypes's hook
🐍 x = [[1]]
🐍 y = [[[1]]]
🐍 x in y
True
🐍 import sys
🐍 for _ in range(sys.getrecursionlimit()):
•• x = [x]
••
🐍 for _ in range(sys.getrecursionlimit()):
•• y = [y]
••
🐍 x in y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RecursionError: maximum recursion depth exceeded in comparison
ehehehe that was fun
you know something good is about to happen when you see for _ in range(sys.getrecursionlimit()) 🍿
def f():
f()
f()```
Alright that's fun but a little bit easy. My goal is to get a RecursionError in one line of code.
I thought I could use an immediately invoked function like (lambda: 42)() but recursion makes it hard.
(f=lambda:f())() throws a SyntaxError which is weird because I thought the assignment operator returned a value (otherwise a = b = 42 wouldn't work) but apparently I'm missing something.
So now I'm trying something like (lambda:getcurrentfunction)() but I don't know where to find such a function.
The SyntaxError was caused by the parentheses before the assignment.
(lambda: 42)() works
(a=42) doesn't
Hmmm,
def ff(): return sys._getframe(0).f_code.co_name -> ff
ff = lambda: sys._getframe(0).f_code.co_name -> <lambda>
That's a bummer.
To be clear, f=lambda:f();f() is cheating.
(f:= lambda: f())()```
I know it's also possible to declare a lambda with lambdas, and make a recursive call from the inner ones
which is more of a mess
I want to call @crystal mica to the stand because I was never able to follow his walrusless recursive lambda abomination for AoC
(lambda x: x(x))(lambda x: x(x))
@snow beacon could you explain what's going there? I don't even know the order I should read it
I read it from the right.
The (lambda x: x(x)) is a function that takes a function and calls it on itself.
In order to make it recurse infinitely, we just need to call it on itself.
Fortunately, we've already figured out what function calls its argument on its argument.
It's the same function.
That's why it repeats.
More explanations, or more lambdas?
more operations in the lambda
such as having a working, and actually useful lambda like that
(lambda x: x(x))(print) prints "<builtin print function>" or something similar to the console. (lambda x: x(x))(str) returns "<builtin class str>" or whatever it is. (lambda x:x())( lambda x: x() ) calls itself on itself on itself on itself on itself...
I like to look at it in terms of beta-reduction.
I mean just recursive lambdas
lambdas can be pretty messy, I don't blame you.
like taking the last one and doing fibonacci recursion
(lambda x: x(x))(print) this isn't hard to read, it's the lambda definition being evaluated first, then we pass print so we print(print)
recursive lambdas mess are my issue lol
not that it matters since they're merely done for esoteric enjoyment but still
it basically is beta-reduction
combinators are fun:
In [44]: Y = lambda f:(lambda x: f(lambda z:x(x)(z)))(lambda x:f(lambda z:x(x)(z)))
...: R = lambda f: lambda n: 1 if n <= 2 else f(n-1) + f(n-2)
...: print(*(Y(R)(i) for i in range(1, 10)))
1 1 2 3 5 8 13 21 34
oh yes
i did that in coconut a while back
was slow as hell, but it looked awesome
im liking the look of Hy tho
>>> utils.edit(list, 'sq_length')(lambda *s:print(s))
<CFunctionType object at 0x1028f2640>
>>> len([1,3])
Python(97991,0x10515adc0) malloc: *** error for object 0x102a3efc0: pointer being freed was not allocated
Python(97991,0x10515adc0) malloc: *** set a breakpoint in malloc_error_break to debug
[1] 97991 abort python3``` this is fun
what
@red timber @snow beacon Two beautiful solutions, thanks
What's the shortest way to get the number of arguments a function takes?
.__code__.co_varnames length of that?
or inspect module
.__code__.co_argcount even better
what should this method return in the case of variadic arguments?
i'm not sure, lemme find out
i meant in terms of spec
I don't think I'm dealing with variadic functions, so it doesn't really matter what it does
co_argcount wont take *args, **kwargs into account i dont think
In [9]: a = lambda *args:None
In [10]: a.__code__.co_argcount
Out[10]: 0
which is probably the best way to handle it
idk, that's rather ambiguous
*args is pretty ambiguous
how will you differentiate between a function that actually doesnt take any arguments?
though
I don't think I'm dealing with variadic functions, so it doesn't really matter what it does
so it doesn't really matter for the problem at hand
i think there is a solution though, but i've long forgetten it
uhhh, i used __code__ in my intcode computer for AoC, and i remember there being some wrinkle for *args, **kwargs
__code__.co_varnames[:f_code.co_argcount + f_code.co_kwonlyargcount]
lemme try that
In [11]: a = lambda a, b, *args, c, **kwargs:None
In [12]: code = a.__code__
In [13]: code.co_varnames[:code.co_argcount + code.co_kwonlyargcount]
Out[13]: ('a', 'b', 'c')
@zealous widget dont forget posonlyargcount (3.8+)
oh nice
@gilded orchid The best way to get an argument count would be to use inspect.signature() on the function - that returns an object you can inspect, and uses a protocol allowing it to produce the right result for builtin functions (which don't have __code__) as well as stuff like functools.partial that have dynamic argument requirements.
@pure dew you were wondering about this the other day
@brazen geyser you also might like to take a look ^
@rugged sparrow I'd rather make iter(123) result in 1, 2, 3 generator
>>> class Int(int):
... def __iter__(self):
... yield from map(int, str(self))
...
>>> list(Int(123))
[1, 2, 3]``` idk
I mean, you can always import _utils and make the wrapper for your code lol
The stuff in there is mainly examples
Honestly I doubt it
Take it to the next level, so Int(10111213) will return 10, 11, 12, 13 lol
Coz Int(10-13) is for casual
Ooo
Time to mod int subtract to make ranges
Lmao
>>> @utils.edit(int, 'nb_subtract')
... @utils.nullwrap
... def int_sub(self, other):
... return range(self, other)
...
>>> 1-2
Traceback (most recent call last):
File "_ctypes/callbacks.c", line 237, in 'calling callback function'
File "/Users/chilaxan/Desktop/python/future/_utils.py", line 16, in wrapper
return func(*map(lambda arg:ctypes.cast(arg, ctypes.py_object).value if arg else Null, args))
File "<stdin>", line 4, in int_sub
TypeError: 'range' object cannot be interpreted as an integer
Traceback (most recent call last):
File "_ctypes/callbacks.c", line 237, in 'calling callback function'
File "/Users/chilaxan/Desktop/python/future/_utils.py", line 16, in wrapper
[1] 2075 segmentation fault python3``` 🤔
i guess subtraction has to return an int
>>> @utils.edit(list, 'nb_subtract')
... @utils.nullwrap
... def list_sub(self, other):
... for item in other:
... try:self.remove(item)
... except:pass
... return self``` ah well i can still do this
>>> x = [1,2,3]
>>> x - [1,2]
[3]```
tbh that should prob use .copy
bruh tf
is that the shit you showed me other day with random C errors but it still ran?
yea
it will basically be a more precise forbiddenfruit module
@dense spire I strongly request to rename this channel to esoteric-cpython, haha
hardly
No, it would be. Sure, a lot of the tweaks and hacks are cpython specific, but not all patterns used here are cpython-specific; most lambda-golfs are perfectly fine according to the language specs and not necessarily cpython-specific.
Oh wait, you actually implement dead PEPs?
Haha that's great!
thanks
anyone here know why raising an exception in a CFuncType python function causes a segfault?
( only when its called from c)
raising like raise?
PyErr_SetString or something was used for that if I didn’t forget it
PyErr_SetString doesnt work
i think this might actually be a bug with ctypes 👀
or acc prob something wrong with how my code works
either way, if an exception is raised, a garbage value is being returned that any operations on fail (except id)
PyObject* raise() {
PyErr_SetString(PyExc_RuntimeError, "test except");
return NULL;
}``` doesn’t this kinda thing work? or are you doing ctypes all the way
Ctypes all the way
Also its probably my code
Cause Im manually initializing the structure within python if the type doesnt have it
@brisk zenith i remember you do a lot of ctypes stuff, do you know how i can properly add a new methods struct to a class? like tp_as_number on a list. I got it to work unsafely (it segfaults on exit, any exception in any of those methods causes it to return a garbage value that) but would prefer it work properly
question about recursion:
say you call getFactorial(3)
1 it adds getFactorial(3) to the stack
2 it adds getFactorial(2) to the stack
3 it adds getFactorial(1) to the stack, which returns 1
4 then it returns 2* getFactorial(1) == 2
5 then it returns 3* getFactorial(2) == 6
my question is can you stop the execution after step 3, such that it doesn't clear the steps 4, 5 from the stack?
@rugged sparrow i'm not sure what you mean. could i see an example? :D
Also I think I fixed adding the struct
I just need to push newest
The issue I'm having now is with exceptions raised inside the CFunctions
nope it still segfaults on exit
>>> from py_future import _utils as utils
>>> @utils.edit(list, 'nb_subtract', safe=False)
... @utils.nullwrap
... def list_sub(self, other):
... return self, other
...
>>> [] - []
([], [])
>>> exit()
[1] 4211 segmentation fault python3
``` @brisk zenith
>>> from py_future import _utils as utils
>>> @utils.edit(list, 'nb_subtract', safe=False)
... @utils.nullwrap
... def list_sub(self, other):
... [*other]
...
>>> x = [] - 1
Traceback (most recent call last):
File "_ctypes/callbacks.c", line 237, in 'calling callback function'
File "/Users/chilaxan/Desktop/python/py_future/_utils.py", line 18, in wrapper
return func(*map(lambda arg:ctypes.cast(arg, ctypes.py_object).value if arg else Null, args)) #TODO solve exceptions issue
File "<stdin>", line 4, in list_sub
TypeError: 'int' object is not iterable
>>> id(x)
140732819296720
>>> # x is now some sort of garbage value somehow
...
>>> print(x)
[1] 4528 segmentation fault python3```
@brisk zenith this is another weird issue with exceptions ^
@rugged sparrow are you doing the references properly?
if the function is something in a type struct then that's a reference to it, so you need to incref it
the error thing is really weird though
I am increasing it's reference count
I should probably make a atexit function to decref it tho
morse=lambda s:''.join((lambda c,i=lambda c,s=0,t=None:int(str(ord(c))[s:t]):{''.join('.-'[int(l)]for(l)in bin(i(a,s=2))[3:]):chr(i(a,t=2))for(a)in'ʏ᧠ᩆʴ᭪ᯊᰰ˞ᵙ᷄̉̒ừὖ῁‒͆͋͛↩∇≹⋟⍄ፓᎯᐏᑱᓔᕈᖴᘜᚂዿ'}.get(c)or' ')(m)for(m)in s.split())
``` golfed morse code translator
The crazy characters are just here for their chr value?
yea
Haha, that’s great!
that string contains all the data needed for a morse code map of letter/number to val
for(a) same bytes as for a
Yeah
@zealous widget if you want to shorten it more be my guest I want to see how short it can get
you can replace s=2 with just 2 I think
You're right
.get(c)or' ' maybe can be
.get(c,' ') (this one I am not sure, you may be using falsey values along with the None
you can replace the outermost comprehension (the one in ''.join) with a map
that works too nice
morse=lambda s:''.join(map(lambda c,i=lambda c,s,t:int(str(ord(c))[s:t]):{''.join('.-'[int(l)]for(l)in bin(i(a,2,9))[3:]):chr(i(a,0,2))for(a)in'ʏ᧠ᩆʴ᭪ᯊᰰ˞ᵙ᷄̉̒ừὖ῁‒͆͋͛↩∇≹⋟⍄ፓᎯᐏᑱᓔᕈᖴᘜᚂዿ'}.get(c,' '),s.split()))
``` @proper vault got it a bit shorter by making `i` not take any kwargs
nice
5 more chars off to get it to 200
you can save 2 chars by adding ,o=''.join to the args of the main lambda and replacing the two calls
true
morse=lambda s,o=''.join:o(map(lambda c,i=lambda c,s,t:int(str(ord(c))[s:t]):{o('.-'[int(l)]for(l)in bin(i(a,2,9))[3:]):chr(i(a,0,2))for(a)in'ʏ᧠ᩆʴ᭪ᯊᰰ˞ᵙ᷄̉̒ừὖ῁‒͆͋͛↩∇≹⋟⍄ፓᎯᐏᑱᓔᕈᖴᘜᚂዿ'}.get(c,' '),s.split()))
``` current version
does it decode or encode?
hi
😄
I'm new to python so yeah. Hi guys.
Hey; this channel isn't intended for some beginner stuff, though; more like abusing C, python's parser and writing one-liners/golfing things.
oh
-~a == a + 1
~-a == a - 1
kinda neat
mhm
I'm not a fully begginer but I don't know what you class a begginer but I can do some random number maths quizzes
!e
from dis import dis
dis('-~1'), dis('a + 1')
@marsh void :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_CONST 0 (2)
002 | 2 RETURN_VALUE
003 | 1 0 LOAD_NAME 0 (a)
004 | 2 LOAD_CONST 0 (1)
005 | 4 BINARY_ADD
006 | 6 RETURN_VALUE
1 0 LOAD_NAME 0 (a)
2 UNARY_INVERT
4 UNARY_NEGATIVE
6 RETURN_VALUE
1 0 LOAD_NAME 0 (a)
2 LOAD_CONST 0 (1)
4 BINARY_ADD
6 RETURN_VALUE
the binary operation is faster
yep
!e from timeit import timeit; t = lambda s: timeit(s, setup='a = 13'); print(t('a = -~a')); print(t('a += 1'))
@marsh void :white_check_mark: Your eval job has completed with return code 0.
001 | 0.08198634907603264
002 | 0.06853515096008778
I have a little challenge for all of you guys
fizz = 0
while True:
fizz += 1
if fizz%3 == 0 and fizz%5 == 0:
print("FizzBuzz")
elif fizz%5 == 0:
print("Buzz")
elif fizz%3 == 0:
print("Fizz")
else:
print(fizz)
if fizz == 20:
break
Make this a one liner
simple ternary expression
print("\n".join(not x%5 and not x%3 and 'FizzBuzz' or not x%5 and 'Buzz' or not x%3 and 'Fizz' or str(x) for x in range(1, 21)))
``` edit: that actually looks a bit nicer and still works
print('1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n11\nFizz\n13\n14\nFizzBuzz\n16\n17\nFizz\n19\nBuzz')
~~```py
any(map(lambda i:print((('FizzBuzz','Fizz'),('Buzz',i))[i%3>0][i%5>0]),range(1,21)))
~~```py
any(print((('FizzBuzz','Fizz'),('Buzz',i))[i%3>0][i%5>0])for i in range(1,21))
```~~
```py
[print((('FizzBuzz','Fizz'),('Buzz',i))[i%3>0][i%5>0])for i in range(1,21)]
oh nice
why any and not []
oo good call
what else
theres probably a way to flatten the tuple and index it once
just gotta figure out the logic
[print((i%3<1)*'Fizz'+(i%5<1)*'Buzz'or i)for i in range(1,21)]
there's probably a way to use less brackets in this
what’s that fizzbuzz thing
for i in range(1,21):print((i%3<1)*'Fizz'+(i%5<1)*'Buzz'or i)
if divisible by 3, print Fizz, if divisible by 5, print Buzz, else print a number
yep?
It prints FizzBuzz if divisible by 15.
I didn’t say elif there! haha
But you didn't put an else clause on the first if.
for i in range(20):print(i%3//2*'Fizz'+i%5//4*'Buzz'or-~i)
It is not the shortest possible, but it is the shortest I know of
That looks pretty short.
that integer division is smart, I spent ages looking for bitwise operators that could do it but didn't find anything
what's the evidence that it's not the shortest @proper vault
there is some website with these where someone got it down to 54 (when going up to 100)
7 people with sub-57 solution
this one?
it counts multibyte characters as 1
this one doesn't have sub 58 solutions
the top 2 are likely cheating
exec('潦湩爠湡敧ㄨ〰㨩牰湩⡴╩⼳㈯✪楆空⬧╩⼵㐯✪畂空漧⭩⤱'.encode('u16')[2:])
```this is 56, exec doesn't even need a string wow
maybe they used 3 or 4-byte characters somehow
What do you mean?
I'm saying lakmatiol solution is likely to be the shortest
the 54 byte solution, upgraded to 53 is from a site that counts several bytes as one, as long as it's one character
Ah, right.
utf has 2,3 and 4 byte characters, 2 byte turns out to be simple
I don't know how to use the larger ones
Oh wait, they have 58 with range 100, how could I miss that
I have a feeling there could be some crazy way to do something like 'FizzBuzz'[something:]or i
where something somehow gets the right string
actually wait you would need something on the other side as well
'FizzBuzz'[4*(i%3>0):4*(i%5==0)+4]or i seems to work
Oh wow
(i%3<1)*'Fizz'+(i%5<1)*'Buzz'or i
'FizzBuzz'[4*(i%3>0):4*(i%5<1)+4]or i```
ok it's actually longer than if you do it the other way
I have a feeling there is a way to shorten both parts of the slicing
the right part can be ~-i%3//2*4 I'm pretty sure
>>> ['FizzBuzz'[~-i%3//2*4:4*(i%5<1)+4]or i for i in range(20)]
['Buzz', 'Fizz', 'Fizz', 3, 'Fizz', 'FizzBuzz', 6, 'Fizz', 'Fizz', 9, 'FizzBuzz', 'Fizz', 12, 'Fizz', 'Fizz', 'Buzz', 'Fizz', 'Fizz', 18, 'Fizz']```
nope
Right part of the slice, not left
oh
wait oops no that's wrong I think
>>> ['FizzBuzz'[4*(i%3>0):~-i%3//2*4]or i for i in range(20)]
['Fizz', 1, 2, 'Fizz', 4, 5, 'Fizz', 7, 8, 'Fizz', 10, 11, 'Fizz', 13, 14, 'Fizz', 16, 17, 'Fizz', 19]```
for reference here's the correct answer ```py
['FizzBuzz'[4*(i%3>0):4*(i%5==0)+4]or i for i in range(20)]
['FizzBuzz', 1, 2, 'Fizz', 4, 'Buzz', 'Fizz', 7, 8, 'Fizz', 'Buzz', 11, 'Fizz', 13, 14, 'FizzBuzz', 16, 17, 'Fizz', 19]```
That one is actually one char shorter than the multiplication, but you need to start from 1, which adds 2 characters
But saves 1 on incrementing
Oh, I miscounted, it is equally long
Or not, I don't know what we're comparing
But it ends up 1 char longer, unless it is acceptable to start from 0
Maybe start with 2 and decrement
I might make a bruteforcer to see if [i%-3&4:12&8-i%5] can be any shorter
although it does look pretty optimal
where did you steal find that from? @vestal solstice
https://docs.python.org/3.8/faq/programming.html#is-it-possible-to-write-obfuscated-one-liners-in-python I find it funny this is even a question in the FAQ
Don’t try this at home, kids!
anyone want to help me implement this py d = {'a': 100, 'b':200} a, b, c = d #a = 100, b = 200, c = None
def dict_iter(self):
iterator = iter(self.values())
while True:
yield next(iterator, None)
replace tp_iter with that
d = {'a': 100, 'b':200}
b, a, c = d #b = 100, a = 200, c = None```
or
d = {'a': 100, 'b':200}
b, a, c = d #a = 100, b = 200, c = None```
@grizzled cloak @brazen geyser the goal is to make it set vars with the same name as a key to the corresponding value
Oh snap
yea thats what i was about to try tbh
imo, a nicer way would be {'a': foo, 'b': bar} = {'a': 10, 'b': 20}; foo,bar==(10,20)
or py foo:'a', bar:'b' = {...}
eh first imma try to get the var names
also, couldnt you do sth like locals().update({varname: targetdict.get(varname) for varname in the_variables_assigned_t}) (probably not locals(), but you get the idea
yea
but if i can get the variables assigned to i can just build and return a list iterator that has all the vals in the right order
from . import _utils as utils
import inspect
import dis
@utils.edit(dict, 'tp_iter')
@utils.nullwrap
def dict_iter(self):
last_frame = inspect.currentframe().f_back
for instruction in dis.Bytecode(last_frame.f_code):
if instruction.opname in ['STORE_FAST', 'STORE_GLOBAL', 'STORE_NAME', 'STORE_DEREF']:
yield self.get(instruction.argval)
``` this mostly works
from py_future import expdict
>>> def func(**kwargs):
... opt1, opt2 = kwargs
... return opt1, opt2
...
>>> func(opt1=10, opt2=20, opt3=30)
(10, 20)
>>> ```
@rugged sparrow dont foget about f_lasti to get index of last instruction
for disambiguation purposes
Ah yeah you're right
Interesting hack: https://github.com/georgek42/inlinec
I like. It also links to an HTML variant that inspired it.
Is it possible to exec a string as code in f-strings?
!e ```py
a = 'print(1),"2"'
print(f"{exec(a)}")
@distant wave :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | None
?
I meant without using exec or eval
actually nvm
what builtins/dunders (if any) can be made using the characters lfisp_?
You can use the same character many times?
no builtins, apparently
>>> [name for name in dir(builtins) if all(char in set('lfisp_') for char in name)]
['_']
def PYTHON(PYTHON):
def PYTHON(*PYTHON):
return ''.join(*PYTHON)
return PYTHON
class PYTHON:
def __new__(PYTHON):
return PYTHON.PYTHON('PYTHON')
@PYTHON
def PYTHON(PYTHON):
return PYTHON
print(PYTHON())
the fuck
PYTHON!
this isnt a shitposting channel @chrome moth
No shit
wasnt sure you realized that
whats going on here?
I'm not sure I just posted some "General Pyhon weirdness" and got called a shit poster rofl, please correct me if this isn't the place to post such snippets.
half the stuff i've seen here could be construed as a shitpost
I was more thinking about why you would comment like that @pure dew. like, I do not see how useful your post is @chrome moth but i would not call it out
it's just dumb obfuscated code that serves no practical value but is fun to think about and read
like a lot of the on-topic content here
It's not functional at all
it prints "PYTHON"
it's late ya'llq imma go to bed so i wont be a grumpy bear
all good
@chrome moth that's why I avoid same variable names haha
dapper misreading the code is just more proof it belongs in this channel 😏
@glacial rampart i hope you realise that obfuscation and code gore are listed in the channel topic as well
:)
im so glad i switched to notepad as my editor, its clean white and black makes it so easy to see everything without all the colors confusing my eyes
@sick hound Yea that was my bad all around
What the actual f██k
from mrmister import code
code.is_confusing = True
no no, i think youre just tired or something, its pretty straight foward
it takes your name and makes you a new nickname
Oh, shut up. That thing is unreadable
othan than cases i think its pretty pythonic
Pythonic or not, its unreadable
i think thats a little harsh, as you can see by its file name, its perfect_code
no, objectively wrong, its the best way to write code, no confusing colors or indent lines
notepad is cool
and the perfect code is so simple, you give it your name and it give you the better name
BabBoop>>>MrMister
your name is MMurgle```
Notepad++ is good.
VSCode is better.
Notepad can burn in hell for programming
Like this?
yes exactly, im glad youve embraced the perfect code
Notepad can still burn
pft notepad > sublime > VSCode > Notepad++
Where notepad is worst and notepad ++ is best
not_correct = "pft notepad > sublime > VSCode > Notepad++"
correct = not_correct.replace(">", "is better than")
print (correct)
pft notepad is better than sublime is better than VSCode is better than Notepad++
.replace("VSCode", "VSCode is best")
you better be posting code soup
morse=lambda s,o=''.join:o(map(lambda c,i=lambda c,s,t:int(str(ord(c))[s:t]):{o('.-'[int(l)]for(l)in bin(i(a,2,9))[3:]):chr(i(a,0,2))for(a)in'ʏ᧠ᩆʴ᭪ᯊᰰ˞ᵙ᷄̉̒ừὖ῁‒͆͋͛↩∇≹⋟⍄ፓᎯᐏᑱᓔᕈᖴᘜᚂዿ'}.get(c,' '),s.split()))
``` @distant kite @next mist morse code decoder
yeah thats the one
i can find minesweeper one sec
[[[[[t.update(n=t['n']+b[i+x][j+y]['d'])for y in[-1,0,1]for x in[-1,0,1]if all(map(lambda v:v>=0and v<len(r),[i+x,j+y]))]for j,t in e(r)]for i,r in e(b)],f(b,0,0,8),[*iter(lambda h='\x1b[':all(all((t['d']&1and t['d']&2)or t['d']&4for t in r)for r in b)or[p(h+'2J'),[p('',*[h+f'{7if t["d"]&8else 0}m{t["n"]if t["d"]&4else"F"if t["d"]&2else"#"}{h}0m'for t in r])for r in b],p(f'\n{h}7mMove (wasd), Flag (f) or Clear (c):{h}0m '),[*[(lambda t,c,n:lambda:[f(b,*c,8),f(b,c[0]+n[0],c[1]+n[1],8)]if c[0]+n[0]>=0and c[0]+n[0]<len(b[0])and c[1]+n[1]>=0and c[1]+n[1]<len(b[0])else 0)(*g(b,e),n)for n in zip([-1,0,1,0],[0,-1,0,1])],lambda:f(b,*g(b,e)[1],2),lambda:exit('You Lose')if g(b,e)[0]['d']&1else f(b,*g(b,e)[1],4)if g(b,e)[0]['n']else r(b,f,r,*g(b,e)[1],[]),p]['wasdfc'.find(__import__('sys').stdin.read(1))]()][0],1)],exit('You win')]for e,p,b,f,g,r in[(enumerate,print,(lambda s:[[dict(d=__import__('random').choice([0]*s+[1]*(s//3)),n=0)for()in[()]*s]for()in[()]*s])((lambda i:int(i)if i.isnumeric()and int(i)>2else(exit('Invalid Size')))(input('Board Size (Min 3): '))),lambda b,x,y,v:b[x][y].update(d=b[x][y]['d']^v),lambda b,e:sorted([[(t,(i,j))for j,t in e(r)if t['d']&8]for i,r in e(b)])[-1][0],lambda b,f,r,i,j,l:[[[f(b,i+x,j+y,4),r(b,f,r,i+x,j+y,l+[(i+x,j+y)])if b[i+x][j+y]['n']==0and(i+x,j+y)not in l else 0]if not b[i+x][j+y]['d']&4and not b[i+x][j+y]['d']&1else 0]for y in[0,1,-1]for x in[0,1,-1]if all(map(lambda v:v>=0and v<len(b[0]),(i+x,j+y)))])]]``` @distant kite take a look
HOW IS THAT MINESWEEPER?!?!
its beautiful
nah its so hard to actually tell whats going on
i expected something pretty like a numpy array looking thing
not that...thing
i mean arnt most people
i mean it works in WSL
works on linux
windows console is yikes
put __import__('colorama').init() at the top of the file
@next mist ^
should make it work
Screenshot?
Try cmd
^
colorama should have fixed ittttt
eww, downloading stuff? thats work
suit yourself
i understand what its supposed to be haha
cmder is a much better console than cmd/pshell for all purposes
problem is windows removed some of the apis that colorama used in the newest couple updates
Then it's time to fire up a VM I guess
what
if you have a relatively new build of windows 10, you can enable the windows subsystem for linux (WSL) and download ubuntu directly in windows
Or just do that
you run it like you would powershell
yea wsl supports ansi
Quick question, could anyone look at my post in #303934982764625920? It's not really esoteric, but it's my first public project
Wsl has a seperate shell program
oh ah
@distant kite sure
thanks :)
Oh really? Honestly hadn’t looked much into it
windows console api is wack, who knows
Yeah, same as for openssh and things like that
i'll stick with stdout/stdin and good old \x1b[34m
It is the formatting character type of thing, isn't it?
ANSI escape sequences yea
Yeah, I tried that, it is kinda hard to deal with
And does it work on windows though?
Haha, it is special indeed
Time to fire up a VM now then?
if you want man
if not x == x:
print(1)
``` add code above this that creates the variable `x` so that this snippet runs. (no defining classes/no `type`)
good old banana
bingo
x = float('nan')
Stand by for a method without explicitly calling float
x = 1e309 - 1e309
(Might depend on your implementation. If it doesn't work add some zeroes)
!e ```py
a = [1, 2, 3, 4, 5, 6]
a.extend(a)
print(a)
def extend(dest, src):
for i in src:
dest.append(i)
#extend(a, a)
@distant wave :white_check_mark: Your eval job has completed with return code 0.
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]
!e
en = lambda x:list(enumerate(enumerate(enumerate(x))))
x = range(10)
print(en(en(en(en(en(en(en(x))))))))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
[(0, (0, (0, (0, (0, (0, (0, (0, (0, (0, (0, (0, (0, (0, (0, (0, (0, (0, (0, (0, (0, 0))))))))))))))))))))), (1, (1, (1, (1, (1, (1, (1, (1, (1, (1, (1, (1, (1, (1, (1, (1, (1, (1, (1, (1, (1, 1))))))))))))))))))))), (2, (2, (2, (2, (2, (2, (2, (2, (2, (2, (2, (2, (2, (2, (2, (2, (2, (2, (2, (2, (2, 2))))))))))))))))))))), (3, (3, (3, (3, (3, (3, (3, (3, (3, (3, (3, (3, (3, (3, (3, (3, (3, (3, (3, (3, (3, 3))))))))))))))))))))), (4, (4, (4, (4, (4, (4, (4, (4, (4, (4, (4, (4, (4, (4, (4, (4, (4, (4, (4, (4, (4, 4))))))))))))))))))))), (5, (5, (5, (5, (5, (5, (5, (5, (5, (5, (5, (5, (5, (5, (5, (5, (5, (5, (5, (5, (5, 5))))))))))))))))))))), (6, (6, (6, (6, (6, (6, (6, (6, (6, (6, (6, (6, (6, (6, (6, (6, (6, (6, (6, (6, (6, 6))))))))))))))))))))), (7, (7, (7, (7, (7, (7, (7, (7, (7, (7, (7, (7, (7, (7, (7, (7, (7, (7, (7, (7, (7, 7))))))))))))))))))))), (8, (8, (8, (8, (8, (8, (8, (8, (8, (8, (8, (8, (8, (8, (8, (8, (8, (8, (8, (8, (8, 8))))))))))))))))))))), (9, (9, (9, (9, (9, (9, (9,
... (truncated - too long)
Full output: too long to upload
that looks awesome on mobile
Hahah I though you were setting "en" to lambda and typehinting x as a list of enum hahah
Mobile formating suucks
yeah
I just used en so I didn't have to type enumerate 80k times
for all you non mobile users heres how it looks
@edgy kelp banana? 
Probably ba NaN a
Ahh haha
it looks different for me
What is all that white?
white theme >.>
Why do you have to do that to yourself?
because i like it
morse=lambda s:"".join(map(lambda c,i=lambda c,s,t:int(str(ord(c))[s:t]):{bin(i(a,2,9))[3:].translate(48*a+'.-'):chr(i(a,0,2))for(a)in'ʏ᧠ᩆʴ᭪ᯊᰰ˞ᵙ᷄̉̒ừὖ῁‒͆͋͛↩∇≹⋟⍄ፓᎯᐏᑱᓔᕈᖴᘜᚂዿ'}.get(c,' '),s.split()))
``` @proper vault got morse code translator shorter with `str.translate`
nice
the 48*a is padding for the translate table
wow lol
@brazen geyser any suggestions on golfing it even further?
will let you know if i do. my brain is fried atm
aight
I mean you could make morse m but u don't think that's what you were asking
yea
morse=lambda s:"".join(map(lambda c,i=lambda c,s,t:int(f'{ord(c)}'[s:t]):{bin(i(a,2,9))[3:].translate('.-'*25):chr(i(a,0,2))for(a)in'ʏ᧠ᩆʴ᭪ᯊᰰ˞ᵙ᷄̉̒ừὖ῁‒͆͋͛↩∇≹⋟⍄ፓᎯᐏᑱᓔᕈᖴᘜᚂዿ'}.get(c,' '),s.split()))
``` cut it down to 195
morse=lambda s:"".join(map(lambda c:{bin(int(str(ord(a))[:-2]))[3:].translate('.-'*25):chr(ord(a)%100)for(a)in'ڈǙॆ՟ࠜ̉ʦثࣨкͳƀϙۺңਜኍෟഘವዶᘗឨᡱᣌȵঢ੫Ӵčݎֿ'}.get(c,' '),s.split()))
``` new encoding method, got rid of `i` lambda
morse=lambda s:"".join({bin(a//100)[3:].translate('.-'*25):chr(a%100)for(a)in map(ord,'ڈǙॆ՟ࠜ̉ʦثࣨкͳƀϙۺңਜኍෟഘವዶᘗឨᡱᣌȵঢ੫Ӵčݎֿ')}.get(c,' ')for(c)in s.split())
``` even shorter (157) @proper vault
any ya'll seen CodeKlavier
it's not esoteric code per-se, but the goal is use a midi keyboard as a computer interface
what?
Right now it's like a midi player that you control with code using the midi player itself instead of a keyboard https://youtu.be/6QEhnffDlk8
The CodeKlavier is a system which enables a pianist to code through playing the piano as a performative experience. The CodeKlavier repurposes the traditional piano to serve as both a live coding interface and as a musical instrument. This is a performance of our "Hybrid"
T...
https://github.com/narcode/codeklavier and it's written in python
huh. neat
(lambda gd: print(gd.api.Editor().add_objects(*(gd.api.Object(target_group_id=n, x=30, y=n*30, duration=1).set_id('trigger:move').set_easing('easing:ease_in_out') for n in range(1, 101))).dump()))(__import__('gd'))``` I have added builder style for my library and did this for no reason
er_svar_riktig = lambda self, svar: svar == str(self.riktig_svar)
Inside of a class. TA is going to freak out but that's okay
__str__ = lambda self: f"\nSpørsmål:\n\n{self.sporsmaal}" + \
"".join(map(lambda t: f'\n\n{t[0]}:\t{t[1]}', enumerate(self.svaralt)))```
That thing is in production code?
I hope not lol
def pic_th():
global screenheight, screenwidth, res, drawfile
window = pyglet.window.Window(screenwidth, screenheight)
def init():
drawgif('sans.gif')
def drawimg(selected):
pyglet.resource.path = [res]
pyglet.resource.reindex()
bg = pyglet.resource.image('greenscreen.png')
bg.width, bg.height = screenwidth, screenheight
image = pyglet.resource.image(selected)
move = window.width - image.width
@window.event
def on_draw():
window.clear()
pyglet.gl.glEnable(pyglet.gl.GL_BLEND)
bg.blit(0, 0)
pyglet.gl.glBlendFunc(pyglet.gl.GL_SRC_ALPHA, pyglet.gl.GL_ONE_MINUS_SRC_ALPHA)
image.blit(0 + move, 0)
pyglet.app.exit()
def drawgif(selected):
pyglet.resource.path = [res]
pyglet.resource.reindex()
animation = pyglet.resource.animation(selected)
bg = pyglet.resource.image('greenscreen.png')
bg.width, bg.height = screenwidth, screenheight
sprite = pyglet.sprite.Sprite(img=animation)
move = window.width - sprite.width
sprite.x += move
@window.event
def on_draw():
window.clear()
pyglet.gl.glEnable(pyglet.gl.GL_BLEND)
bg.blit(0, 0)
pyglet.gl.glBlendFunc(pyglet.gl.GL_SRC_ALPHA, pyglet.gl.GL_ONE_MINUS_SRC_ALPHA)
sprite.draw()
pyglet.app.exit()
init()
while True:
time.sleep(1 / 600)
if drawfile:
if drawfile.endswith('.gif'):
drawgif(drawfile)
drawfile = ''
elif drawfile.endswith('.png'):
drawimg(drawfile)
drawfile = ''
pyglet.app.run()```
whats a short way to generate the string '0123' for f(4)?
something better than
''.join(map(str, range(n)))
because thats just asking to be shortened
ok i guess i should post the entire challenge,
a function that takes a string and a number and then replaces the first n letters of that string with 0-n
>>> f("Hello World", 4)
'0123o World'```
this is my shortest so far:
f=lambda s,n:''.join(map(str,range(n)))+s[n:]
what happens if you get numbers higher than 9?
@grizzled cloak if the function wont get numbers higher than nine, then this works py f=lambda s,n:'0123456789'[:n]+s[n:]
f=lambda s,n:('0123456789'*(n//10+1))[:n]+s[n:]
if you want the string to repeat for higher n?
tbh i have no idea haha it was someones question
hmm
f=lambda s,n:''.join(map(str,range(n)))+s[n:]```
Shorter by a tiny bit?
wait that's literally what leterax has lol
hehe
made a random generator...
import threading
import time
THREAD_AMOUNT = 2000
loaded = False
def b():
while not loaded: time.sleep(0.3)
print("1", end="0")
for thread in [threading.Thread(target=b) for _ in range(THREAD_AMOUNT)]:
thread.start()
loaded = True
@proper vault added a spacing arg to your shortened version of mine:
h = lambda n,s:{print((('*'+s*' ')*-~i).center(n*(s+1),' '))for i in range(n)}```
I had to, sorry
h = lambda n,s:{print((('*'+s*' ')*-~i).center(n*-~s,' '))for i in range(n)}
Saves 2, I loose () and replace +1
@edgy kelp ouch.
does anyone know a python bot scirpt that dms everyone in a server
This isn't the channel for that.
(lambda f: f(f))(lambda x: print(5 * 4), x)
``` Does this work?
That's my attempt at a Y combinator.
no that doesnt work
@hollow patrol you mean that?
>>> (lambda f: f(f))(lambda x: (print(5 * 4), x))
20
(None, <function <lambda> at 0x10eac7268>)```
@marsh void Right, yeah that doesn't work
(lambda f: f(f))(lambda x: print(5 * 4), x())
That?
In mathematics and computer science in general, a fixed point of a function is a value that is mapped to itself by the function. In combinatory logic for computer science, a fixed-point combinator (or fixpoint combinator) is a higher-order function
...
Y combinator is how you make recursion
even if the language forbids it or something
it is a specific way to create recursive functions, there are other ways
essentially, Y(f) beta reduces to f(Y(f)),
(lambda f: f(f))(lambda f: (input('test '), f(f))[0])``` that's inf recursion right
and what are we trying to achieve
in python, you really do not need a Y combinator
I'm just trying to achieve using an esoteric way for recursion
lakmatiol, that's why this is #esoteric-python
We do things that you don't need in Python
(lambda f: f(f))(lambda f: (print('test'), f(f)))
Yep
(lambda f: f(f))(lambda x: print(5 * 4), x(f))
I actually do have a use for lambdas
Not the single-expression ones, but more complex ones
(lambda f: f(f))((lambda x: print(5 * 4)), x(f))
lt.function(lambda v: print(5 * 4), v.__ref__())
yes
I actually use it a fair amount when I need complex logic in lambdas and a decorator won't work
What are you using lambdas for?
for everything
he's making lambdas like actual functions I'd say
so you can have loops etc
I see
what's lambdatools? can't find anything relevant on google
It's a small project I'm working on @lament ibex
It gives lambdas some abilities like async lambdas,recursion, conditionals, loops
Of course, most/all of these things can be done with extreme python hacks, but I find mine more readable
It's on my github
Sure
myfunction = function(lambda v: ( #define function as ANONYMOUS function set to variable myfunction
setattr(v, x = 0), #set x to 0
(yield from during(lambda v: v.x < 6, lambda v: ( #loop while x < 6 with a yield inside the loop
setattr(v, x = v.x + 1), #increment x by 1
(yield v.x) #yield x
)))
))
``` It makes lambdas less esoteric
(lambda x: x(int(__import__('sys').stdin.readline()).__rmul__(int(__import__('sys').stdin.readline()))))(lambda y: __import__('sys').stdout.write(y.__str__()).__str__()[:-1])
multiplies 2 numbers without using print nor input in 1 line
or *
just garbage
Someone made a program to multiply numbers using string manipulation.
^
Also, I made a version that didn't use string manipulation but allowed a few more operators than that and supported more types: https://discordapp.com/channels/267624335836053506/470884583684964352/548675000509530121
@tribal moon shorter: py (lambda r,w:w(int(r()).__rmul__(int(r()))))(*(lambda s:s.stdin.readline,s.stdout.write)(__import__("sys"))
Haha
radix_sort = lambda nums,base:(lambda n:(lambda f,*a:f(f,*a))(lambda f,nums,idx:f(f,sum([[num for num in nums if get_digit(num,idx,base)==digit]for digit in range(base)],[]),idx+1) if idx<n else nums,nums,0))(ceil(log(max(nums),base)))
what's the shortest way to get rid of the first occurunce of a specific number in a list?
remove?
>>> x = [1, 2, 3, 1, 2, 3, 3, 2, 1, 3, 2, 4, 1]
>>> x
[1, 2, 3, 1, 2, 3, 3, 2, 1, 3, 2, 4, 1]
>>> x.remove(2)
>>> x
[1, 3, 1, 2, 3, 3, 2, 1, 3, 2, 4, 1]```
no, it returns None
oh
you can do x.remove(a)or x
which will return x with the remove applied to it
but you need a named reference to the list
oh ok that will work, thanks 🙂
also I made this terrible thing to sort a list of unique numbers
f=lambda a,b=[]:(f({*a}-{min(a)},b+[min(a)])if len(a)else b)
hi
i want help with Microsft azure search
image and wb
I am clueless
If you know of guides/experience do let me know
@young wyvern not the right channel for that
this channel is for help with things like making 2 + 2 equal 5
>>> from ctypes import *
>>> cast(id(4), POINTER(c_int))[6] = 5
>>> 2 + 2
5```
5
and guess what 3 + 1 - 1 will be
>>> 3 + 1- 1
5
no, 5 still
4 - 1 is also 5
4 + 1 is 6
doing ~4 does weird things
Oh yeah, 5, it is just too late to do maths now 😄
overall, this seems to break ~ entirely
What is even ~? Is it some kind of binary inverter type of thing?
>>> ~4
-6
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: raw write() returned invalid length 5 (should have been between 0 and 4)
-6```
@proper vault is that overloaded when using with pandas? I just know that ~ negates a series of true/false
yep, you can overload it with __invert__
so the operator used in pandas has been overloaded - here i mean - it's acting in a way one might not expect given the outline of it in this thread
shortest way to flip a string of binary digits? (eg: "1000" -> "0111")
~str(int(s))
''.join('10'[int(e)] for e in s)
``` not sure how to use `~` here, as bin on negative numbers does not do 2s complement
I'm trying to make the shortest lambda to increment a binary string, without using bin, if anyone has any ideas
f=lambda x:(x[:x.rfind("0")]+"1")[::-1].zfill(len(x))[::-1]
I made this horrible thing but it doesn't work if the input is all 1's
(also .rpartition("0") might be useful but I can't work out how to use it
@gilded orchid you can subtract ord from 97
Not sure if it's short
Like it looks fine, just add 0 to x before doing rfind
>>> f=lambda x:(x[:("0"+x).rfind("0")]+"1")[::-1].zfill(len(x))[::-1]
>>> f("111")
'100'
Yeah :/
you could do sth like this
f=lambda x:(lambda a,b,c:a+'1'+'0'*len(c))(*x.rpartition('0'))
but that is quite long
f=lambda x:(a:=x.rpartition("0"))[0]+"1"+"0"*len(a[2])
ah, forgot about walrus
I wonder if there's a way to do it without walrus (somehow getting the number of 1's at the end of the string in a short way)
f=lambda x:x.rpartition("0")[0]+"1"+"0"*len(x.split("0")[-1])
I did it without walrus but it's longer
Rsplit?
wdym?
it would save a few in the lambda solution
i'm confused, how?
you could skip the b parameter, as rsplit('0',1) would only return 2 things
is there a way of overloading operators on functions?
You can create a function object that has its own operators
I think it's possible
Then call the object like a function
def function_with_overloaded_operators(fun: Callable, operations: Dict[str, Callable]):
return type('', (), {'__call__': lambda self, *a:fun(*a), **operations})()
``` sth like this perhaps
In [11]: super_print = function_with_overloaded_operators(print, {"__add__": lambda s,o: s(o)})
In [12]: super_print + "Hello World!"
Hello World!
could make it a decorator like so
def with_operators(**operations: Dict[str, Callable]):
def decorator(fun: Callable):
return type('', (), {'__call__': lambda self,*a: fun(*a), **operations})()
return decorator
ah, minor error I just noticed
In [11]: @with_operators(__add__=lambda s,o:s(o))
...: def a(o):
...: print(o)
...:
In [12]: a + 4
4
In [13]: a(4)
4
What's the shortest Hello World that doesn't use any ( or )?
import __hello__ maybe
That's a good one. There I was puzzling the best way to call functions.
!e python f=lambda _:"Hello world" @print @f class t:pass
@snow beacon :white_check_mark: Your eval job has completed with return code 0.
Hello world
No brackets.
@marsh void :white_check_mark: Your eval job has completed with return code 0.
<function f at 0x7f752375f1f0>
ah, makes sense
!pep 614
one can hope
!e ```py
d = lambda x:x
@print
@d(lambda val:'Hello World')
class a:pass
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
Hello World
that works
I was trying to avoid brackets.
fair
my hope is if that pep is implemented youd be able to just do @lambda: blahblah outright
same
A slightly golfed version of the unbracketed one:
f=lambda _:"Hello world"
@print
@f
class _:0```
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Hello world
I use ```python
Lines of code go here
You can omit the python on the first line if you don't care about syntax highlighting.
!e
import hello
@fallen heath :white_check_mark: Your eval job has completed with return code 0.
Hello world!
Do you need the codeblock?
No
!e import this
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | The Zen of Python, by Tim Peters
002 |
003 | Beautiful is better than ugly.
004 | Explicit is better than implicit.
005 | Simple is better than complex.
006 | Complex is better than complicated.
007 | Flat is better than nested.
008 | Sparse is better than dense.
009 | Readability counts.
010 | Special cases aren't special enough to break the rules.
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/atabekomuj
@thin trout :white_check_mark: Your eval job has completed with return code 0.
Hello world!
Class decorators are like function decorators.
They are just being called with a callback to the function or class as the first arg and assign the returned value to the global name of the function/class
In that case, @f makes _ equal to "Hello world" and then it is fed to print() through the @print decorator
_ ends up as None from the print.
Yeah because _ is the latest returned value in the repl
The decorator still assigns to it if it isn't in the repl.
!e
a = "Hello World!"
__import__(a[:len(dir(a)[~False])].lower().join([chr(len(dir(True))+len(dir(())+~False)*-~True]*-~True))```
@hot crypt :x: Your eval job has completed with return code 1.
001 | File "<string>", line 2
002 | SyntaxError: closing parenthesis ']' does not match opening parenthesis '('
ah mistyped
!e
a = "Hello World!"
__import__(a[:len(dir(a)[~False])].lower().join([chr(len(dir(True))+len(dir(()))+~False)*-~True]*-~True))```
@hot crypt :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | ModuleNotFoundError: No module named 'gghellogg'
can i run !e with py2.7? 😅
Nope :D
@gilded orchid @thin trout the f decorator is passed the class _ into it's only argument (and that isn't used) and returns the string 'Hello World'. This string is then passed to the print function (here used as a decorator because the syntax for decorators means the the return value/input to a decorator does not need to be a function. There only has to be a function at the innermost level)
Hey, I think I got it right haha
Without using numbers, is there a shorter way to obtain -1 other than ~False?
oh -True. welp
haha
im very new to golfing x)
I tried to code an esoteric hello world without numbers or strings other than "Hello World!", then golfed it.
The result looks like somebody with very poor logic skills attempted a hello world
a = "Hello World!"
b=True;c=-~b;d=chr((c+b<<c+c+b)-b)*c;__import__(d+a[:c+c+b].lower()+d)```
Sounds like an esoteric script haha
couldn't you just print("Hello World!")
__builtins__.__dict__.__getitem__.__call__('__import__').__getattribute__('__call__').__call__('__hello__')
Why did I laught to this
the last __call__ may be cheating
but whats the fun in that @sick hound
you could also change a to be "Hello <whatever>"
__builtins__.globals.__call__().__getitem__('__builtins__') @proper vault to stretch it a bit more
but then you use not __name__ things
ah true
__builtins__.__dict__.__getattribute__('__getitem__').__call__('__import__').__getattribute__('__call__').__call__('__hello__') is an option, but you can nest those indefinitely
exec("[0]"*2993) for the compiler
!e ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
@sick hound :x: Your eval job has completed with return code 1.
001 | s_push: parser stack overflow
002 | MemoryError
replacing exec with eval seems to move the recursions one step back
Python 3.8.1 (default, Feb 17 2020, 11:48:46)
[GCC 9.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
s_push: parser stack overflow
MemoryError```That's so dumb haha
!e exec('[0]'*2993)
@marsh void :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | RecursionError: maximum recursion depth exceeded during compilation
hahaha
interesting, ipython gives the proper error
wait wat
oh, nvm, just took a larger number ```py
In [23]: exec('[0]'*29993)
RecursionError Traceback (most recent call last)
<ipython-input-23-3e019763dfac> in <module>
----> 1 exec('[0]'*29993)
RecursionError: maximum recursion depth exceeded during compilation
mistyped and put one more number when trying to find the ipython ceiling on that and python just crashed
!e exec('[0]'*299993)
@proper vault :warning: Your eval job timed out or ran out of memory.
[No output]
wonder why this happens
!e
for i in range(2):
for func in exec, eval:
multiplier = 2993 + i
try:
func("[0]"*multiplier)
except RecursionError:
print(f"{func.__name__} failed with {multiplier=}")
except TypeError: pass
print()
@edgy kelp :white_check_mark: Your eval job has completed with return code 0.
001 | exec failed with multiplier=2993
002 |
003 | exec failed with multiplier=2994
004 | eval failed with multiplier=2994
or how rather
import ast;ast.parse("0,"*10000000000)
``` dont try at home
immediately tries at home
might as well tuple a range
@marsh void just tried with pegen, fails at the same position
for func in (extension.parse_string, compile):
x = 2992
try:
while True:
x += 1
func("[0]"*x)
except:
print(f"{func.__name__} failed at {x}")
parse_string failed at 2993
compile failed at 2993
It doesnt fail in the parser, it fails in the symboltable
construction
Is the second one faster than the first one or are these the same?
def a(x,y):
pass
def a(x: int, y:int) -> int:
pass
nvm turns out they're identical
isn't the latter one a negligible bit slower? @gilded orchid
it evaluates type annotations, idk
I'm pretty sure type annotations don't actually do anything
they are just helpful for stuff like automatic documentation
well
in 3.8 - their evaluation is postponed
it is not slower at all
at least, i'm 90% sure they aren't slower.
i mean, unless you consider the time taken to parse the extra tokens, but that's negligible.
3.8 will have broken one of my programs, it appears.
__import__('builtins', level=0).__dict__['print']('Time is: ',__import__('datetime').__dict__['datetime'].now().strftime('%I:%M'))
tells the time
Typehint are a bit slower because they are additional metadata to parse, store and load into memory, but that's almost nothing compared to the rest of the startup procedure, plus it doesn't cost anything at runtime, except for memory (iirc)
^
>>> import ctypes
>>> ctypes.c_longlong.from_address(id(4)+8).value=id(bool)
>>> 4
False
>>> 2 + 2
False```
>>> 4
False
>>> bool(4)
True```
what have we done
hahaha
!e
import ctypes
ctypes.c_longlong.from_address(id(True)+8).value = id(bool)
print(1)
@marsh void :white_check_mark: Your eval job has completed with return code 0.
1
!e
import ctypes
ctypes.c_longlong.from_address(id(True)+8).value = id(bool)
print(True)
@marsh void :white_check_mark: Your eval job has completed with return code 0.
True
okay
yeah makes sense
!e
import ctypes
ctypes.c_longlong.from_address(id(True)+8).value = id(int)
print(True)
@marsh void :white_check_mark: Your eval job has completed with return code 0.
1
alongisde token parsing, creating a temporary dictionary and mapping the arguments to annotations if you postpone the evaluation, there will be the cost of AST unparsing. Unparser itself written in C, so that won't affect much.
out of curiousity, what doesn't error, and makes this return false?
f=lambda x:type(x)(x)==x
object
In [100]: f=lambda x:type(x)(x)==x
In [101]: f(object)
Out[101]: False
and str/list/dict
essentially anything whose type is type
and type(x) != x
is there anything that works that isn't type? (or NaN)
yea, you can create a metaclass and override __call__ i guess
class A:
def __eq__(*a): return False
def __init__(self,*a): super().__init__()
an object defined like this, an empty numpy array (with a depracation warning, returns a falsey object)
okay so
I have seen a speech about messing with python's import and damn it was so fun
some_file.json
script.py```
```py
from magic_importer import some_file
print(some_file.data)``` and this will print contents of the file
wait how?
@rugged sparrow import hooks?
yep, import hooks
specifically, sys.meta_path iirc
!eval import sys; print(sys.meta_path)
@marsh void :white_check_mark: Your eval job has completed with return code 0.
[<class '_frozen_importlib.BuiltinImporter'>, <class '_frozen_importlib.FrozenImporter'>, <class '_frozen_importlib_external.PathFinder'>]
here
Just add your magical PathFinder and Loader there
>>> x = []
>>> for _ in range(10000):
... x = [x]
...
>>> x in x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RecursionError: maximum recursion depth exceeded in comparison```
RecursionErrors aren't pokemon
are you sure?
class INF:
__getitem__=lambda t,k:t.__dict__[k]if k in t.__dict__ else INF()
print(INF()[1]["DFNDJ"][2893297493847394873]["qqq"]["dfdfd"][22][1212])
It is not as cool as the other ones in here, but still I thought was decent!
Actually, just realized that there was no point in t.__dict__ anyway, woops
Reminds me of flail.
Fuck
I cant format it as code
(lambda h,t,w,o:((lambda f:(lambda x:x(x))(lambda y:f(lambda *args:y(y)(*args))))(lambda l:(lambda x:(lambda x:l(x))((lambda a,b,xpt,ypt:str(h.__getitem__(ypt).__setitem__(xpt,(((h.__getitem__(ypt).__getitem__(xpt)!="E")+1)%2)*o[t[0]%2]+(((h.__getitem__(ypt).__getitem__(xpt)!=o[(t[0]+1)%2])+1)%2)*o[(t[0]+1)%2]+(((h.__getitem__(ypt).__getitem__(xpt)!=o[(t[0])%2])+1)%2)*o[(t[0])%2]))+0*str(t.__setitem__(0,t.__getitem__(0)+1)))(print("Player "+o[t[0]%2]+" playing."),str(print("\n\t0\t1\t2\t\n\n0\t"+h[0][0]+"\t"+h[0][1]+"\t"+h[0][2]+"\t"+"\n\n1\t"+h[1][0]+"\t"+h[1][1]+"\t"+h[1][2]+"\t"+"\n\n2\t"+h[2][0]+"\t"+h[2][1]+"\t"+h[2][2]+"\t\n")),int(input("Enter the x coordinate of your selection: ")),int(input("Enter the y coordinate of your selection: ")))) if (lambda x:True)(print((o[(t[0]+1)%2]+" won!")*w(h,o[(t[0]+1)%2]))) and (lambda x:True)(print(("\n\t0\t1\t2\t\n\n0\t"+h[0][0]+"\t"+h[0][1]+"\t"+h[0][2]+"\t"+"\n\n1\t"+h[1][0]+"\t"+h[1][1]+"\t"+h[1][2]+"\t"+"\n\n2\t"+h[2][0]+"\t"+h[2][1]+"\t"+h[2][2]+"\t\n")*w(h,o[(t[0]+1)%2]))) and w(h,o[(t[0]+1)%2])==0 and t[0]<9 else None)))("c"))([["E","E","E"],["E","E","E"],["E","E","E"]],[0],(lambda b,p:(((b[0][0]==p)+(b[0][1]==p)+(b[0][2]==p))==3)+(((b[1][0]==p)+(b[1][1]==p)+(b[1][2]==p))==3)+(((b[2][0]==p)+(b[2][1]==p)+(b[2][2]==p))==3)+(((b[0][0]==p)+(b[1][0]==p)+(b[2][0]==p))==3)+(((b[0][1]==p)+(b[1][1]==p)+(b[2][1]==p))==3)+(((b[0][2]==p)+(b[1][2]==p)+(b[2][2]==p))==3)+(((b[0][0]==p)+(b[1][1]==p)+(b[2][2]==p))==3)+(((b[0][2]==p)+(b[1][1]==p)+(b[2][0]==p))==3)),["X","O"])
There
yeah, by one-linerizer
Aaah
is this tictactoe
yes
Oh God
^ #esoteric-python in a nutshell
from itertools import*;m,p,q,r,s,l,a=dict(enumerate("276951438")),[[],[]],0,print,' │ │ ','─┼─┼─','XO';b=[*map(list,[s,l,s,l,s])];f=lambda:r('\n'.join(map(''.join,b)));f()
while m:
i=int(input(a[q]+' move: '))-1;p[q]+=[int(m.pop(i))];b[~(i//3*2)][i%3*2]=a[q];f()
if any(sum(d)==15for d in combinations(p[q],3)):r(a[q]+' wins');break
q^=1
else:r('Draw')
i like this one better
That is much nicer
https://github.com/salt-die/golfs/blob/master/tictactoe.py -- three in a row is checked with a magic square
Haha, that's genius. I love it.
@zealous widget does it verify input tho?
Oh I was looking at the embed, links in discord have always been wonky for me
i remember when i made tictactoe in a 400MB python script.
the interpreter segfaulted once it reached like 50 GB of memory usage (i put a lot of swap towards it because otherwise memory errors would come first :D)
that was just for parsing the script
it never actually ran
@proper vault :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
yes but that's just a memory error
i got a straight up segfault
and i couldn't upload it to github because 100MB is their file limit. so sad.
gitlab can do it though, i think
It might have been a segfault due to you having a collections past ssize_t
i mean, it didn't even finish parsing/compiling the code, so it's not my fault!! :D
try pypy
well i don't even have the code any more so i'm gonna recreate it
!e
print("wow, working?")
@eager depot :white_check_mark: Your eval job has completed with return code 0.
wow, working?
there is #bot-commands for random tests
@warm gate :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | RecursionError: maximum recursion depth exceeded during compilation
hehe
Imagine all the people here doing something productive. That would be amazing. 😝
Ok i have a challenge for all of you guys
Use aiohttp to get the contents of a webpage in 2 lines
And print it
echo "await (await __import__('aiohttp').client.ClientSession().get('http://example.org')).text()" | python3.8 -m asyncio ? Bit of a weird request
!e
s="eval(s)"
eval(s)
!e
s="eval(s)"
eval(s)
@wispy horizon :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | File "<string>", line 1, in <module>
004 | File "<string>", line 1, in <module>
005 | File "<string>", line 1, in <module>
006 | [Previous line repeated 496 more times]
007 | RecursionError: maximum recursion depth exceeded during compilation

lul
hahaha
okay so I am doing this
# coding: not_python
def func() -> None {
print(13);
}```
don't ask haha
@marsh void it would be super cool to use this with from __future__ import braces
@marsh void how does that work?
# coding: something can be hooked (site module) to define new "encoding" in order to access the code before runtime
then I run some shitty re/parsing on the code
@sick hound as funny as it sounds, I am 90% sure I can do that
You would just have to import one small module before that
Oh wait, I can't do that, haha
Since I need to access everything before runtime
my dumb
well actually you can
(just a guess) you can create a pth file to load your custom module which will just replace the decoder method of the default encoding instead of registering an encoding
so user doesn't need to specify # coding etc
while you are decoding you can just compare iterate through tokens and when you see first from token just take a peek ahead, and compare the second value is a __future__ import and then do some transformations
if there is not any future imports, you can just use backuped decode version of the original decoder
are you doing something like inlinec?
@marsh void what in the site module do you use to hook into encodings?
It’s not that
- This module is automatically imported during initialization. *
(site)
And basically that fact allows you to hook encodings
That’s what I meant
oh ok
I am going to try and make some simple example
Can someone inspect if this is CPython impl detail, though?
I guess it depends how you are hooking into the site?
AFAIK pth files are specific to CPython, and they will be removed soonish.
oh no
this is so sad
# coding: pyxl
html = <html><body>Inline HTML!</body></html>
print(html)``` we can even do this now
oh god
^ #esoteric-python in a nutshell 2