#esoteric-python
1 messages · Page 82 of 1
yeah it's cool
it's just something you'd never see in a million years outside of #esoteric-python
I'm kinda curious how the hooking into encoding works
does it just give the source code and you can do whatever you want to it before it's ran?
@marsh void how does that work?
okay great but how does that work? :D
well it hooks custom encoding through site module which is imported on initialization
import codecs
def search_function(encoding):
if encoding != 'pyxl': return None
import encodings
from pyxl.codec.transform import pyxl_decode, PyxlIncrementalDecoder, PyxlStreamReader
# Assume utf8 encoding
utf8=encodings.search_function('utf8')
return codecs.CodecInfo(
name = 'pyxl',
encode = utf8.encode,
decode = pyxl_decode,
incrementalencoder = utf8.incrementalencoder,
incrementaldecoder = PyxlIncrementalDecoder,
streamreader = PyxlStreamReader,
streamwriter = utf8.streamwriter)
codecs.register(search_function)``` here's how pyxl.codec.register looks
then, after installing, it writes a pyxl.pth file into python's source with the following content: py import pyxl.codec.register
@brisk zenith
Yet I smell PEP8 violation here with the keyword argument style haha
Wait if I want {}; python I'll have to rewrite the tokenizer right haha
@gilded orchid hey, sorry for the late response, you can look above and at the source of pyxl_decode function on GitHub for further explanation.
Also if you dont want to mess with hooking things etc., BRM provides the same functionality with an IMHO better API
k = lambda: (
print('line 1'),
print('line 2'),
print('line 3'),
)
doesn't have to be a tuple either, you can use parentheses to split just about any expression into multiple lines
lambda x, y, z: (
3*x + 7*y +
8*z**3
)
even strings can be implicitly concatenated across multiple lines
lambda name, age, place: (
f'Hello, my name is {name}. '
f'I am {age} years old. '
f'I am from {place}.'
)
@brazen geyser what if I want a try/except or some understandable while/for
what's that meta anagram thing tho haha
@marsh void that stuff requires some boilerplate but its still do-able
nahh
I want normal multi line lambdas haha
Lambda is by definition a function without a name technically
_while=lambda f:[*iter(f,())]```
runs f until it returns ()
_try=lambda t,a=(),k={},f=lambda a:a,e=(Exception,),r={}:r.get('r',type('',(__import__('contextlib').ContextDecorator,),{'__enter__':r.clear,'__exit__':lambda s,*a:issubclass(a[0]or map,e)and[r.update(r=f(a))]})()(t)(*a,**k))``` my try lambda pattern
but why
could use those to have fully functioning mulitline lambdas with all features you want
I am writing my own python and rust-inspired language btw
which translates to python
lambda a: int, b: int -> {a + b}``` here's kind of syntax I have in mind
hmm
i wonder if i might be able to get something similar in normal python
like lambda a, b:0 > 'code'
I mean
or i just hook the compiler using a .pth
lambda (string: str, x: int) -> {
string *= x;
return string;
}``` it's actually this
that's why I am making my thing
it's going to be some smart def function when transpiled though
neat
Λ
λ
(string: str, x: int) -> {
// return string copied <x> times
return string * x;
}``` how about just this
λ
what I am creating is pretty much python + rust but works like python haha
@rugged sparrow actually, I’ll probably just construct FunctionType(...) during compilation lol
makes sense lol
hey there, I'm doin this just for fun..
Would there be a way to condense it into even lesser number of lines? It's 5 lines atm
medals = input().split()[:-1][::-1]
num = list(map(int,input().split()))
for i in range(0, len(medals), num[0]):
num.extend(medals[i:i+num[0]][::-1])
print(*num[1:])
where my input is like so:
10 20 30 40 50 60 -1
3
And my output after some processing is:
40 50 60 10 20 30
and the processing that happens btw is that,
So my 1st line of input is the well, list. (And the -1 at the end is just useless so that has to be popped)
The second line is say some number x.
So like I have to start from the end of my input list, print the last x numbers, then move behind further, on and on
why is the num read as a list?
cuz at the end I'm doing *num[1:]
Like, I read it as int before but my program was
more than 5 lines with that
oh
can do [medal for i in range(0, len(medals), num[0]) for medal in medals[i:i+num[0]][::-1]] for the loop as the simplest thing
is the length of medals guaranteed to be a multiple of num
yes, it's guaranteed
@edgy kelp so this
medals = input().split()[:-1][::-1]
num = list(map(int,input().split()))
print(*[medal for i in range(0, len(medals), num[0]) for medal in medals[i:i+num[0]][::-1]])
that's 3 lines
great
is this the best we can go? There's no way btw where input and printing can take place all in the same line yeah?
print(*(elem for chunk in zip([[*map(int, input().split())][:1][::-1]]*int(input())) for elem in chunk))
I'm thinking the 2 lines of input could somehow be reduced to 1
this seems to work
wait,
it is quite hacky, but it does indeed work
what output did you get?
getting the same as thejester
ah, found the error
print(*(elem for chunk in zip(*[[map(int, input().split())][:1][::-1]]*int(input())) for elem in chunk))
``` forgot to save
isn't that pycharm?
it is
I still get
uhm
this
<map object at 0x7f8acae2c7f0> <map object at 0x7f8acae2c7f0> <map object at 0x7f8acae2c7f0>
as output
where are you saving or runing the old thing then (or wrong run config set? )
oh, nvm, I had the wrong file running
lak, not you. Just curious about the saving because pycharm autosaves
ye, I did not forget to save, I just ran a wrong scratch file
no, my code does not work
print(*(elem for chunk in [*zip(*[iter([*map(int, input().split())][:-1])]*int(input()))][::-1] for elem in chunk))
``` this seems to finally work
ah yes
could you also explain how that works 😅 so I could write some magic like that myself in the future
it uses the zip(*[iter(var)]*n) trick, which lets you do this
!e
var = range(12)
n = 4
print(*zip(*[iter(var)]*n))
@proper vault :white_check_mark: Your eval job has completed with return code 0.
(0, 1, 2, 3) (4, 5, 6, 7) (8, 9, 10, 11)
and then prints those out in reverse order, flattened
well
how did you compress the two lines of input into 1,
er wait I get that actually
you just call input() in 2 different places. In most cases, the left side of a binary operator is evaluated first, so e.g.
!e
(print("Hi"),1)[1] * (print("Bye"),1)[1]
@proper vault :white_check_mark: Your eval job has completed with return code 0.
001 | Hi
002 | Bye
will always print those in that order
(at least I think so, someone correct me if I am wrong)
which is why it should never happen that input() happen in the wrong order
if you do need them in some less convenient order
you can do
(lambda n,l: rest_of_code)(input(), map(int, input().split()))
``` which is guaranteed to evaluate from left to right
(print("Hi"),1)[1]
what's the [1] for? and why do you have the 1 in the tuple too?
so that the * would not error
oh right
I just make a tuple of print("Hi"), 1, select the 1 and multiply it with another one from another tuple
another way to do it is using or
!e
(print(1)or 1) * (print(2)or 2)
@proper vault :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 2
(print(1) or 1)? lol what that mean
!e
print(1 or 2, 0 or 1, None or 1, type or False, False or 88)
@proper vault :white_check_mark: Your eval job has completed with return code 0.
1 1 1 <class 'type'> 88
wow it could compare type with False
!e
import time
print(20 or this_variable_is_not_defined, 20 or quit(), 20 or time.sleep(10))
print('no sleep')
@proper vault :white_check_mark: Your eval job has completed with return code 0.
001 | 20 20 20
002 | no sleep
or in python checks if the first operand is truthy, and if it is, it results in it, completely ignoring the other one. If it is falsey, it just returns the other one without checking it
I see, I wonder
!e
print(class or type)
class is a keyword, not a value
yep, type is value
!e
print(type)
@cursive plover :white_check_mark: Your eval job has completed with return code 0.
<class 'type'>
@cursive plover :white_check_mark: Your eval job has completed with return code 0.
<class 'type'>
type is an instance of type
metaclasses in python are a thing
which lets you do
!e
print(type("", (), {"__str__": lambda *_: "totally a real class promise"})())
@proper vault :white_check_mark: Your eval job has completed with return code 0.
totally a real class promise
oh wow, I've never heard about metaclasses before so I'll be sure to read up on that, and look at that code again
about the original code, it was this
print(*(elem for chunk in [*zip(*[iter([*map(int, input().split())][:-1])]*int(input()))][::-1] for elem in chunk))
So
[*zip(*[iter([*map(int, input().split())][:-1])]*int(input()))][::-1]
gave us the
uhm, [ [40,50,60], [10,20,30] ]
yep
now you did elem for chunk in [ [40,50,60], [10,20,30] ] for elem in chunk
except the inner ones are tuples, but that is not relevant
yep, you can nest list comprehension
oh right, you take each element, and form a new list of all such individual elements
and then you have a print(*(new list formed))
yep
right, this zip(iter()) thing is something I've never seen before, thank you
is there a place where you can hone your golfing skills or something? I don't think I can just think of such magic thingies by myself
here tbh
just like, hang around and you find some truly cursed things
yeah, that's true too
also, clash of code has shortest mode
so there's no like, place or book or smth that actually talks about this in detail right?
sec lemme look up what's clash of code
ah, okay, fewer chars
is there something for trying to put code into baar?
like, I've been trying to do one-liners for problems in the recent past, guess golfing isn't really the right word for that like you pointed out
also, that website doesn't open for me, is it just me or is the link broken?
Mm, also thank you once again. I learnt quite a lot !
In [83]: type(Ellipsis)
Out[83]: ellipsis
``` interesting
!e
e = ...
print(e, type(e), type(e)())
@marsh void :white_check_mark: Your eval job has completed with return code 0.
Ellipsis <class 'ellipsis'> Ellipsis
@proper vault soo? ¯_(ツ)_/¯
@marsh void I think Ellipsis is a Singleton too
Yeah it is
I'm pretty sure you can find a way to import the same module twice and make two different objects
The import machinery lets you just... create modules. Sure, regular imports are cached, but modules are by no means singletons
hmhmhm. has this channel produced ever anything tangibly useful? 
this stuff makes me feel warm and fuzzy inside
hmm is there some nifty way to implement in basic python the prod function just like sum?
from math import prod
in python 3.8 I guess?
ye
there's always reduce and operator.mul
ye, that is a nice one
I hacked it together with those but I was wondering to get it to work on lists somehow nicely
from functools import reduce
from operator import mul
reduce(mul, [1,2,3,4])
that's as close as I got too
what is this thing lacking?
it pretty much is. You can also give it an initial value arg, except even better, because it does not assume 0 by default
okay hmm
prod = lambda xs: xs[0] if len(xs) == 1 else xs[0]*prod(xs[1:])
prods.append(prod(chunk))```
it's not pretty but
now it works like the sum
no need for any imports
def prod(xs):
it = iter(xs)
val = next(it)
for n in it:
val *= n
return val
that's hurting my brain. what is val pointing to?
it's not changing when it changes I suppose
but it gets reassigned when it gets multiplied everytime by n?
ok yeah the return makes more sense
val is the first element of the iterable
so that it works for multiplying things that do not have 1 as an interoperable element
i was thinking you're accumulating the answer into the xs or something
like it was a cumulative product of some kind
where the values of the array get reassigned by the product so far
def prod(iterable):
value = 1
for n in iterable:
value *= n
return value```
sorry, I just un-esoteric-ed it
that assumes 1 * x == x, which is not guaranteed
def prod(iterable, start=None):
if start is None:
start, *iterable = iterable
for n in iterable:
start *= n
return start
to be pedantic, memory inefficient if you pass a generator and no start
that's true, you can just next it
*= is technically also different from *
yep, in this case you do want *= though
that assumes
1 * x == x, which is not guaranteed
@proper vault as an algebra fanboy, highly agreed
You do? You'd want your prod function to mutate your start object?
def prod(iterable, start=None):
iterable = iter(iterable)
if start is None:
start = next(iterable)
for n in iterable:
start *= n
return start
oh, ye, in salts case no, in the one I had, ye
but honestly, even then it would be fine
you generally pass a literal for start
literal was a bad term, I meant more inline object
essentially sth you do not have a named reference to
@proper vault when would 1 * x != x?
when you use an object with custom __mul__
ah
if x was a deck of cards and if you ever multiply a deck of cards it shuffles it or something
:D?
Very dank
tbh, I can think of no case where x * 1 != x would make sense
mostly in cases where it isn't defined
In [30]: class permutation:
...: def __init__(self, *seq):
...: if not all(i in seq for i in range(len(seq))):
...: raise ValueError("Not a proper permutation.")
...: self.seq = seq
...:
...: def __mul__(self, other):
...: if not isinstance(other, permutation):
...: raise TypeError("Not a permutation.")
...: if not len(other) == len(self):
...: raise ValueError("Length mismatch.")
...: return permutation(*(self.seq[i] for i in other.seq))
...:
...: def __len__(self):
...: return len(self.seq)
...:
...: def __repr__(self):
...: return f"permutation({', '.join(str(i) for i in self.seq)})"
...:
...:
In [31]: a = permutation(0, 4, 2, 1, 3)
In [32]: b = permutation(3, 1, 4, 2, 0)
In [33]: a * b
Out[33]: permutation(1, 4, 3, 2, 0)
I don't think it would make sense here, for instance.
Anyone know how I would make this code make as least a sense as possible so people wouldn't know to remove it. Trying to add a secret message into my program as people have been selling it.
import codecs
import base64
import sys
fortnite_ios_token = "R3V2ZiBvYmcgdmYgc2Vyci4gdnMgbGJoIGNudnEgc2JlIHZnLCBsYmgganJlciBmcG56enJxLg=="
sys.stdout.write(codecs.decode(base64.b64decode(fortnite_ios_token).decode(), 'rot_13') + '\n')
Probably not.
Made this thing a bit ago that encodes text to a string of zero width spaces https://paste.fuelrats.com/iqunayowem.py, if they don't know python it should be less obvious than a bunch of lambdas or something
the first bunch of functions are faster but result in a lot longer strings
i would recommend obfuscating that in with the rest of the program too and making sure the boundary is unclear
however much you obfuscate that bit of code, if someone can just see the obfuscated bit and get rid of it you've failed
@scarlet scroll What is the token for?
there will still be a clear difference between that code and normal code, so unless you plan on obfuscating it all or making the source unavailable t'll still probably be fairly easy even with trial and error
This bot is free. if you paid for it, you were scammed.
if you decode the base64 you get Guvf obg vf serr. vs lbh cnvq sbe vg, lbh jrer fpnzzrq., and then you un-rot13 that and you get that
i was gonna write the crazy thing for compiling a python codebase to bytecode and writing a codec register to execute it on load, but python already does that
so i guess all i'm writing is a nifty in-place bytecode compiler
when you use an object with custom
__mul__
@proper vault
erm, could you also give an example?
class Lol:
def __rmul__(self, other):
exit()
1 * Lol()``` @cursive plover
oh so that does 1 * exit() and thus exits, ah
>>> class Safe:
... def __init__(self):
... if __import__('random').randint(0, 1):
... __import__('ctypes').string_at(0)
...
>>> Safe()
<__main__.Safe object at 0x7f0db2ab1e90>
>>> Safe()
Segmentation fault (core dumped)
segfault roulette. I have no idea why I thought of this or wrote it.
haha
import ctypes
import random
class MaybeSafe:
def __init__(self) -> None:
if random.randint(0, 1):
ctypes.string_at(0)
```  pep8
pep8 bad
pep8 nice
What is that cool trick where you can split a string into several parts of size n, for example 'abcdefghi' with part size of 3 would return ['abc', 'def', 'ghi']
zip(*[iter(string)]*size)
technically not what you asked because it doesn't work on strings
without join
Ahh, that's what I was thinking of. Thank you.
I think it's called chunking.
print(*__import__("itertools").zip_longest(*[iter("ABCDEFGH")]*3, fillvalue=None))
hey, do you guys have some weird way to delete all files in a windows pc ?
trying to show some friend why he shouldn't be copypasting code without knowing how it works
you can just turn it off
(didn't intent to run it tho), kind of curious about how you can camouflage code
a puzzle for y'all:
$ python3 -ic 'url = "http://httpbin.org/status/402"'
>>> del __builtins__.__import__
>>> # your code here
...
>>> requests.get(url).text
'F**k you, pay me!'
Borrowed from https://sopython.com/wiki/Riddles#1-3
is this cheating? ```py
del builtins.import
class Lol:
... def getattr(self, attr):
... return self
... def call(self, *args):
... return self
... def repr(self):
... return "'Fk you, pay me!'"
...
requests = Lol()
requests.get(url).text
'Fk you, pay me!'```
yeah, sorry. You're supposed to actually import requests
spec = __loader__.find_spec("builtins")
m = __loader__.create_module(spec)
requests = m.__import__("requests")
Create module is the piece I was missing
@whole kiln Nice!
You may be interested in level 2 ;) https://sopython.com/wiki/Riddles#1-4
...never mind, your solution works for that one. Level 3, then. https://sopython.com/wiki/Riddles#1-5
fair warning: I spent like 4 hours on that one
come on, that's easy
seems like you get left with an unremovable __builtins__ dict
>>> del __builtins__.__import__, __builtins__
>>> sys = ().__class__.__base__.__subclasses__()[64].acquire.__globals__['sys']
>>> __builtins__ = sys.modules['builtins']
>>> spec = __loader__.find_spec('builtins')
>>> m = __loader__.create_module(spec)
>>> requests = m.__import__('requests')```
on different versions of python that 64 might change to something like 80
but same idea
@vestal quail that wasn't very hard :P
huh. Not bad, not bad at all
glad you're enjoying the puzzles (:
you can do pretty much anything after getting to object which is always accessible from constants
well if it can be any error other than a SyntaxError, (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( would do the trick since it stack overflows the parser and raises a MemoryError
6 seems like a good case for the compiler recursion errors 😄
@vestal quail Well it only took me 30 seconds to realise builtins is available in locals()
And then it's basically the same solution as before
... or just use a tab to have it more convenient in the console and get a TabError
Wait, you can access locals() after running globals().clear()?
Yes
that throws a NameError on my machine
Worked for me
>>> globals().clear()
>>> locals()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'locals' is not defined
number 10 is easy, ||object.__new__(Bomb)||
>>> globals().clear()
>>> globals().keys()
dict_keys(['__builtins__'])
``` I have this neat thing
not using CPython I guess?
for 11, is ||__import__('__main__').__dict__.__delitem__('x')|| considered cheating?
aww :(
@proper vault Are you also using 3.8?
ye
that explains why locals is still accessible, then
also i have a self-containing tuple ```py
t
((...),)
t[0] is t
True```
dude, how
>>> import ctypes
>>> t = 0,
>>> ctypes.c_longlong.from_address(id(t)+24).value = id(t)
>>> t
((...),)```
smart
Thanks, I'm gonna post that solution if you don't mind
You guys are on a roll, so maybe someone wants to help us figure out #22
actually i do mind, a proper solution would fix the reference counts
since otherwise if you removed the reference to that tuple, it would probably end up with a reference count of -1 which is not good
and you might also break 0's reference count, not that it would particularly matter
lots of these puzzles have side effects that are not good hahaha
well yeah but ```py
import ctypes
x = id((1, 2, 3))
x = ctypes.cast(x, ctypes.py_object).value
x
(((((((((((((((((((((((((((((<NULL>, (<class '_ctypes.Structure'>,), {(<class 'ctypes.c_long'>, (), 1): <class 'ctypes.CFUNCTYPE.<locals>.CFunctionType'>}), 'BigEndianStructure', <class '_ctypes.Structure'>), None, None), (<class '_ctypes.PyCFuncPtr'>,), {((((((((<NULL>, <class 'ctypes._endian.BigEndianStructure'>), <class 'ctypes.CFUNCTYPE.<locals>.CFunctionType'>), 1), None), 'ctypes'), 'cast'), 'x'), None): 0}), 'CFunctionType', <class '_ctypes.PyCFuncPtr'>), (), 1), 'This class represents a dll exporting functions using the\n Windows stdcall calling convention, and returning HRESULT.\n HRESULT error values are automatically raised as OSError\n exceptions.\n ', None), 'l', None), 'This class represents a dll exporting functions using the\n Windows stdcall calling convention.\n ', None), 'This class represents the Python library itself. It allows\n accessing Python API functions. The GIL is not released, and\n Python exceptions are handled correctly.\n ', None), 'u', None), 'pointer', '_pointer_type_cache'), '?', None), 'P', None), 'c', None), 'b', None), 'B', None), 'Q', None), 'q', None), 'g', None), 'd', None), 'f', None), 'I', None), 'i', None), 'L', None), 'l', None), None, None), None, None), 2571192850400, <class 'ctypes.py_object'>)```
0 is interned anyway, so shouldn't be a problem
>>> import ctypes
>>> x = id((1, 2, 3, 4, 5))
>>> x = ctypes.cast(x, ctypes.py_object).value
>>> x
('ctypes', 'cast', 'x', 'py_object', 'value')``` how did *that* happen??
shrug
if you mess up your reference counting, this kind of stuff happens ```py
import ctypes
x = id((1, 2, 3, 4, 5, 6))
x = ctypes.cast(x, ctypes.py_object).value
x
(((((<NULL>, 'module', 'qualname', 'doc', 'slots', 'swappedbytes'), 'module', 'qualname', 'doc', 'slots', 'swappedbytes'), 'module', 'qualname', 'type', '_check_HRESULT', 'check_retval'), 'module', 'qualname', 'doc', '_FUNCFLAG_STDCALL', 'func_flags'), 2, 3, 4, 5, 6)```
oh hey look this tuple contains itself ```py
x
((((((...), 'module', 'qualname', 'doc', 'slots', 'swappedbytes'), 'module', 'qualname', 'doc', 'slots', 'swappedbytes'), 'module', 'qualname', 'type', '_check_HRESULT', 'check_retval'), 'module', 'qualname', 'doc', '_FUNCFLAG_STDCALL', 'func_flags'), 2, 3, 4, 5, 6)```
what ```py
x
(((...), 'module', 'qualname', 'doc', ''\'\\\'\\\\, 'func_flags'), 2, 3, 4, 5, 6)```
>>> x
(((...), '__module__', '__qualname__', '__doc__', "((...), \\\\\\\\\\\\'\\\\\\", '_func_flags_'), 2, 3, 4, 5, 6)```
ok it seems like it's staying at that
you can post it as a partial solution if you want to, just keep in mind that you might get some nonsense tuple out if you mess around with the resulting self-containing tuple enough
I recently shared my pepgrave project here, this morning I wrote something about how it works. https://isidentical.com/blogs/pepgrave.html
!e
__import__('ctypes').string_at(0)
@proper vault :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
33
third of the things here are segfaults 😄
!e
__import__('ctypes').wstring_at(0)
@proper vault :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
@sick hound :x: Your eval job has completed with return code 139 (SIGSEGV).
001 | Fatal Python error: Cannot recover from stack overflow.
002 | Python runtime state: initialized
003 |
004 | Current thread 0x00007f6d2563a740 (most recent call first):
005 | File "<string>", line 2 in f
006 | File "<string>", line 2 in f
007 | File "<string>", line 2 in f
008 | File "<string>", line 2 in f
009 | File "<string>", line 2 in f
010 | File "<string>", line 2 in f
011 | File "<string>", line 2 in f
... (truncated - too many lines)
Full output: too long to upload
@sick hound :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
ye, pretty much any ctypes pointer set at 0 will segfault
looks like the above doesn't work on win
challange: segfault python without any imports / external modules. Only with the builtin object and syntaxes (importing any extension module is forbidden)
from ctypes import*;string_at(0) is 32
if you find such a case, you can report it to the upstream btw
just refuses the access with OSError
Try doing it with something that doesn't include string in the function name
@sick hound py def f(): try:f() except:f() f() i don't know if this is exactly a segfault but...
this is not a segfault
is this a segfault?
@sick hound
if you're wondering what on earth i did, it jumps forward 2,164,260,863 opcodes, which (as you might expect) breaks something
i didn't import anything or use any external modules, just some internal cpython madness
that is cool
not worth to report though
btw in 3.8 you can use .replace method of codetype
import inspect
f=lambda:eval(inspect.getsource(f)[2:])()
terrible way of hitting the recursion limit
a,b=[input()],-1
while a[b]!=a[b][::b]:a+=[str(int(a[b])+int(a[b][::b]))]
print(*a)
some terrible code I just made
I feel like it belongs here
!e
a,b=[input()],-1
while a[b]!=a[b][::b]:a+=[str(int(a[b])+int(a[b][::b]))]
print(*a)```
@thin trout :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | EOFError: EOF when reading a line
Yeah, it is in fact horrible haha
it's a lot more readable if you substitute all of the b's for -1, but it's 2 bytes shorter so yeah
>>> class Int:
... def __init__(self, value):
... self.value = value
... self.pos = False
... self.neg = False
... def __pos__(self):
... if self.pos: self.value += 1
... self.pos = not self.pos
... return self
... def __neg__(self):
... if self.neg: self.value -= 1
... self.neg = not self.neg
... return self
... def __repr__(self):
... return repr(self.value)
...
>>> i = Int(0)
>>> ++i
1
>>> --i
0
>>> --i
-1
>>> i
-1
Not usable, but fun :^)
Somebody wanted to know if you could do
max = MO[0]
for i in range(15):
if max < MO[i]:
max = MO[i]```
shorter. I am not proud of this.
!e
vals = [3, 4, 2, 7, 8, 9, 2, 1]
m = vals[0]
[m := vals[i] for i in range(len(vals)) if vals[i] > m]
print(m)```
@fallen heath :white_check_mark: Your eval job has completed with return code 0.
9
Isn't that just max(MO)?
Yes, he didn't want to use max though
anyone need nice performant multiset with choice?
hmm, maybe this is better in #algos-and-data-structs , i'll move it there
only the map at the end reminds me of here
where, i figured the need for a multisetch was pretty esoteric
not the code itself
how about this max:
In [95]: vals = np.random.randint(0, 20, size=20).tolist()
In [96]: [m for m in [-float('inf')] for i in vals for m in [m if m > i else i]][-1]
Out[96]: 19
In [97]: max(vals)
Out[97]: 19
it's not really shorter, but it is a one-liner
In [1]: vals = [3, 4, 2, 7, 8, 9, 2, 1]
In [2]: m = vals[0]
In [3]: [m := (m,x)[m<x] for x in vals]
Out[3]: [3, 4, 4, 7, 8, 9, 9, 9]
In [4]: m
Out[4]: 9```
students = int(input())
cards = int(input())
l1 = [num for i in range(1, cards, 2*students) for num in range(i,i+students) ]
for i in range(1, students + 1):
if cards in l1:
if cards - i % students == 0:
break
else:
if (cards + i) % students == 0:
break
print("S%d" %i)
Now I know I can reduce the two lines of input to a baar, any way you'd reduce the whole for loop thing into lesser baar?
I have no idea what this code is doing
I can explain that
so consider this
Card Number ↓ 1 2 3 4 5
9 8 7 6 10
11 12 13 14 15
19 18 17 16 20
21 22 23 24 25
I have 5 students, and say 25 cards, which are distributed in the manner as shown
now given a card, I'm to say which student it belongs to, which my code does
what I did there is that I noticed, the rows where the numbers are increasing, like 1 2 3 4 5, or 11 12 13 14 15, you can get the student id X like so:
I think you misplaced the 10 there?
no, it's right. That's how it's supposed to be
it's like circular
so it goes s1 -> s2 -> s3 -> s4 -> s5 -> s4 -> s3 -> s2 -> s1 -> s5 -> s1 -> ...
anyway that's besides the point
what I did is, if you see the rows where the cards are in an increasing order, you can notice a pattern
the student id X is such that it satisfies Card - X % Total number of cards == 0
and for non increasing rows, Card + X % Total number of cards == 0
That's what my code does
the list l1 basically contains the elements which are in increasing order in a row in that table I made above
does that make sense?
I'm still trying to process it
would you like me to clarify some part in specific @vestal quail ?
I think I'm confused because your code doesn't match your explanation
at least I think it doesn't
hm, wait lemme edit that
I think I'm writing it badly with the 'Element of the row' thing
!e py vals = [1,19,2,3,24,5,15,6,7,8,8] print(sorted(vals)[-1])
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
24
I also don't see how your code takes a card as input. As far as I can tell it only asks for the number of students and the number of cards, but never asks for a specific card
@vestal quail ah, yes the number of cards, is well also the card that is supposed to be the specific card
so is number of cards is 36, the specific card is also 36
Oh. Then I'm pretty sure there's an easier way to find the result
still thinking about it, but I'm pretty sure it exists
do you happen to have some test cases?
Input
5
16
Expected output
S4
-------------------
Input
7
14
Expected output
S7
-------------
Input
7
36
Expected output
S6
this seems to do it:
def find_student(students, card):
if ((card-1) // students) % 2:
# decreasing row
return students - card % students
else:
# increasing row
return (card - 1) % students
the increasing rows always start with a multiple of students + 1, so in those you basically just need a modulo operation
the decreasing rows are similar, except you subtract the result from students because the ordering goes backwards
yeah, you have a cards - 1 in the else but no so in the if, why is that?
students = int(input())
cards = int(input())
if ((card-1) // students) % 2:
print("S%d" %(students - card % students))
else:
print("S%d"%(card - 1) % students)
``` and the new shortened code would look like this
I think I can shorten that further
so something like this
students, card = [int(input()) for i in range(2)]
print("S%d" %(students - card % students) if ((card-1) // students) % 2 else "S%d"%(card - 1) % students)
wonder if I could combine the above 2 lines into 1
In the decreasing rows you don't need a -1 because they're shifted - the largest number is on the right
ah, yes
@vestal quail nah I'm looking to write a one-liner for fun
which is why #esoteric-python 🙂
lakmatiol!
(lambda students, card: print("S%d" %(students - card % students) if ((card-1) // students) % 2 else "S%d"%(card - 1) % students))(int(input()), int(input()))
I have no clue what is going on, but I do know how to inline variables
inline variables?
take a
var = stuff
code
``` and make it a single line
so is the basic structure like
(lambda variable, variable, more variables : print() and other functions here THEN the conditions THEN the input)
?
can I use that in all cases?
(lambda var, var1, var2: code with vars)(get_var(), get_var1(), get_var2())
``` the trick is you call the lambda
I call the lambda? but where?
Its useful if for example you need to use the input more than once
the () which enclose the wholecode?
Something like (lambda a: (a+1)*(a-1))(int(input()). You call it directly
uhm
also, why is the whole lambda thing inside a pair of brackets()
like
why is it (lambda a: (a+1)*(a-1))(int(input()) and not lambda a: (a+1)*(a-1))(int(input() ?
Is it the brackets that are helping us call the lambda function?
(lambda a: thing)(5) calls the lambda with 5 as the argument
Because of order of operations. Also, note where the first parenthesis closes, it is not at the end
Oh ya, missed the closing position
whereas lambda a: thing(5) would call thing with 5 and give us a lambda
give us a lambda? like lambda object or smth?
The whole thing would return a lambda (if it didn't error)
uhm, sorry but what is 'a lambda'?
lambdas do not error as long as there is not a syntax error in them
I thought lambdas were just like unnamed functions
they are
Oh yeah, good point
so lambda(x) returns to me an unnamed function? whereas (lambda)(x) calls the function?
you can do
def u(): pass
a = u
``` and you can do
```py
a = lambda: None
in both cases, you get a function instance
oh wow, I didn't know you can do that
something like lambda: None gives you a function
in the first case, its name is u, in the other it is either None or <lambda>, I am not too sure
(the name would be <lambda> iirc)
if you have a function in something like a, you can call it with a()
!e print((lambda:0).__name__)
@proper vault :white_check_mark: Your eval job has completed with return code 0.
<lambda>
ye
if your function is lambda: None, you can't do lambda: None() since that would be a lambda that calls None, so you add brackets
(lambda: None)() calls the lambda
not particularly helpful in this case since you could just write None but still
functions are objects in python, meaning you can do the same things with it as you can with any other variable
and also you can do this
almost everything in python is an object
!e
a = lambda:0
a.i = 5
print(a.i)
@proper vault :white_check_mark: Your eval job has completed with return code 0.
5
classes are objects? what wow
everything except keywords are objects in fact
>>> class Example:
... pass
...
>>> print(Example)
<class '__main__.Example'>
>>> x = Example
>>> x
<class '__main__.Example'>```
keywords are syntax thingies, objects are runtime thingies. Kinda pointless to compare them
you can also use functions as arguments to functions ```py
(lambda f:f())(lambda:4)
4```
Thank you people for the help, learnt so much. I'm gonna head off now but will come back and read the convo that goes on
is it possible to set function code by string assignment?
def dummy():
pass
# magic? somehow?
dummy.code = "print('Hello World')\nprint('kthxbye')"
dummy()
> Hello World
> kthxbye```
not overriding the function, just changing its code
>>> def func(): pass
...
>>> func.__code__ = compile("print('hey')", "<string>", "eval")
>>> func()
hey
is it possible for
variable
``` to execute arbitrary code.
possibly.
if you override dict.__getitem__ somehow, or replace the dictionary given by globals() with a custom subclass which implements its own __getitem__
>>> class EditedGlobals(dict):
... def __getitem__(self, x):
... if x.startswith('exec_'):
... self.__class__.__base__.__getitem__(self, '__builtins__').exec(self.__class__.__base__.__getitem__(self, '__builtins__').__import__('binascii').unhexlify(x[5:]))
... else:
... return self.__class__.__base__.__getitem__(self, x)
...
>>> __import__('ctypes').c_longlong.from_address(id(globals())+8).value=id(EditedGlobals)
>>> __import__
<built-in function __import__>
>>> exec_7072696e74282768656c6c6f20776f726c642729
hello world```
@proper vault
neat, I though that ctypes may be the way, but I do not know enough about ctypes
>>> exec_0a78203d206c6973742872616e676528322c203130303029290a69203d20320a7768696c65206920696e20783a0a20202020666f72206a20696e20783a0a20202020202020206966206a203e3d20693a0a202020202020202020202020627265616b0a2020202020202020696620692025206a203d3d20303a0a202020202020202020202020782e72656d6f76652869290a202020202020202020202020627265616b0a2020202069202b3d20310a7072696e742878290a
[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]```
if you're wondering what all of the self.__class__.__base__.__getitem__(self, '__builtins__') is about, it's because if you try to access globals the function will recurse infinitely
but self and x aren't globals so those are fine
btw for earlier:
import forbiddenfruit as fb
def dummy(): pass
fb.curse(type(dummy), 'code', property(lambda s: None))
def _set_code(f, c):
f.__code__ = compile(c, "<string>", "eval")
fb.curse(type(dummy), 'code', type(dummy).code.setter(lambda s, c: _set_code(s, c)))
dummy.code = "print('test')"
dummy()```
i=int(input())
a=i-2
print(*['#'*i,*['#'+' '*a+'#']*a,'#'*i*(i>1)],sep='\n',end='')
more terrible code I wrote
it basically outputs a square, so with an input of 3 it gives
###
# #
###
!eval ```py
i=int("20")
a=i-2
print(*['#'i,['#'+' '*a+'#']*a,'#'i(i>1)],sep='\n',end='')
@brisk zenith :white_check_mark: Your eval job has completed with return code 0.
001 | ####################
002 | # #
003 | # #
004 | # #
005 | # #
006 | # #
007 | # #
008 | # #
009 | # #
010 | # #
011 | # #
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/vazixayagu
so it does
that is shockingly terrible
golfing would only make it more readable
haha
i=int("20")
a=i-2
print('#'*i,*['#'+' '*a+'#']*a,'#'*i*(i>1),sep='\n',end='')
``` is I feel a pretty good start
oh yeah good point
any ideas on how to get rid of the *(i>1)? (made so it works when input is 1)
class a:
def __invert__(_):
return ~_
_=a()
print(~_)
another way of hitting the recursion limit
how can I overwrite builtin's dunders?
the module builtins or just generally built-in things?
just generally built-in things
depends on which dunder it is
I wanted to overwrite things like int.__add__
Python now maintains documentation for AST nodes, https://docs.python.org/3.9/library/ast.html
~type('',(),{'__invert__':lambda _:~_})()``` @gilded orchid hey what was that clean code to cause recursion errors, here's better one
you can use forbiddenfruit
!e
from forbiddenfruit import curse
curse(int, '__add__', lambda *_: 5)
print(1 + 6)
@proper vault :white_check_mark: Your eval job has completed with return code 0.
7
oh, right, snekbox is not always accurate with those
In [3]: from forbiddenfruit import curse
...: curse(int, '__add__', lambda *_: 5)
...: print(1 + 6)
5
snekbox da power
!e
import ctypes
ctypes.memmove(id(4), id(5), 28)
print(4, 5, 4 == 5, 4 is 5)
@marsh void :x: Your eval job has completed with return code 139 (SIGSEGV).
001 | <string>:3: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | 5 5 True False
003 | munmap_chunk(): invalid pointer
my repl just gives up
putting it into a scratch file does give the same output as snek
ipython just completely gives up
haha
as it does more math to figure out how it should look, and pretty much any ctypes fuckup will collapse it
such as replacing any integer sum with 5, or replacing 4 with 5
how about replacing all cached integers with 5
@marsh void i hope you're writing
what are we doing again?
from typing import Union
def sign(n: Union[float, int]) -> int:
return (-1 if n < 0 else (1 if n > 0 else 0))```
simple one
just as an example of what I do on average with it
on what haha
https://paste.pythondiscord.com/odezomapaj.py what do I win?
I will make it even longer, forgot a docstring
Fuck you
You didn't even write that yourself
You probably made it using a tool
Mine is handmade quality
I did write the tool myself
yes but still
buuut, I do concede it is kinda cheating
two guys arguing over whose is longer 🤔
😳
the elongated variant https://paste.pythondiscord.com/ifixajikey.py
5262characters of utter irrelevance
elongated with my utf-32 exec hack
https://paste.pythondiscord.com/tudopahuru.py
oops, forgot to import itertools as it
other than that, it does work and the parsing is actually taking time now
hi special channel.
Hi special member
!e
class Str(str):
def __mul__(self, other):
if type(other) in [float, int]:
absval = abs(other)
s = super().__mul__(int(absval))
cf = len(self) * (absval - int(absval))
s += self[:int(cf)]
return Str(s) if other >= 0 else Str(s[::-1])
else:
return Str(super().__mul__(other))
better_string = Str("Hello World!")
print(better_string * 2)
print(better_string * 2.5)
print(better_string * -0.3)
print(better_string * 5 * 0.1)
@hot crypt :white_check_mark: Your eval job has completed with return code 0.
001 | Hello World!Hello World!
002 | Hello World!Hello World!Hello
003 | leH
004 | Hello
I am happy now
@hot crypt Geniuos
@hot crypt Geniuos
mhmhm
you could generalize that
it warms my heart
🔥 ❤️
string + string is easy to define. that's just concatenation
string times string would be an inner product. that's the only way it makes sense. so it would probably be the difference in length or something
string - string hmm
what is that
string - string just deletes the length
but what about "kappa" - "ligma"
'Hello' - 'Dude' = 'H'
how does that make sense
that would be "Hello" - 4 imho
' ' * "ABCDE" == "A B C D E"
"Kappa" * "Ligma" = "LigmaKLigmaALigmaPLigmaPLigmaA"
or wrong way around
I don't think we can get the algebra working 😓
you can overload __mul__ for different types
how about string - string deletes all characters from string2 in string1
so "Hello" - "eo" == "Hll"
kinda like set substraction, but order is preserved
or maybe string2 is removed from string1 if present...
"Hello this is text" - "this is " == "Hello text"
nvm theres already str.replace("text", "") for that
ye, a - b as a.replace(b, '') sounds good
could even be extended to str - list(str)
!eval
print("test")
@sick hound :white_check_mark: Your eval job has completed with return code 0.
test
!eval print test
!eval
while True:
!eval
while True:
!eval
foo = 0
while True:
print("This is line " + str(foo) + " of the test.")
foo += 1
@sick hound :x: Your eval job timed out or ran out of memory.
001 | This is line 0 of the test.
002 | This is line 1 of the test.
003 | This is line 2 of the test.
004 | This is line 3 of the test.
005 | This is line 4 of the test.
006 | This is line 5 of the test.
007 | This is line 6 of the test.
008 | This is line 7 of the test.
009 | This is line 8 of the test.
010 | This is line 9 of the test.
011 | This is line 10 of the test.
... (truncated - too many lines)
Full output: too long to upload
gotcha
!eval
import ctypes
t = 0,
ctypes.c_longlong.from_address(id(t) + 24).value = id(t)
while t:
t = t[0]
@marsh void :warning: Your eval job timed out or ran out of memory.
[No output]
hehe
someone on repl.it turned python into a bunch of lambdas
it took something like 540 bytes just to output "Hello!"
(lambda _, __, ___, ____, _____, ______, _______, ________:
getattr(
__import__(True.__class__.__name__[_] + [].__class__.__name__[__]),
().__class__.__eq__.__class__.__name__[:__] +
().__iter__().__class__.__name__[_:][_____:________]
)(
_, (lambda _, __, ___: _(_, __, ___))(
lambda _, __, ___:
bytes([___ % __]) + _(_, __, ___ // __) if ___ else
(lambda: _).__code__.co_lnotab,
_ << ________,
(((_____ << ____) + _) << ((___ << _____) - ___)) + (((((___ << __)
- _) << ___) + _) << ((_____ << ____) + (_ << _))) + (((_______ <<
__) - _) << (((((_ << ___) + _)) << ___) + (_ << _))) + (((_______
<< ___) + _) << ((_ << ______) + _)) + (((_______ << ____) - _) <<
((_______ << ___))) + (((_ << ____) - _) << ((((___ << __) + _) <<
__) - _)) - (_______ << ((((___ << __) - _) << __) + _)) + (_______
<< (((((_ << ___) + _)) << __))) - ((((((_ << ___) + _)) << __) +
_) << ((((___ << __) + _) << _))) + (((_______ << __) - _) <<
(((((_ << ___) + _)) << _))) + (((___ << ___) + _) << ((_____ <<
_))) + (_____ << ______) + (_ << ___)
)
)
)(
*(lambda _, __, ___: _(_, __, ___))(
(lambda _, __, ___:
[__(___[(lambda: _).__code__.co_nlocals])] +
_(_, __, ___[(lambda _: _).__code__.co_nlocals:]) if ___ else []
),
lambda _: _.__code__.co_argcount,
(
lambda _: _,
lambda _, __: _,
lambda _, __, ___: _,
lambda _, __, ___, ____: _,
lambda _, __, ___, ____, _____: _,
lambda _, __, ___, ____, _____, ______: _,
lambda _, __, ___, ____, _____, ______, _______: _,
lambda _, __, ___, ____, _____, ______, _______, ________: _
)
)
)
that's 1916 bytes
nice
BRUH! I don't understand nothing in this code
I believe it creates some numbers using some bitshifts and by reading the number of parameters to a function mapped to 8 functions, then I think it finds sys.stdout.write or something by constructing the attribute names out of the documentation and names of various objects. It passes the numbers to whatever output function it's using, and the numbers represent the Unicode for Hello world!
This is code with best readability lol
actually it gets os.write, not sys.stdout.write
!pep 614
Behold, everyone!
Hell yes
lambdas as decorators without magic!
def d_(x):
# identity
return x
@print
@d_(lambda f: f.__name__)
def lemon() -> None: ...``` though we should be able to do this now
_=lambda x:x
@_(lambda:0)
def zero():5
first time posting some snippet in #esoteric-python ```py
from random import choice
while True:
(lambda player_move=input('rock paper scissors\n'),computer_move=choice(['rock','paper','scissors']):
print('Draw') if computer_move==player_move else print ('You win.') if {'paper':'scissors','scissors':'rock','rock':'paper'}[computer_move]==player_move else print ('You lose.') if player_move in ('rock','paper','scissors') else print('Invalid Input'))()
This is cool. Stand by for me making it even more weird.
PEP614, oh hell yeah!
By the way @robust palm in your dictionary, 'scissor' is missing an s.
*iter(lambda options={'paper':'scissor','scissors':'rock','rock':'paper'}:(user_move:=input("rock paper scissors\n"))and (computer_move:=__import__("random").choice([*options]))and print(computer_move,[["You lose!","You win!"][options[computer_move]==user_move],"Draw!"][computer_move==user_move]),...),
PEP 614 was accepted‽ I agree with the 'hell yeah!'
I expect the code above can be golfed a lot by combining the strings and only checking the first letter for the dict.
@snow beacon yeah, it was; GvR was basically the sponsor of it so it makes sense haha
Nice @snow beacon Can you tell me how this works without if statement [["You lose!","You win!"][options[computer_move]==user_move],"Draw!"][computer_move==user_move]),...),?
Working back from the end:
The comma is part of *blah, which converts to a list.
The , ...) is the second argument of iter.
In this case, it makes a while loop that executes the function until it returns Ellipsis, which is basically a while loop.
Then there's the subscript [computer_move==user_move] which is either True or False, which are used as integers in this case. False is 0, True is 1.
It indexes in the list [options[computer_move]==user_move],"Draw!"].
Wait, no.
The list is [["You lose!","You win!"][options[computer_move]==user_move], "Draw!"]
So it either picks "Draw!" or the other option based on the boolean.
Thanks.
There's another way to make it which is extremely hard to read.
I'll make a demo.
"YYoouu lwoisne!!"[options[computer_move]==user_move::2]
Replacing ["You lose!","You win!"][options[computer_move]==user_move].
I'll let you figure out how it works because I've got to go.
I figured it out [options[computer_move]==user_move will return either true 1or false 0 and then print the string skipping a character each time
salt-die made this really cool RPS
from random import randint
user = "rsp".find(input("Choose rock[r], paper[p], or scissors[s]: "))
computer = randint(0, 2)
print(f"The computer chose {('rock', 'scissors', 'paper')[computer]}.")
print(("It's a draw!", "You lose!", "You win!")[user - computer])
>>> ord('r')%5%3
1
>>> ord('p')%5%3
2
>>> ord('s')%5%3
0
this might be useful
@gilded orchid That raises an error
this py (lambda _, __, ___, ____, _____, ______, _______, ________: getattr( __import__(True.__class__.__name__[_] + [].__class__.__name__[__]), ().__class__.__eq__.__class__.__name__[:__] + ().__iter__().__class__.__name__[_:][_____:________] )( _, (lambda _, __, ___: _(_, __, ___))( lambda _, __, ___: bytes([___ % __]) + _(_, __, ___ // __) if ___ else (lambda: _).__code__.co_lnotab, _ << ________, (((_____ << ____) + _) << ((___ << _____) - ___)) + (((((___ << __) - _) << ___) + _) << ((_____ << ____) + (_ << _))) + (((_______ << __) - _) << (((((_ << ___) + _)) << ___) + (_ << _))) + (((_______ << ___) + _) << ((_ << ______) + _)) + (((_______ << ____) - _) << ((_______ << ___))) + (((_ << ____) - _) << ((((___ << __) + _) << __) - _)) - (_______ << ((((___ << __) - _) << __) + _)) + (_______ << (((((_ << ___) + _)) << __))) - ((((((_ << ___) + _)) << __) + _) << ((((___ << __) + _) << _))) + (((_______ << __) - _) << (((((_ << ___) + _)) << _))) + (((___ << ___) + _) << ((_____ << _))) + (_____ << ______) + (_ << ___) ) ) )( *(lambda _, __, ___: _(_, __, ___))( (lambda _, __, ___: [__(___[(lambda: _).__code__.co_nlocals])] + _(_, __, ___[(lambda _: _).__code__.co_nlocals:]) if ___ else [] ), lambda _: _.__code__.co_argcount, ( lambda _: _, lambda _, __: _, lambda _, __, ___: _, lambda _, __, ___, ____: _, lambda _, __, ___, ____, _____: _, lambda _, __, ___, ____, _____, ______: _, lambda _, __, ___, ____, _____, ______, _______: _, lambda _, __, ___, ____, _____, ______, _______, ________: _ ) ) )
for me, anyway.
Traceback (most recent call last):
File "C:\Users\User\python\myProgram.py", line 1, in <module>
(lambda _, __, ___, ____, _____, ______, _______, ________:
File "C:\Users\User\python\myProgram.py", line 2, in <lambda>
getattr(
OSError: [Errno 9] Bad file descriptor```
well
ouch
lambda cls: next(obj for obj in __import__('gc').get_objects() if type(obj) is dict and obj == dict(cls.__dict__))``` this seems more friendly
And I made this one, hehe
@marsh void does it same with gc.get_referents(cls.__dict__)
yea, most of time I use it
>>> gc.get_referents(object.__dict__)[0]["__init_subclass__"] = classmethod(lambda cls: print("I am the owner of this interpreter"))
>>> class X:
... pass
...
I am the owner of this interpreter
This would be a good challange for this channel to create a class that is not inheriting from object in python 3
how
lmao
Okay that would be hecking fun
get_dict = lambda cls: __import__('gc').get_referents(cls.__dict__)[0]``` okay this one is better for modifying stuff then
TIL such an epic thing exists
I'm pretty sure that they are sending this challenge completely aware that it is impossible haha
Yeah it feels like so
It's not, you could do it by using ctypes or the like to create a class inheriting from itself.
even though everything in python inherits from object
I'm pretty sure the interpreter will reject it
It doesn't implement the basis of what a python object needs to communicate with the interpreter
Or.. You could redefine everything yourself
Lol
i'm getting somewhere ```py
from ctypes import *
x=c_char_p(b'test')
y=c_char_p(b'something')
typ=cast(ARRAY(c_longlong,44)(10, id(type), 0, c_void_p.from_buffer(x).value, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, c_void_p.from_buffer(y).value, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),py_object).value
typ
<class 'test'>```
@bitter iris ```py
from ctypes import *
x=c_char_p(b'test')
y=c_char_p(b'something')
arr=ARRAY(c_longlong,44)(10, id(type), 0, c_void_p.from_buffer(x).value, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, c_void_p.from_buffer(y).value, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
arr[33]=addressof(arr)
typ=cast(arr,py_object).value
z=()
arr[42]=id(z)
typ
<class 'test'>
typ.bases
()```
@marsh void @thin trout it's not impossible
yooo
admittedly it's not a particularly useful class ```py
typ()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot create 'test' instances```
but it is not a subclass of object ```py
issubclass(typ, object)
False```
isinstance(typ, object) tho?
neat
all these zeros for methods like tp_iter and stuff in C code?

yes
>>> obj=cast(ARRAY(c_longlong,2)(10,id(typ)),py_object).value
>>> obj
<test object at 0x000001BFE5613E10>
>>> type(obj)
<class 'test'>
>>> isinstance(obj,object)
False```
i love how no matter what is thrown at this channel, in a matter of hours someone has it coded
That's Python for you.
noice @sick hound
that reminds me i need to update my nickname
anyway yeah, i basically just looked up the struct and wrote the memory manually
I lost my discord account because of discord kicked me out of session while switching my 2FA app :///
@sick hound yea, there is a part which checks a special condition and if the condition couldnt find it sets object as a base
Here's a one line rock-paper-scissors using the tricks from above:
print((lambda a,b:'The computer played '+['scissors','rock','paper'][b]+'.\n'+'DYYrooauuw WL io ns !e !'[(a-b)%3::3])(ord(input()[0])%5%3,__import__('random').randint(0,2)))
If you don't care what the computer played:
print('DYYrooauuw WL io ns !e !'[(__import__('random').randint(0,2)-ord(input()[0])%5%3)%3::3])
Someone who knows more about python than I do could probably get it shorter, but I'd say it's decent.
from random import randint
user = "rsp".find(input("Choose rock[r], paper[p], or scissors[s]: "))
computer = randint(0, 2)
print(f"The computer chose {('rock', 'scissors', 'paper')[computer]}.")
print(("It's a draw!", "You lose!", "You win!")[user - computer])
-->
print("=LW"["rsp".find(input("r,p,s: "))-randint(0,2)])
(Importing random still.)
I feel like it would be difficult to get it shorter than
print('=LW'[ord(input())%-4+__import__('random').randint(0,2)])
well you could ignore the input and just return a random LW=
i mean, that's really the gist of it anyway
input();print(choice('=LW'))
On cpython you can get random-ish numbers with id.
__import__('os').urandom(1)[0]%3 one char shorter :p
I stand by my threaded random generator
maybe could make it a bit faster by changing the switch interval
sleep(0) is somewhat a random generator lol
!e
(lambda cls: __import__('gc').get_referents(cls.__dict__).pop(0))(int).update(square=lambda self: self * self); print(13.square())
@neat otter :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | (lambda cls: __import__('gc').get_referents(cls.__dict__).pop(0))(int).update(square=lambda self: self * self); print(13.square())
003 | ^
004 | SyntaxError: invalid syntax

oops
!e (lambda cls: import('gc').get_referents(cls.dict).pop(0))(int).update(square=lambda n: n**2)
@marsh void :warning: Your eval job has completed with return code 0.
[No output]
!e (lambda cls: import('gc').get_referents(cls.dict).pop(0))(int).update(square=lambda n: n**2); print((13).square())
@marsh void :white_check_mark: Your eval job has completed with return code 0.
169
@neat otter
excuse me what
yep
no idea about how it works but it looks super cool
a=val
f"{' , '.join([' '.join([clef + ':', kwargs[clef] , '(' + type(kwargs[clef]).__name__ + ')']) for clef in kwargs])}
``` Wonder how I could get the len of that thing in the middle lol
O wait, i'm just stupid
(supposed to present the code to ppl in my class, trying to make one line overly stupid and complicated just to mess up with them
I did the same to my math teacher, it was fun haha
It was a little for loop to calculate sequences, I turned it into a one-liner with some itertools in the middle
shortest way to get the product of a list of numbers?
actually nvm
are there any ways I can golf this code?
a=1
for x in input().split():a*=sum(map(int,x))
print(a)
!e
import math
print(math.prod(range(1,12)))
@proper vault :white_check_mark: Your eval job has completed with return code 0.
39916800
Also I don't get why you're mapping int on x and summing
So "12" is supposed to become 3?
Cause otherwise that's a logical error
print(eval(input().replace(' ','*')))
It's not, it's splitting the input on whitespace before iterating
"12 24" x becomes "12" in first iteration and so on, right?
oh yeah, you're right after all
To simplify, basically If you're splitting, then all you need is int(x).
Summing on a Mapping takes the string one digit at a time. That will give you bad results
it's reasonable that they want that, they never said otherwise
Aye, I've posed it as a question
eval('print(('+input().replace('','+').replace('+ ',')*(')+'0))')
an input would be like
3
12 53 16
the first line is the number of numbers, and the second line was the space seperated numbers
the goal was to output the product of the sums of each number's digits (eg: (1+2)*(5+3)*(1+6) which is 158 in that case)
AttributeError: attribute 'f_locals' of 'frame' objects is not writable
Any way to mess with it?
I need to replace function's globals
ah, I meant f_globals
I tried to make it like that so it will not affect current globals but ehh
a = 13
f = lambda: var(b=a**13), result(b)``` basically I am trying to get this to work
var modifies f_locals, but b is already LOAD_GLOBAL in the code
that's what I am trying to figure out
@brazen geyser
you can modify f_globals the same way as f_locals
and aside from that you'd have to patch the bytecode to change any instructions to use locals rather than globals
if i understand what youre trying to do correctly
how about putting things into globals and then restoring the state of globals, using sth like a context manager. Not sure how much more viable it is that that though
if you have access to the actual source symbol table might help you to infer the context of variables unless you dont know
I mean ehh
So my idea now is to find the access to variables that are in call var(a=1) (updates locals()['a'] = 1 basically)
For now I am looking for LOAD_GLOBAL which refer to a name defined as kwarg for that var function
Then I replace it with LOAD_FAST pointing to the index of a new appended name in co_varnames
But it doesn't seem to work quite well haha
hm, I just thought, how about
def f():
var(a=<expr>, b=<expr>)
print(a, b)``` convert the bytecode of this function to that:
```py
def f():
a = <expr>
b = <expr>
print(a, b)```
_May I ask what is var() ? It doesn't seems like a built in, doesn't it? _
f= lambda u:((a:=u+3), print(a)) ```
Well that works but not <3.8
hm, is augmented assignment an additional opcode though
!e
import dis; dis.dis('(a := 1)')
@marsh void :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_CONST 0 (1)
002 | 2 DUP_TOP
003 | 4 STORE_NAME 0 (a)
004 | 6 RETURN_VALUE
@marsh void :white_check_mark: Your eval job has completed with return code 0.
001 | 3 0 LOAD_CONST 1 (1)
002 | 2 DUP_TOP
003 | 4 STORE_FAST 0 (a)
004 | 6 POP_TOP
005 | 8 LOAD_GLOBAL 0 (print)
006 | 10 LOAD_FAST 0 (a)
007 | 12 CALL_FUNCTION 1
008 | 14 POP_TOP
009 | 16 LOAD_CONST 0 (None)
010 | 18 RETURN_VALUE
def f():
var(a=<expr>, b=<expr>)
print(a, b)``` convert the bytecode of this function to that:
```py
def f():
a = <expr>
b = <expr>
print(a, b)```
So, any ideas regarding this? I tried but it turns pretty meh since I am pretty newbie to bytecode
!e
import dis
def f(): var(a=1, b=str()); print(a, b)
def g(): a = 1; b = str(); print(a, b)
dis.dis(f), dis.dis(g)
@marsh void :white_check_mark: Your eval job has completed with return code 0.
001 | 2 0 LOAD_GLOBAL 0 (var)
002 | 2 LOAD_CONST 1 (1)
003 | 4 LOAD_GLOBAL 1 (str)
004 | 6 CALL_FUNCTION 0
005 | 8 LOAD_CONST 2 (('a', 'b'))
006 | 10 CALL_FUNCTION_KW 2
007 | 12 POP_TOP
008 | 14 LOAD_GLOBAL 2 (print)
009 | 16 LOAD_GLOBAL 3 (a)
010 | 18 LOAD_GLOBAL 4 (b)
011 | 20 CALL_FUNCTION 2
... (truncated - too many lines)
Full output: too long to upload
So yeah that's what I have
I really like working with dis.Bytecode objects. They are immutable but the Instruction format makes everything a bit more easy. You can create a Bytecode object, go over the instructions and check if the opcode is LOAD_GLOBAL and the value of the oparg is one of your kwargs (var (**kwargs)) and if it is true append this bytecodes offset to a list. And then go over that list of offsets and alter the only opcode that is presented on that offset, argument can be same and then recreate a Code object with replace
Can I subclass bool by means of ctypes?
Oh, it turns out my use case simply needed to do some reference trickery in __bool__().
Hey everyone, I'm gathering some ideas to maybe bring esoteric challenges back to life as a user event, if you have any interesting challenge ideas, feel free to DM me 
My brain is just melting right now
i feel like i deleted my fork a day or two ago
Hey, you have a repo bin
Yes in your settings I thing
I mean.. I didn't even understood what was your circles about haha
it's the different ways to draw non-intersecting circles
where () represents a circle
(())() is one circle inside another circle next to a circle
((())) circle inside a circle inside a circle
But what do you consider as intersecting?
the circles don't intersect
By the way
they are either next to each other or inside one another, but no intersecting boundaries
(()) but this can be considered as intersecting and non-intersecting, right?
it could if we didn't specify non-intersecting circles apriori
Intersecting is like (()()) right?
no thats two circles next to each other inside a big circle
that would be a forbidden config
This sounds like one of the thing I did, forgot what it is, but needs to count open / close brackets
sorry about the bad gimp drawing
but maybe that makes it clearer
how many topologically distinct sets of n non-intersecting circles?
i find it interesting that you can represent them with parenthesis mostly
But a same representation can have many actual shapes right?
second picture the circles overlap
which isn't allowed
non-intersecting
means the circles can't intersect
so the goal is to draw the circles?
intersecting circles shown above can be done with different brackets:
( { ) }
but not all distinct sets of intersecting circles can be represented 1-dimensionally
since the intersections can get pretty subtle with a lot of circles
(May I also ask what this can be used for?)
but none of that matters for non-intersecting circles, they're perfectly representable
i dunno what it can be used for
it's a fun problem, it can be used to take up some of your time
It sounds a bit like an advent of code challenge
it could be probably
Well, if you have any other challenge idea

that's much different than the combinatorial problem
Okay, I see, so different circles has different brackets to denote
()[]{} and ({})[] are good
({)}[] is not
Yep, this sounds a lot like what I use for parsing wikimedia or w/e it is
I made my own parser to parse into trees, basically have a stacks of opens and ends
Whenever I see an end symbol, I pop the last open symbol and pair them together -> never overlap
so ({)}[] turned into ({})[]
Can be tweaked to check I guess
you don't really need different brackets for non-intersecting circles though, it's unambiguous
it might make it more readable though
i have a function that gives this:
In [154]: set(all_words_length(4))
Out[154]:
{(((()))),
((()())),
((())()),
((()))(),
(()(())),
(()()()),
(()())(),
(())(()),
(())()(),
()((())),
()(()()),
()(())(),
()()(()),
()()()()}
but there are some redundant sets in there
like this ((())()) is really the same as this (()(())) topologically
i was going to work more on it eventually
I was able to use laktiamol's teachings today, and rewrite
total, rows = int(input()), int(input())
l = [i**3 for i in range(1, total + 1)]
print(rows**3, sum(l), sep = "\n")
into baar
(lambda total, rows: print(rows**3, sum([i**3 for i in range(1, total + 1)]), sep = "\n"))(int(input()), int(input()))```
🙂 so I'm glad I've made some progress, thank you @proper vault !
Oh there's 2 other kind of things I wanna learn to write in a baar
Ek is this:
l1 = []
indices = []
while a != 0:
l1.append(a)
if a%2 == 0:
indices.append(index)
a = a//2
index += 1
essentially a while loop with conditions in it and appending to two lists in the same loop
The 2nd is this:
l2 = []
for j in range(len(l1)):
l2.append(b)
b = b*2
where I'm changing something inside the for loop, but like
so I could do l2 = [b**2 for j in range(len(l1))] but that will miss out the first b that was appended in the original for loop.
So how do I write the above two things in like baar xd
The 2nd one looks likepy l2 = [b * pow(2, i) for i in range(len(l1))]
It's simply math, where you loop from 0 to len(l1) but not doing anything with it, and each time increase b by 2
that first looks like the recipe to fast exponentiation
It does
which you can shrink by wrapping it in a function and letting it call itself, i guess
The 2nd one looks like
py l2 = [b * pow(2, i) for i in range(len(l1))]
thanks, damn I didn't think of that
The first can be like this, i still think it can be much better
prev = a * 2
l1 = [(prev := prev // 2) for _ in range(len(bin(a)[2:]))]
indices = [i for i, s in enumerate(bin(a)[2:]) if s == '1']
print(l1, indices)```
basically making use of bin(a)
you could use log base 2 i think
sorry salt, I don't follow
The first snippet is well yeah, appending to a list a number, and the quotient when divided by 2, till the number becomes 1 and storing indices where the quotient was even
yep, im dumb
l1 = [a // pow(2, i) for i in range(len(bin(a)[2:]))]
indices = [i for i, n in enumerate(l1) if not n % 2]
print(l1, indices)```
[10, 5, 2, 1] [0, 2]```
i don't think i have a simple fast exponentiation snippet, just a matrix mul one
but when you are doing fast exponentiation: you use squares
def exp_squaring(u, n):
if n == 0:
return [[1, 0], [0, 1]]
if n == 1:
return u
if n & 1:
return matrix_mul(u, exp_squaring(u, n - 1))
return exp_squaring(matrix_mul(u, u), n >> 1)
that's overkill lol
@crystal mica right, the log2 thing and checking for places with 1, yeah that makes sense
the length of l1 is the length of bin(a)[2:]
oh shit
im dumb again gdi
prev = a << 1
l1 = [(prev := prev >> 1) for i in range(len(bin(a)[2:]))]
indices = [i for i, n in enumerate(l1) if not n % 2]
print(l1, indices)```
In [170]: 11//2
Out[170]: 5
In [171]: 11 >> 1
Out[171]: 5
yeah I just realized
yep, bit shifting is fast
it is extremely fast
no way by the way to have both indices and l1 being assigned things in like a baar, yeah?
why not
uhm, how ?
prev = a << 1
l1, indices = [(prev := prev >> 1) for i in range(len(bin(a)[2:]))], [i for i, s in enumerate(bin(a)[2:]) if s == '1']```
hmm, 2 lines
also why did you use := there
well if you go with the // then you wont need it
hmm
good question
l1, indices = [a >> i for i in range(len(bin(a)) - 2)], [i for i, s in enumerate(bin(a)[2:]) if s == '1']```
There you go
I need sleep
that's the length of a binary number .... well you need to take the ceiling
so you mean do a for i in range(ceil(int(log(a,2)))) in Shirayuki's code?
In [181]: a = 312109841204
...: len(bin(a)) - 2
Out[181]: 39
In [182]: ceil(log(a, 2))
Out[182]: 39
something like that, yes
Sometimes it's about thinking outside the box
hm, yeah I'm dumb xd





