#esoteric-python
1 messages · Page 36 of 1
>>> f = 123.456
>>> import struct as s;s.unpack('q',s.pack('d',f))[0]
4_638_387_860_618_067_575
>>>
>>> n = 4_638_387_860_618_067_575
>>> import struct as s;s.unpack('d',s.pack('q',n))[0]
123.456
python floats are actually doubles
>>> f = 123.456
>>> import struct as s;s.unpack('i',s.pack('f',f))[0]
1_123_477_881
>>>
>>> n = 1_123_477_881
>>> import struct as s;s.unpack('f',s.pack('i',n))[0]
123.45600128173828
ctypes.c_ulonglong.from_buffer(ctypes.c_double(f)).value is another
kinda boring tho
def f2n(f: float) -> int:
import math
sign = f < 0
exp = int(math.log2(f))
frac = f / 2 ** exp
return (sign << 31) | ((exp + 127) << 23) | int(frac * 2 ** 23 + 1)
def check(f: float) -> None:
import struct
n1 = struct.unpack('i',struct.pack('f',f))[0]
n2 = f2n(f)
assert n1 > 0 and n2 > 0, (n1, n2, f)
s1 = bin(n1)[2:].rjust(32,'0')
s2 = bin(n2)[2:].rjust(32,'0')
sdiff1 = ''.join(' ' if a == b else a for a,b in zip(s1,s2))
sdiff2 = ''.join(' ' if a == b else b for a,b in zip(s1,s2))
if s1 != s2:
print(f'f = {f}')
print(f'expected: {s1}')
print(f'diff: {sdiff1}')
print(f'got: {s2}')
print(f'diff: {sdiff2}')
print()
import random
for _ in range(100):
exp = random.randint(-127,+128)
frac = 1 + random.random()
f = frac * 2 ** exp
check(f)
``` sometimes it works 😄
!e
import marshal
b = marshal.dumps(123.456)[1:]
print(marshal.loads(b'\xe9' + b[4:]) * 0x100000000 + marshal.loads(b'\xe9' + b[:4]))
don't think marshal can do 32bit ones though.
@proper vault :white_check_mark: Your 3.12 eval job has completed with return code 0.
4638387860618067575
!e py m = memoryview(bytearray(4)) m.cast('f')[0] = 123.456 print(m.cast('i')[0]) you can abuse memoryview casting
@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.
1123477881
i actually used that trick to make doubles that i can use to make fake objects by swapping the type with CellType
!e
import os
import time
from sys import platform
print("WELCOME. MAKE SURE ITS NOT https://google.com OR http://google.com IT MUST BE google.com NOT HTTPS OR HTTP.")
hostname = input("enter your epic web: ")
response = os.system("ping " + hostname)
#check response
if platform == "linux" or platform == "linux2":
os.system('clear')
elif platform == "darwin":
os.system('clear')
elif platform == "win32":
os.system('cls')
#break
print("WELCOME. MAKE SURE ITS NOT https://google.com OR http://google.com IT MUST BE google.com NOT HTTPS OR HTTP.")
print("enter your epic web: "+ hostname)
if response == 0:
print(f"{hostname} is running, lmao")
else:
print(f"{hostname} is not running :(")
time.sleep(1.0)
@weak heron :x: Your 3.12 eval job has completed with return code 1.
:warning: Note: input is not supported by the bot :warning:
001 | WELCOME. MAKE SURE ITS NOT https://google.com OR http://google.com IT MUST BE google.com NOT HTTPS OR HTTP.
002 | enter your epic web: Traceback (most recent call last):
003 | File "/home/main.py", line 5, in <module>
004 | hostname = input("enter your epic web: ")
005 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
006 | EOFError: EOF when reading a line
1wrong channnel
I wrote this a while ago:
Python techniques for golfing:
- "
,=" operator and starred assigning (aka*x, _ = stuff). This can also convert something to a list while doing other stuff, and can be used in multiple ways. Look up the docs. :=operator (akawalrusorassignment-expression)*xunpacking something (even**xfor dicts){*x}set conversion or[*x]list conversionu=long_function_nameoverused function renaming (if the function is used multiple times this will save space)open(0)read from stdin- Look for alternate solutions or hacky math methods
- Use binary operations if possible
<<,~- - Any kind of comprehension
- If using a function, abuse default arguments
- Use
lambdaif you can and it is shorter - Combine conditionals (
x==2 and y==2becomes (x==y==2) - Also, combine comparisons (
a<b and b>cbecomesa<b>c) - Precompute what you can
exec/evalcan be used in clever ways, like running something multiple times (exec("print('hello world');"*5))- Use
a,b,c,d=somethingto unpack it into 4 values (also usea,b,c='123'nota,b,c='1','2','3') - Use [::-1] to reverse a list instead of
list(reversed())[this is also better outside of golfing in general] - Use multiplication on bools (version-specific now) (
if a and bbecomesif a*b). True is 1 in this case and False is 0 - Use
+=instead ofappend - Use as many builtins as you can (*guide, not a rule) as they are usually shorter
- If you need to import something from a builtin, use
from x import*or justimport x, whichever is shorter. - If you are using string literals, use the minimal amount of escape sequences possible, or even a raw-string.
- Never use random.randint (*guide not rule) and use
id('')%nto get a random number from1ton-1. Note that this works in CPython but may not with other versions. - Use
//1to floor something
More tips that are smaller/rarer with less use cases:
- Use
&for set overlaps (intersections) [just use set operators in general] - If you want to print without a newline use
print(end=x) - Most
range()calls that are small (range(3)) are shorter as set, list, or tuple literals ({0,1,2}orfor x in 0,1,2) - You can put many types of literals next to
ifstatements so reorder your comparisons (if x=='a':x='b'becomesif'a'==x:x='b') - Use hex literals for numbers greater than
999,999 - Use ternary statements or do an array subscript instead of if statements (
[False, True][a==b]) - If in Python 2 (idk who still is) then you can abuse the fact that all things can be compared (
a<b<[]>c>d) - Make sure to only use spaces in increments of 1 if using identation
- Store a lookup table as magic numbers (https://codegolf.stackexchange.com/a/41742/115749)
- You can write
n+1andn-1as-~nand~-n, which can save space in parentheses due to the python order of operators - Use a
range()andchr()setup to get a certain set of characters if it is shorter - Read in binary to avoid
ord()calls list[~i]suprisingly gets the-ith element from the reverse of list (fixes an off by one error for-i)
Those are more so code golfing techniques
If you want to get better at general esoteric-ness, I would probably just linger around the channel and spot what you can spot or look at the history of the channel
some topics are fishhook, different codings, ctypes, abusing syntax and language features (e.g. see my recent abusage of type bounds and default mutable arguments), and of course more.
Also, using % string formatting
that's not golfing
Can this be pinned?
i'm still confused about pandas islice syntax trick like df[islice(...),:]
itertools.islice(iterable, stop)``````py
itertools.islice(iterable, start, stop[, step])```
Make an iterator that returns selected elements from the iterable. If *start* is non-zero, then elements from the iterable are skipped until start is reached. Afterward, elements are returned consecutively unless *step* is set higher than one which results in items being skipped. If *stop* is `None`, then iteration continues until the iterator is exhausted, if at all; otherwise, it stops at the specified position.
If *start* is `None`, then iteration starts at zero. If *step* is `None`, then the step defaults to one.
@cloud fossil my bad, it's https://pandas.pydata.org/docs/reference/api/pandas.IndexSlice.html but i saw it imported as islice in a tutorial
It seems like it's a convenience class for what would otherwise be an iterable of slice objects
yes, because you can only use the : sugar inside indices
hence if you want to group slices together you need to do it in a separate slicing object
idk if anyone is interested in code golf, but I was able to tie the best Python solution for the Evil Numbers problem at 40 bytes https://code.golf/evil-numbers#python:
i=0
while i<51:print(i);i=i+2^-(i+2^i)%3
(I didn't figure out the math, I yoinked it from stack exchange)
I don't think that many people here are interested in code golfing
I am interested in code golfing
that's what surprised me, i never saw people using : as custom sugar before
oh I see, you can't enjoy : outside a getitem override
in a function f, f(1:2) will be invalid syntax, but with any class you can then use it
f[1:,:,:2,::3,1::3]
((slice(1, None, None), slice(None, None, None), slice(None, 2, None), slice(None, None, 3), slice(1, None, 3)),)
so fun
cant the i=i+... be written as i+=...?
I don't think so, but let me try it
nah it doesn't work
i actually don't know why though
it's probably something to do with the invert ^
i suppose a+b^c is parsed as (a+b)^c
!e
print(1+2^3)
print((1+2)^3)
@spiral parrot :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 0
002 | 0
yeah that's because of operator precedence
why do you think that?
lol
there's a % right at the end of it
That was a joke ofc, i guess it missed :p
oh
hehe ```pycon
type('',(),{'del':lambda _:print("the following is NOT 2")})()
<main. object at 0x0000026F698623F0>
2
the following is NOT 2
2
lmao
does anyone know how to use a file codec after its ,,added" via site.addsitedir pth file
like it isnt available if i do it right at the start if its not loaded but after site.addsitedir it no longer cares as its not the first line
and i dont want to do add the thing to my actual site directory
k i got something to work lmao
import site
import os
site.addsitedir(os.path.dirname(os.path.realpath(__file__))+"/autoexec")
import run # can use # coding: <> in run.py
print((λx:x+1)(1))
lmao this finally works
that is interesting
i would think it gets cleaned up immediately?
OH
builtins._ in the repl
that's really funny
that's what i thought too
until i tested it out
python's repl is so silly
not necessarily
but in general, being good at golfing requires in-depth knowledge of a language
it's almost entirely true
you don't need to be good at maintainability
but everything else counts
Is there a hacky way to add a parameter to a function with CodeType/FunctionType modifications?
!e ```py
def foo():
print(c)
c = None # force c to be a local
foo.code = foo.code.replace(co_argcount=1)
foo('abc')
@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.
abc
is that what you mean?
mainly looking for keyword-only args since I don't know exactly how those work
You can probably bump up the number of co_kwonlyargcount the same way, but you may need to add a variable name to make the bind correct
!e ```py
def foo():
print(c)
c = None # force c to be a local
foo.code = foo.code.replace(co_kwonlyargcount=1)
foo(c='foobar')
foo()```
@rugged sparrow :x: Your 3.12 eval job has completed with return code 1.
001 | foobar
002 | Traceback (most recent call last):
003 | File "/home/main.py", line 7, in <module>
004 | foo()
005 | TypeError: foo() missing 1 required keyword-only argument: 'c'
the tricky part would be aligining the variables, since locals are order dependent
But according to that code snippet, wouldn't it just be ```py
co_varnames = (*co_varnames[:co_argcount], myvarname, *co_varnames[co_argcount:])
co_argcount += 1
co_kwonlyargcount += 1
f.defaults = (*f.defaults, mydefault)
you'll need to add to co_nlocals
Gotcha
!e ```py
def foo():
print(locals())
foo.code = foo.code.replace(
co_kwonlyargcount=1,
co_varnames=('varname',),
co_nlocals=1
)
foo.kwdefaults = {'varname':'value'}
foo()```
@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.
{'varname': 'value'}
Can I ask or tell about some exotic things in python?
Well... this thing is not very strange, but interesting
print([0xfor x *range(y << exec("raise ValueError"))])
ah, that's a funny one. I was so confused until I figured out how it was parsed.
The more interesting variant — IMHO — is the one where in is involved, making it even more deceptive:
print([0xbeef_for x in wat])
hex literal trickery
TIL in python 2.2 you can specify metaclass for all classes in one module by using module-level __metaclass__
it became unsupported in 3.0
speaking of Python 2, I miss this ```>>> "x" <> '"x"'
True
!e
import time
def functionThatTakesTime():
time.sleep(0)
return "Some value"
def functionThatDoesThings(verbose=True):
print("Running function")
return [
functionThatTakesTime(),
print("Finished running function") if verbose else None
][0]
print(functionThatDoesThings())
@arctic plume :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | Running function
002 | Finished running function
003 | Some value
No need for an intermediate variable
Not to mention some fancy logging module that's more advanced than the project it's being used in
huh?
what is that?
>py -2 -c "print('x' == 'x')"
True
>py -2 -c "print('x' == `'x'`)"
False
>py -2 -c "print(type(`'x'`))"
<type 'str'>
>py -2 -c "print(type('x'))"
<type 'str'>
``` truly esoteric moment
oh wait
'x' + `'x'` == "x'x'"
but py 'x' + `x` doesnt work because x is not defined
its just repr right?
Not everywhere, at least
only in indexes I think. x[...] is legal. The motivation was extended slicing for numpy arrays I believe
C:\Users\denba>py -2 -c "..."
File "<string>", line 1
...
^
SyntaxError: invalid syntax
C:\Users\denba>py -2 -c "print(...)"
File "<string>", line 1
print(...)
^
SyntaxError: invalid syntax
C:\Users\denba>py -2 -c "x[...]"
Traceback (most recent call last):
File "<string>", line 1, in <module>
NameError: name 'x' is not defined
C:\Users\denba>py -2 -c "x[... + 1]"
File "<string>", line 1
x[... + 1]
^
SyntaxError: invalid syntax
C:\Users\denba>py -2 -c "[][...]"
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: list indices must be integers, not ellipsis
C:\Users\denba>py -2 -c "type('',(),dict(__getitem__=lambda self, x: __import__('sys').stdout.write(str(x))))()[...]"
Ellipsis
C:\Users\denba>py -2 -c "print(Ellipsis)"
Ellipsis
interesting
so ... is special-cased inside x[]
x[...], x[...,...] and x[...,1:2,...] are valid
x[... + 1], x[...:...] are not
whoa
yeah
tbh i miss the backtick repr
its a nice syntax
Wait what how does this work
: )
oh this would be majorly annoying for an obfuscator
wdym by that
naive python source code parsing would malfunction here i guess
like it would assume that the or is inside the hex literal
tbh just use tokenize(r) if its valid python originally
what happens if
1
1 1
or even
2
1
err
I even dont know xD
I have two questions, one is pretty esoteric, one is not. Idk where is the best place to ask it, so i am asking here:
- I have a pointer. How to determine if I can dereference the pointer?
Maybe something like (idk if this is possible on windows) ```cpp
void* ptr = 42;
try:
(char)ptr;
except SEGFAULT:
return not_valid;
else:
return valid;
I want it to work on windows preferably in pure python (with ctypes), but simple c-extension is also good.
Additional features that will be nice to have:
- is an entire range from X to Y valid?
- how many bytes after X are available?
- somehow iterate over all available bytes (= get list of all available ranges)
2. I'm starting python thread in some game. I want to talk to this thread from another process. How can I do that?
I thing `socket` can do it, but i think it is too low-level. What are other approaches to this?
What is this for: injected dll will read and write to memory, external process is a CheatEngine-like GUI for that.
I want to send commands like "write X to Y" or "read N bytes from X" to my thread in game, so i can control and monitor game state from outside without big changes to the game itself.
note: there is no tos violation/malicious intent, this is only for educational and research purposes
!d multiprocessing.shared_memory.SharedMemory TIL this is a thing in stdlib 😄
class multiprocessing.shared_memory.SharedMemory(name=None, create=False, size=0)```
Creates a new shared memory block or attaches to an existing shared memory block. Each shared memory block is assigned a unique name. In this way, one process can create a shared memory block with a particular name and a different process can attach to that same shared memory block using that same name.
As a resource for sharing data across processes, shared memory blocks may outlive the original process that created them. When one process no longer needs access to a shared memory block that might still be needed by other processes, the [`close()`](https://docs.python.org/3/library/multiprocessing.shared_memory.html#multiprocessing.shared_memory.SharedMemory.close) method should be called. When a shared memory block is no longer needed by any process, the [`unlink()`](https://docs.python.org/3/library/multiprocessing.shared_memory.html#multiprocessing.shared_memory.SharedMemory.unlink) method should be called to ensure proper cleanup.
- off the top of my head, there are three ways i can think of
- find where the allocation information is stored and use that (requires significant amount of work + understanding the
malloc(or other memory allocator) implementation you're using) - brute force it: fork, have the child deref the pointer, and see if the child segfaults. to get more information (size of allocation, etc.) do the fork/deref check for each byte you want to check in the range
- i dont remember what the exact name is but there's a thing in
/proc/selfthat has all the memory maps of the process. you could read that
If you're comfortable writing in C++ there's https://github.com/Plaristote/segvcatch but this is more of a #c-extensions topic
But safest will always be to run it in a subprocess as recovering from a segfault is a scary thing to do
On Linux you could query /proc/self (I believe?) to see what memory regions are accessible as well
ooh i have a weird answer for this one.
the write syscall internally does not fail on invalid read
let me find my code
it is, it needed due to some odd behavior with pipes afaik, it raises an OSError
Identical behavior across operating systems?
it has worked on my unix based x86 macbook and on an x86 ubuntu box
about to test on arm
i doubt windows works, but you can already catch invalid r/w on windows by default
!e ```py
import os
from ctypes import c_char
def check_addr(addr):
r, w = os.pipe()
try:
if os.write(w, (c_char*1).from_address(addr)):
return True
except OSError:
return False
finally:
os.close(r)
os.close(w)
print(check_addr(1337)) # invalid address
print(check_addr(id(1))) # valid address
@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | False
002 | True
you could also use the pipe directly to deref the pointer, by passing a size to use instead of 1 and then just reading from r with os.read
@grave rover ^ it worked on my m2 mac as well, i think that behavior is part of spec
if you print the OSError, it reprs as [Errno 14] Bad address (at least on my m2 macbook)
This is so incredibly cursed I love it
i need to find my original notes on it, I remember i walked thru the unix source to find the reason for it
first approach is not realistic
python, iirc, uses malloc, but game is written in delphi and there is another allocator that is incompatinle with malloc
second is good, but im on windows and game is pretty old and written for windows, so it is impossible to recompile it :-(
/proc/self is interesting, i didnt know that (also doesnt work on windows :-( )
oh, this even works on windows 🥳
[Errno 22] Invalid argument - on windows
for is an entire range from X to Y valid? you can just calculate the offset from X to Y (Y - X) and use that as the size of the c_char array
yes, that will work, but it requires reading every byte, so it is a bit slow for big ranges
you could do a binary search inward
for a few layers deep until you are confident that the entire range is probably good
if A is valid and B is not - sure, binsearch is perfect for that
but if A is valid and B is valid too, the only option is to check as many addresses inside as i can
true
if page size is 4kb, i think i can check every byte with step 4k
thats what i was about to say, you can compute the start of the page from a given address
isnt that just ptr - ptr % pagesize ?
ptr & ~(pagesize - 1) i think? let me check my asmhook code
and you can get the pagesize with libc
!e ```py
from ctypes import cdll
libc = cdll.LoadLibrary(None)
print(hex(libc.getpagesize()))
@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.
0x1000
doesnt work on windows :(
^ that has example C code for windows
i can adapt to ctypes code gimme a sec
i cant figure out how to load winapi dll
nvm, there is no such thing as winapi.dll
there is kernel32.dll
from ctypes import windll, Structure, Union, POINTER, c_int, c_void_p, c_short, byref
class DUMMYSTRUCTNAME(Structure):
_pack_ = 1
_fields_ = (
('wProcessorArchitecture', c_short),
('wReserved', c_short)
)
class DUMMYUNIONNAME(Union):
_fields_ = (
('dwOemId', c_int),
('DUMMYSTRUCTNAME', DUMMYSTRUCTNAME)
)
class _SYSTEM_INFO(Structure):
_pack_ = 1
_fields_ = (
('DUMMYUNIONNAME', DUMMYUNIONNAME),
('dwPageSize', c_int),
('lpMinimumApplicationAddress', c_void_p),
('lpMaximumApplicationAddress', c_void_p),
('dwActiveProcessorMask', POINTER(c_int)),
('dwNumberOfProcessors', c_int),
('dwProcessorType', c_int),
('dwAllocationGranularity', c_int),
('wProcessorLevel', c_short),
('wProcessorRevision', c_short)
)
_getsysteminfo = windll.kernel32.GetSystemInfo
_getsysteminfo.argtypes = [POINTER(_SYSTEM_INFO)]
def getsysteminfo():
systeminfo = _SYSTEM_INFO()
_getsysteminfo(byref(systeminfo))
return systeminfo
print(getsysteminfo().dwPageSize)```
^ that should work, tested on a windows vm
I should really build a C struct -> ctypes Structure converter
no point in doing all of that by hand
import ctypes
lib = ctypes.WinDLL('kernel32')
si = ctypes.create_string_buffer(100) # arbitrary big enough size
lib.GetSystemInfo(si)
print(ctypes.c_int32.from_address(ctypes.addressof(si) + 4)) # pagesize is located at offset 4
del si # how to properly deallocate it?
^ i did this
that works (btw kernel32 is accessible at ctypes.windll.kernel32)
🧐
ah yea i thought I had talked about that code in here before
os.write returns the number of bytes written, so using it with if there works
hmm
actually
!e ```py
import os
from ctypes import c_char
def check_addr(addr):
r, w = os.pipe()
try:
return os.write(w, (c_char*1).from_address(addr)) == 1
except OSError:
return False
finally:
os.close(r)
os.close(w)
print(check_addr(1337)) # invalid address
print(check_addr(id(1))) # valid address``` now it'll only return True or False, previously if the address was valid but write wrote 0 due to other reasons, it would return None
@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | False
002 | True
def check_addr(addr: int) -> bool:
r, w = os.pipe()
try:
os.write(w, (c_char*1).from_address(addr))
except OSError:
return False
else:
return True
finally:
os.close(r)
os.close(w)
is that the same?
that would return True if an address was readable but the os did not read any bytes (there are some weird edge cases where it can do that)
if thats ok with your impl then that should work
afaik, the only way that could happen with the above code is if the pipe buffer is full which I don't think could be possible
although on some os's where pipes share a global buffer it could happen
but it should be extremely unlikely
you can also get rid of the (c_char * 1) and instead just do c_char, the buffer should be treated the same afaik
indeed
are you loading pythondlls into a game?
i am trying to start thread, but it refuses to start and just hangs whole application
im not sure what is happening
i tried to print-debug it, and it hangs here: https://github.com/python/cpython/blob/3.12/Lib/threading.py#L983
i guess that is because new thread quickly crashes and doesnt unlock the lock, but i dont see any exceptions printed to stdout/stderr/__stderr__
game has its own threads, and i am starting my own thread from one of game's threads
interpreter otherwise works fine
do you have any ideas why this doesnt work?
Lib/threading.py line 983
self._started.wait()```
tbh i have no idea, could be the game is managing threads and is killing the child thread you start?
what game is it and how are you injecting code?
game is Space Rangers HD, written in old delphi (delphi 7, iirc), 32bit
i'm loading my dll using game's script function, it just loads dll without anything else fancy
all my code is in DllMain, i'm initializing interpreter and starting little python script that hangs on mythread.start(), and that hangs entire game because game waits my code to complete
it is also tricky to make stdout/stderr work in that environment since GUI app doesnt have them
i tried this: c freopen(LOGFILE_STDOUT, "w", stdout); setvbuf(stdout, NULL, _IONBF, 0); // no buffering freopen(LOGFILE_STDERR, "w", stderr); setvbuf(stderr, NULL, _IONBF, 0); and this: ```py
out = open('####py-stdout.log', 'at', buffering=1) # line-buffering
sys.stdout = sys.stdout = out
sys.stderr = sys.stderr = out
but i still dont see any errors printed related to thread failure
maybe try launching a thread with C then loading the interpreter there? i think that python needs the main thread to stay alive
yeah, i was thinking about that
tomorrow i will try creating just thread without python and doing something in it
if it works, i will launch python in it
smart
hmm, maybe there are some GIL problems? (if i initialized python incorrectly)
parent threads holds gil, child tries to do something but gil is held, so parent is holding gil and waiting for child indefinitely
Could be, I'm not sure how the GIL works when embedding python
that works perfectly! 🥳
!e ```py
metamaker = (lambda meta, cls: ( lambda: [ (dict_.pop(es, None) for es in dict_.get("slots", tuple())) if [None for [globals()["dict_"]] in [[dict(cls.dict)]]][0] is None else None, [None for [globals()["dict_"]["metaclass"]] in [[meta]]], [None for [globals()["dict"]["wrapped"]] in [[cls]]], meta(str(cls.name), tuple(cls.bases), dict), ][-1]))
printf = lambda format_string, *args: print(format_string,end="") if not args else print(format_string % args,end="")
main = metamaker(type("b", (type,), {"call": lambda self, : {None}}), type("", (object,), {}))()
int = metamaker(type("a", (type,), {"sub": lambda self2, : {None} if isinstance(, set) else [None for [globals()[.split("=")[0]]] in [[import('builtins').int(_.split("=")[1])]]][0]}), type("a", (object,), {}))()
void = None
return_0 = None
int-main(void)-{
printf("Hello, World!\n"),
int-"num1=2",
int-"num2=3",
printf("%d + %d = %d\n", num1, num2, num1+num2),
return_0
}```
@harsh spear :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | Hello, World!
002 | 2 + 3 = 5
the actual fu-
Beautiful
the most esoteric thing here is the message from bot
different across platforms
indeed
are you on pc or phone?
react with this: 🐧 🤖 🍎 🪟
chrome discord win10
; left the chat
I got similar one
if you use __annotations__ and globals hooks you can get a syntax without string literals being necessary
e.g.,
int: num1 = 2;
int: num2 = 3;
How can I change the video output of the manim library
I have to change the resolution and framerate of the video making it more high defination and quality
not with the way those curlies are used
true
alternatively, you could use codecs and just invoke a c compiler on the source
!e
_:(__import__(''.join([(lambda:(__:=[*(_*(4>>(4).__class__(4/4)))],__.insert((4).__class__(4/4),[4].__class__.__class__.__name__[(4).__class__(4/4)]),globals().__setitem__('__',__)))(),__][-1]))).stdout.write((4==.4).__class__.__name__[4-4]+(4,).__class__.__name__[(4).__class__(4-4-4/4)]+(.4).__class__.__name__[-(4>>1)]+(4).__class__.__name__[(4).__class__(4/4)]+[4].__class__.__name__[-(4>>1)]+chr(4+4+(4>>(4).__class__(4/4))))=[4].__class__.__name__[-(4>>1)]
@dense nova :white_check_mark: Your 3.12 eval job has completed with return code 0.
beans
4 = (1<<2)
= 1<<1<<1
!e
__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))((4==.4).__class__.__name__[4-4]+(4,).__class__.__name__[(4).__class__(4-4-4/4)]+(.4).__class__.__name__[-(4>>1)]+(4).__class__.__name__[(4).__class__(4/4)]+[4].__class__.__name__[-(4>>1)]+chr(4+4+(4>>(4).__class__(4/4))))```
@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.
beans
not eso enough hmm
!e
__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))((_:=__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())))),(_==.4).__class__.__name__[_-_]+(_,).__class__.__name__[(_).__class__(_-_-_/_)]+(.4).__class__.__name__[-(_>>1)]+(_).__class__.__name__[(_).__class__(_/_)]+[_].__class__.__name__[-(_>>1)]+chr(_+_+(_>>(_).__class__(_/_))))[__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())])
@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.
beans
tehre we go
i'll let the chr and hte .4s live
for now
!e py __builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))((_:=__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())))),(_==.4).__class__.__name__[_-_]+(_,).__class__.__name__[(_).__class__(_-_-_/_)]+(.4).__class__.__name__[-(_>>1)]+(_).__class__.__name__[(_).__class__(_/_)]+[_].__class__.__name__[-(_>>1)]+__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(_.__mul__(_).__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))(_+_+(_>>(_).__class__(_/_))))[__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())])
@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.
beans
!e py __builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))((_:=__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())))),__:=_.__floordiv__(_),(_==_.__truediv__(_.__add__(_).__add__(__.__add__(__)))).__class__.__name__[_.__sub__(_)]+(_,).__class__.__name__.__getitem__((_).__class__(_.__sub__(_).__sub__(_.__floordiv__(_))))+(_.__truediv__(_.__add__(_).__add__(__.__add__(__))).__class__.__name__[-(_.__rshift__(__))]+(_).__class__.__name__[(_).__class__(_.__floordiv__(_))]+[_].__class__.__name__.__getitem__((_.__rshift__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))).__neg__())+__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(_.__mul__(_).__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))(_+_+(_.__rshift__(_).__class__(_.__truediv__(_))))))[__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__neg__()])
@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.
beans
slight esotericisms
!e
((((((((lambda _, __, ___, ____: chr(___ % __) + _(_, __, ___, ____))(
lambda _, __, ___, ____: _(_, __, ___, ____).__add__(chr(____ % __))
if ____ else '',
ord('h') << 7,
))(lambda _, __, ___: _(_, __, ___))(lambda _, __, ___: _ if __ <= _ else _(_, __ - _, ___)(_ + _, __, ___) if not __ % _ else _(2, __ + 2, ___), 2, 16)))))(__import__(().__class__.__name__[::3] + 'y').__class__.__name__[::-1], lambda _, __, ___: _(_, __, ___))
@bold crag :x: Your 3.12 eval job has completed with return code 1.
001 | File "/home/main.py", line 1
002 | (((((((((lambda _, __, ___, ____: chr(___ % __) + _(_, __, ___, ____))(
003 | ^
004 | SyntaxError: '(' was never closed

this is just paren spam
oh yea that makes sense, in the repl, the expression results are printed if they are not None, even in a for loop. So it reaches quit, tries to output it, and segfaults on the invalid read from zero
actually this is a feature of single compile mode: ```py
dis(compile('x;y', '', 'single'))
0 0 RESUME 0
1 2 LOAD_NAME 0 (x)
4 CALL_INTRINSIC_1 1 (INTRINSIC_PRINT)
6 POP_TOP
8 LOAD_NAME 1 (y)
10 CALL_INTRINSIC_1 1 (INTRINSIC_PRINT)
12 POP_TOP
14 RETURN_CONST 0 (None)
CALL_INTRINSIC_1 1 (INTRINSIC_PRINT) simply calls sys.displayhook
>>> dis(compile('x;y', '', 'single'))
0 0 RESUME 0
1 2 LOAD_NAME 0 (x)
4 PRINT_EXPR
6 LOAD_NAME 1 (y)
8 PRINT_EXPR
10 LOAD_CONST 0 (None)
12 RETURN_VALUE
``` 3.11
I see someone has stolen my way of doing it
.
I guarantee this is my way for the numbers because my obfuscator could only do .add to build the numbers
Which ultimately makes it longer than it needs to be
i would recommend using a combination of .__lshift__ and .__add__
except for a few numbers that are close to values that are easy to get
Oh my god
whats an obfuscator? never heard of it
something that takes regular source code and makes it unreadable by regular people
💀 i bet they put a limit on the paste site after i put my bloated hello world
for example this https://pastebin.com/5f0tzeXh is print("Hello, World")
@unique heath
that was a joke
no one needs obfuscators when you have brain
hey i want to learn python
this is NOT the place to learn python
this is advanced python
go to #1035199133436354600 or #python-discussion
this is esopy not advanced python
oh look it's the fishhook author
how awesome
esopy is one of the best ways to learn python deeply
You like knowing something built under python
Instead of just stuff built on top of python
does quantum computing count as esoteric ?
can someone pls coach me in python?
i think so
Cool
I'm becoming interested in quantum AI
Been decoding this stuff (thank you gpt4 senpai)
U is an operator that performs a phase shift for each x_i
The circuit calculates the global phase of the x_i qbits
The whole thing acts as an artificial neuron
In quantum computing, the quantum phase estimation algorithm is a quantum algorithm to estimate the phase corresponding to an eigenvalue of a given unitary operator. Because the eigenvalues of a unitary operator always have unit modulus, they are characterized by their phase, and therefore the algorithm can be equivalently described as retrievin...
The amount of phase shift at each x_i is equivalent to the weights being applied to each input. I think that what is measured is the phase of the entire state, that results from the combination of the x_i
I'm still not super sure how the phase estimation Algo works
if you are still interested, there is a bit more information:
- main thread (entry point of python) has to be alive always, otherwise something will break
- everything works if you spawn new thread in C and then start python there
- threading works perfectly (while main python thread is alive)
- ctypes also works
- i havent checked anything else, bc i dont need it, but i think my cute python should be pretty good in this unfriendly environment
I recently watched Structure and Interpretation of Test Cases from NDC London 2019, and decided to try and implement it in python. It could be pushed further, but it's good enough at it's job to act as a proof of concept. https://pastebin.com/zdUGDSEs
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
google keep?
How do you even come up with stuff like thi?
What's the shortest non-trivial quine? this was the shortest I could get in 5-10mins: ```py
s='s=%s;print(s%%repr(s))';print(s%repr(s))
print(open(__file__).read())```
oh non-trivial
I wouldn't call that a trivial quine
but yeah it's "cheating"
!e chatgpt came up with this:
s = 's = {!r}\nprint(s.format(s))'
print(s.format(s))
@fleet bridge :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | s = 's = {!r}\nprint(s.format(s))'
002 | print(s.format(s))
yeah it's not quite what I was asking for
quine should have no side effects, only output
accessing filesystem counts as side effect
all i know about qiunes is they pritn otu their own prorgam
this is very similar to what you did
is this how AI rebellion should look like?
why not :c
because that's boring
print(__file__[1:]) works if you place it into the root of your system with the name print(__file__[1:])
oh i love that
!e heres a fun one
File "/home/main.py", line 1
File "/home/main.py", line 1
IndentationError: unexpected indent
@versed eagle :x: Your 3.12 eval job has completed with return code 1.
001 | File "/home/main.py", line 1
002 | File "/home/main.py", line 1
003 | IndentationError: unexpected indent
you need to set the string on both lines to be __file__ though
!e
((setattr(__import__('sys'),'stdin',__import__('io').StringIO("0.1+0.2"))),(_:=lambda pat,re:(print(round((lambda expr:((fi:=type(())(map(lambda __:__.group(),re.finditer(pat,expr)))),eval('{'+','.join(f"'{o}':lambda x,y:x{o}y"for o in(pat[i]for i in(3,17,15,20)))+'}')[fi[1]](*map(float,(fi[0],fi[2]))))[-1])(input('>>> ')),1)),None)[-1])(''.join(map(chr,[2**3|2**5,2**2|2**3|2**4|2**6,2**2|2**5|2**6,2**0|2**1|2**3|2**5,2**2|2**3|2**4|2**6,2**1|2**2|2**3|2**5,2**2|2**3|2**4|2**6,2**2|2**5|2**6,2**0|2**1|2**3|2**5,2**0|2**3|2**5,2**2|2**3|2**4|2**5|2**6,2**3|2**5,2**2|2**3|2**4|2**6,2**0|2**1|2**3|2**5,2**2|2**3|2**4|2**5|2**6,2**0|2**2|2**3|2**5,2**2|2**3|2**4|2**5|2**6,2**0|2**1|2**2|2**3|2**5,2**2|2**3|2**4|2**5|2**6,2**2|2**3|2**4|2**6,2**1|2**3|2**5,2**0|2**3|2**5])),*map(__import__,_.__code__.co_varnames[1:])))
@karmic pumice :white_check_mark: Your 3.12 eval job has completed with return code 0.
>>> 0.3
actually this might count as trivial
idk
indeed fun but i think the ,,program" is not ,,outputting" its source tho? its the compiler in this case i think
i like that! ❤️
i think it counts, because program is still printed to the screen (not to stdout, but it is a small detail)
in case of normal quines, interpreter compiles your code, runs it and prints its output
in your case interpreter compiles your code and prints it
this one is really clever
hehe im doing cursed stuff
can someone obfuscate this code for me?
arr = [1, 2, 3] for i in arr: print(i * arr[i])
[print(i*arr[i]) for i in arr]
I'm slowly mastering brainfuck to a point of if im asked to make something i probably can
What (turing complete) esolang should i master next
(As i master it i de-esotericize it)
I was thinking whitespace,and even if i do that . . . What next?
not obfuscated, but oneline'd and golfed a bit (im sure someone can golf it further) (its longer nvm 💀)
befunge is pretty cool imo
Also with each new one id add it to my interpreter, and that lil peice of shitty GUI will grow to be the best esolang interpreter
Ooh okay i think i remember that one a bit
I will look into both
!e this would error, so
arr = [1, 2, 3]
for i in arr:
print(i * arr[i])
@low lynx :x: Your 3.12 eval job has completed with return code 1.
001 | 2
002 | 6
003 | Traceback (most recent call last):
004 | File "/home/main.py", line 3, in <module>
005 | print(i * arr[i])
006 | ~~~^^^
007 | IndexError: list index out of range
o
arr needs to contain values less than len(arr)
I dont mind this one tbh. Imma add it to the list
let's make arr [1, 2, 1] then
arr = [1, 2, 3] for i in arr: x = 0 If i > len(arr) : x = i- i%len(arr) print((i + (x(i-x-i%len(arr))))* arr[i-x])
?
I iust like
Added some extra stuff that seems mathy
At a glance
And did some stuff to fix if you ever have values out of range
Obfuscating is hard ngl
Imma stick to making my own programming languages. Dont need to obfuscate it if no one besides you knows it anyway lol
dog python bot deleted my message because of the python file
@daring arch i pinged you and the bot deleted it, excuse the ghost ping
!e
arr=[1,2,3]
[__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))(__.__mul__(locals().__getitem__(chr((4<<5)-(4<<3)+1)+chr((4<<5)-(4<<2)+2).__mul__(2)).__getitem__(__))) for __ in arr]```
@unique heath :x: Your 3.12 eval job has completed with return code 1.
001 | 2
002 | 6
003 | Traceback (most recent call last):
004 | File "/home/main.py", line 2, in <module>
005 | [__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))(__.__mul__(locals().__getitem__(chr((4<<5)-(4<<3)+1)+chr((4<<5)-(4<<2)+2).__mul__(2)).__getitem__(__))) for __ in arr]
006 |
... (truncated - too long)
Full output: https://paste.pythondiscord.com/URU4YT5HERJ7NRZX77FEJQGZAQ
obfuscator?
see if you can obfuscate the constants, builtins, and the loop
:3
and im hungry
have fun!
!e py arr=[1,2,3] (____:=__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__package__.__dir__().__len__().__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())))),_____:=____(__builtins__,__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__sub__(__import__.__dir__().__len__()).__sub__(__name__.__dir__().__len__()).__sub__(13))),[__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))(__.__mul__(_____.__call__().__getitem__(chr((4<<5)-(4<<3)+1)+chr((4<<5)-(4<<2)+2).__mul__(2)).__getitem__(__))) for __ in arr]) sigh
@unique heath :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 2, in <module>
003 | (____:=__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__package__.__dir__().__len__().__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())))),_____:=____(__builtins__,__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__sub__(__import__.__dir__().__len__()).__sub__(__name__.__dir__().__len__()).__sub__(13))),[__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__(
... (truncated - too long)
Full output: https://paste.pythondiscord.com/V74QVG5H5KO27X24WBPBDOLTPY
what version are you using
3.12.0
did someone ping me here?
oh yeah sorry i pinged the wrong person
!e py arr=[1,2,3] (____:=__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__package__.__dir__().__len__().__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())))),_____:=____(__builtins__,__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__sub__(__import__.__dir__().__len__()).__sub__(__name__.__dir__().__len__()).__sub__(12))),[__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))(__.__mul__(_____.__call__().__getitem__(chr((4<<5)-(4<<3)+1)+chr((4<<5)-(4<<2)+2).__mul__(2)).__getitem__(__))) for __ in arr])
@unique heath :x: Your 3.12 eval job has completed with return code 1.
001 | 2
002 | 6
003 | Traceback (most recent call last):
004 | File "/home/main.py", line 2, in <module>
005 | (____:=__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__package__.__dir__().__len__().__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())))),_____:=____(__builtins__,__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__sub__(__import__.__dir__().__len__()).__sub__(__name__.__dir__().__len__()).__sub__(12))),[__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__
... (truncated - too long)
Full output: https://paste.pythondiscord.com/WQTCEKE7ZDBOVKTUOLE4VGA66Q
there we go
did you test inside a repl or inside a file
repl
that might be why then
hmm if i do too much obf i might get over char limit
o yeh
stuff like __builtins__.__dir__().__len__() would be different
pyramid=lambda s:[print(x)for x in((s+len(s)*"*")[n*(n+1)//2:n*(n+1)//2+n+1]for n in range(len(s)))if x.replace("*","")]
friend issued a challenge, this is what i came up with. something better probably possible
112 chars after the equals
i think these are equivalent
n*(n+1)//2+n+1
n*(n+3)//2+1
!e
(lambda*_:(_:=lambda*sys:(lambda*__:((lambda*f:lambda*g:lambda*a:g[-1](g[0](sys[0],f[0](a[0])),f[0](a[1])))(lambda*l:''.join(map(chr,l[0])))(getattr)([((2**0)|((2**1))|((2**4))|((2**5))|((2**6))),((2**2)|((2**4))|((2**5))|((2**6))),((2**2)|((2**5))|((2**6))),((2**0)|((2**1))|((2**2))|((2**3))|((2**5))|((2**6))),((2**0)|((2**2))|((2**4))|((2**5))|((2**6))),((2**2)|((2**4))|((2**5))|((2**6)))],[((2**0)|((2**1))|((2**2))|((2**4))|((2**5))|((2**6))),((2**1)|((2**4))|((2**5))|((2**6))),((2**0)|((2**3))|((2**5))|((2**6))),((2**2)|((2**4))|((2**5))|((2**6))),((2**0)|((2**2))|((2**5))|((2**6)))]))(chr(10).join(map(lambda*____:str(____[0]*__[____[0]]),__))))(*map(lambda*___:hash(___[0][0]).__mod__(___[0][1]),(((),2),((1,),3),((),2)),),))(*map(__import__,_.__code__.co_varnames))and(None))()
@karmic pumice :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 2
002 | 2
003 | 2
(the 1 2 1 are indeed here)
!e
print(*map(lambda*___:hash(___[0][0]).__mod__(___[0][1]),(((),2),((1,),3),((),2)),),)
@karmic pumice :white_check_mark: Your 3.12 eval job has completed with return code 0.
1 2 1
!e
exec(__import__('base64').b64decode("KGxhbWJkYSpfOihfOj1sYW1iZGEqc3lzOihsYW1iZGEqX186KChsYW1iZGEqZjpsYW1iZGEqZzpsYW1iZGEqYTpnWy0xXShnWzBdKHN5c1swXSxmWzBdKGFbMF0pKSxmWzBdKGFbMV0pKSkobGFtYmRhKmw6Jycuam9pbihtYXAoY2hyLGxbMF0pKSkoZ2V0YXR0cikoWygoMioqMCl8KCgyKioxKSl8KCgyKio0KSl8KCgyKio1KSl8KCgyKio2KSkpLCgoMioqMil8KCgyKio0KSl8KCgyKio1KSl8KCgyKio2KSkpLCgoMioqMil8KCgyKio1KSl8KCgyKio2KSkpLCgoMioqMCl8KCgyKioxKSl8KCgyKioyKSl8KCgyKiozKSl8KCgyKio1KSl8KCgyKio2KSkpLCgoMioqMCl8KCgyKioyKSl8KCgyKio0KSl8KCgyKio1KSl8KCgyKio2KSkpLCgoMioqMil8KCgyKio0KSl8KCgyKio1KSl8KCgyKio2KSkpXSxbKCgyKiowKXwoKDIqKjEpKXwoKDIqKjIpKXwoKDIqKjQpKXwoKDIqKjUpKXwoKDIqKjYpKSksKCgyKioxKXwoKDIqKjQpKXwoKDIqKjUpKXwoKDIqKjYpKSksKCgyKiowKXwoKDIqKjMpKXwoKDIqKjUpKXwoKDIqKjYpKSksKCgyKioyKXwoKDIqKjQpKXwoKDIqKjUpKXwoKDIqKjYpKSksKCgyKiowKXwoKDIqKjIpKXwoKDIqKjUpKXwoKDIqKjYpKSldKSkoY2hyKDEwKS5qb2luKG1hcChsYW1iZGEqX19fXzpzdHIoX19fX1swXSpfX1tfX19fWzBdXSksX18pKSkpKCptYXAobGFtYmRhKl9fXzpoYXNoKF9fX1swXVswXSkuX19tb2RfXyhfX19bMF1bMV0pLCgoKCksMiksKCgxLCksMyksKCgpLDIpKSwpLCkpKCptYXAoX19pbXBvcnRfXyxfLl9fY29kZV9fLmNvX3Zhcm5hbWVzKSlhbmQoTm9uZSkpKCk=").decode())
@karmic pumice :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 2
002 | 2
003 | 2
(chars after the =)
112 -> 100
pyramid=lambda s:[print(X)for n in range(1,len(s)+1)if set(X:=(s+len(s)*"*")[(S:=sum(range(n))):S+n])-{'*'}]
(chars after the =)
100 -> 95
pyramid=lambda s:[print(X)for n in range(1,len(s)+1)if set(X:=(s+(S:=sum(range(n)))*"*")[S:S+n])-{'*'}]
(chars after the =)
95 -> 94
pyramid=lambda s:[print(X)for n in range(1,len(s)+1)if{*(X:=(s+(S:=sum(range(n)))*"*")[S:S+n])}-{'*'}]
(chars after the =)
94 -> 92
pyramid=lambda s:[print(X)for n in range(len(s)+1)if{*(X:=(s+(S:=sum(range(n)))*"*")[S:S+n])}-{'*'}]
don't you have a bunch of [None, None] stuff at the end?
wdym
>>> pyramid('abcdegfhij')
a
bc
deg
fhij
[None, None, None, None]
ah
!e ```py
pyramid=lambda s:[print(X)for n in range(len(s)+1)if{(X:=(s+(S:=sum(range(n)))"")[S:S+n])}-{''}]
pyramid("abcdefghij")
@versed eagle :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | a
002 | bc
003 | def
004 | ghij
when run as a file, that wont be outputted
100 (including pyramid=) -> 56
def pyramid(s):
n=0
while s:=s[n:]:n+=1;print(s[:n])
!e ```py
def pyramid(s):
n=0
while s:=s[n:]:n+=1;print(s[:n])
pyramid("ab")
@versed eagle :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | a
002 | b
it doesnt work
why ?
.
what is the correct output ?
a
b*
okay thats no problem I will fix
it
def pyramid(s):
n=0
while s:=s[n:]:n+=1;print(f"{s[:n]:*<{n}}")
!e
def pyramid(s):
n=0
while s:=s[n:]:n+=1;print(f"{s[:n]:*<{n}}")
pyramid("ab")
@orchid nymph :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | a
002 | b*
ooo format justifying
✨
my honest reaction to looking at this code what the actual fck
@ember crown where are you from
y?
For investigation
europe
Are you my friend
huh?
You are being investigated
I think that’s just bytecode
its not
Oh. What is it?
python
😵💫I know but what is the long string
!e ```py
s = ''.join(map(chr,[23|25,22|23|24|26,22|25|26,20|21|23|25,22|23|24|26,21|22|23|25,22|23|24|26,22|25|26,20|21|23|25,20|23|25,22|23|24|25|26,23|25,22|23|24|26,20|21|23|25,22|23|24|25|26,20|22|23|25,22|23|24|25|26,20|21|22|23|25,22|23|24|25|26,22|23|24|26,21|23|25,20|23|25]))
print(s)
@gleaming linden :white_check_mark: Your 3.12 eval job has completed with return code 0.
(\d+\.\d+)|(\+|-|/|\*)
looks like a regex to me
I used python to create the best isEven() ever. Supports integers all the way up to 100 million…
you should add unit tests
maybe a test for each number?
!e ```py
import math
import zlib
def E(S, A=((65, 90),)):
def _K(R, N):
while N>0:
_D = N%100
if _D == 0:
R.append(10)
else:
R.append(_D*10 if (int(math.log10(_D))+1) == 1 else _D)
N //= 100
def _W(N, *R):
for _LL, _UL in R:
if N < _LL:
return _UL-(_LL-N-1) % (_UL-_LL+1)
elif N > _UL:
return _LL+(N-(_UL+1)) % (_UL-_LL+1)
return N
S = zlib.compress(S.encode("utf-16le"))
_B = []
_R = ""
_I = 0
while _I < len(S):
_N = S[_I]
_J = 0 if len(S) <= (_JI := _I+1) else S[_JI]
_B += [(_I, _N, _J)]
_I += 2
for _G in _B:
_F = []
_F.append(10) if _G[1] == 0 else _K(_F, _G[1])
_F.append(10) if _G[2] == 0 else _K(_F, _G[2])
_S = ""
for _N in _F:
_S += chr(_W(_N, *A))
_R += _S
return _R
print(E("H"))
print(E("Hello"))
print(E("TestHashString"))```
@sly root :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | HXRXEHFXXXHXXI
002 | HXRXEHFHXXXHXDXLXVXYLXGH
003 | HXRXYGHXXBHXBGBHFHBXHMZCXZFXECZCRCTRXRNXLRXX
eh, needs padding
0 :3
!e ```py
import zlib
def E(S, A=((65, 90),)):
def _K(R, N):
while N>0:
_D = N%100
if _D == 0:
R.append(10)
else:
R.append(_D*10 if (len(str(_D))) == 1 else _D)
N //= 100
def _W(N, *R):
for _LL, _UL in R:
if N < _LL:
return _UL-(_LL-N-1) % (_UL-_LL+1)
elif N > _UL:
return _LL+(N-(_UL+1)) % (_UL-_LL+1)
return N
S = zlib.compress(S.encode("utf-16le"))
S = zlib.crc32(S) & 0xffffffff
_R = ""
SL = len(str(S))
_M, _B = [], []
_K(_M, S)
_I = 0
while _I < len(_M):
_N = _M[_I]
_J = 10 if len(_M) <= (_JI := _I+1) else _M[_JI]
_B += [(_I, _N, _J)]
_I += 2
for _G in _B:
_F = []
_F.append(10) if _G[1] == 0 else _K(_F, _G[1])
_F.append(10) if _G[2] == 0 else _K(_F, _G[2])
_S = ""
for _N in _F:
_S += chr(_W(_N, *A))
_R += _S
return _R
print(E("H"))
print(E("Hello"))
print(E("TestHashString"))```
@sly root :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | TSBWLX
002 | HDJIPX
003 | LVWXRX
shithash
ssssh
!e ```py
import zlib
def _RD(X, W):
if W == 8:
X = ((X & 0x55) << 1) | ((X & 0xAA) >> 1)
X = ((X & 0x33) << 2) | ((X & 0xCC) >> 2)
X = ((X & 0x0F) << 4) | ((X & 0xF0) >> 4)
elif W == 16:
X = ((X & 0x5555) << 1) | ((X & 0xAAAA) >> 1)
X = ((X & 0x3333) << 2) | ((X & 0xCCCC) >> 2)
X = ((X & 0x0F0F) << 4) | ((X & 0xF0F0) >> 4)
X = ((X & 0x00FF) << 8) | ((X & 0xFF00) >> 8)
elif W == 32:
X = ((X & 0x55555555) << 1) | ((X & 0xAAAAAAAA) >> 1)
X = ((X & 0x33333333) << 2) | ((X & 0xCCCCCCCC) >> 2)
X = ((X & 0x0F0F0F0F) << 4) | ((X & 0xF0F0F0F0) >> 4)
X = ((X & 0x00FF00FF) << 8) | ((X & 0xFF00FF00) >> 8)
X = ((X & 0x0000FFFF) << 16) | ((X & 0xFFFF0000) >> 16)
else:
return 0
return X
def _C(D, N, P, C=0, RI=False, RO=False, XO=0):
G = 1 << N | P
for _D in D:
if RI:
_D = _RD(_D, 8)
C ^= _D << (N - 8)
for _ in range(8):
C <<= 1
if C & (1 << N):
C ^= G
if RO:
C = _RD(C, N)
return C ^ XO
def _A(T, M=65521):
_F, _G = 1, 0
for _C in T:
_G = (_G + (_F := (_F + _C) % M)) % M
return (_G << 16) | _F
def _K(R, N):
while N>0:
_D = N%100
R.append(10 if _D == 0 else (_D*10 if (len(str(_D))) == 1 else _D))
N //= 100
def _W(N, *R):
for _LL, _UL in R:
if N < _LL:
return _UL-(_LL-N-1) % (_UL-_LL+1)
elif N > _UL:
return _LL+(N-(_UL+1)) % (_UL-_LL+1)
return N
def E(S, A=((65, 90),), D=-1):
S = zlib.compress(S.encode("utf-16le"))
S = (((_A(S) << 64) * (_C(S, 32, 0x1EDC6F41, C=0xFFFFFFFF, RI=True, RO=True, XO=0xFFFFFFFF) << 32)) << 16) & 0xffffffffffffffffffffffffffffffff
SL = len(str(S))
_R = ""
_M, _B = [], []
_K(_M, S)
_M = _M[::D]
_I = 0
while _I < len(_M):
_N, _J = _M[_I], 10 if len(_M) <= (_JI := _I+1) else _M[_JI]
_B += [(_I, _N, _J)]
_I += 2
for _G in _B:
_F = []
_F.append(10) if _G[1] == 0 else _K(_F, _G[1])
_F.append(10) if _G[2] == 0 else _K(_F, _G[2])
_R += "".join([chr(_W(_N, *A)) for _N in _F[::D]])
return _R
print(E("H"))
print(E("Hello"))
print(E("TestHashString"))```
@sly root :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | KHXVIZHPFWBJLTNCEYBD
002 | ZQDXBXDVTFHZMPVEFXXX
003 | CXPPESFWHKXQQOPDQPFT
!e ```py
import zlib,itertools,base64,string
exec(zlib.decompress(base64.b64decode("eJyFU39rIkkQ/T+fohASurV1Z8YfeDIjmJmMTKJjGBMUZLfJJeOth6dBEy4c++G3qrpHXXfCCWJ19atXr6qfL/kSdBaJuZrJ3gXAagmzIOhSCDAPhJhfOR/ttvR9V/4wp8FA9vuu/AXRbCLCKxBhiAjvV4QTI6JVIGIHES1C5GvT0u2c9zzvWt73vHN57/Pux/4nKCcmVPeAih1CdU9VNr3fVZYp/VxtmeLPVZcp/1x92QSnU5yi6YbRbucIJzDDMclT73Mz7y5/e99twMGDDecXbJ1QRCpV9yoMHJUlQfyEJSqb2GA+CRy21TBwfT/9cY/hcrsDHcFqA5Hhxs1miQkBbwKyo46UVRx+C3Tk+yKFOtgUMxDB7mnzVy663IE/oe8HbnFA3vBKUN8jgPmGxufZxKRD7hiqlNjtdOG3+cQMOBAPahx02m3PZRodK43TKFoFCwlJyYOhwhuhhzWh4x4GcU2H8nIs8Xtgxmuzch0b/juRYWcq//f7ap1D2ncsVwQBpJeuQ50AssbT62u+eRGuQ+LpNgCHnwhwXVWTFut8I/ZvO8xIKQniGgidmSeFL18wi6zcfiZSBdWMBfA4o5EC/TiiobLD+6Tg002xRrskhNUFputp3ZVwiTIwgeeatT3/aVLoE/C8FFEixepHQv9ebGEpi7wRUwUDdG6nreAPRyqpIAqwJ5FOcUv/rVd/Np63/7zu8v1eTBv55nn7kovK+9uy7nbWeYVnJ6QQAl90KsH3odOSUMW+IdE3PQXOh3sThZ245So0hfk/0EehP4OH3XuOwcQG5OwDgOmaHs6Bv/i4cIVcy//5kKIRSipebMoidYapSoWiMT7ENZ4WXxV+KXMnKDll3Bhv9HjR60V8leCRjGJMhEefifXYel/jM+tbU6MTZDR+sRjwcTX6NoEeAhJ8AmsaxN4mxI8E11BDLUInSMRk0l4kdOEV/hmSc/S17RqzfhsfHSzZwsOF+/XExTQe7prTxkBlJV55iVeUZKSmUmn8vV1txOL5O/4VZoIEVwf4PiwxZYkx747LClNmPwG3trOm")))
s=[]
for e in itertools.combinations(string.printable, 8):
v=E(t:="".join(e))
if v in s: print("Collision at "+t+"! Hash: "+v)
s.append(v)
@vast wave :x: Your 3.12 eval job timed out or ran out of memory.
001 | Collision at 0123459G! Hash: OXGEXWRNNYLBANKVTBXD
002 | Collision at 0123459
003 | ! Hash: CHDSCCVVSPYZJGZZEYZH
004 | Collision at 012345cP! Hash: AOPKSYDHSILPLLIFHHXZ
005 | Collision at 012345c:! Hash: FHUGZXGHIDIMCSFEYRPF
006 | Collision at 012345dD! Hash: UXMNNELGPNABDJPRKGBE
007 | Collision at 012345dK! Hash: RXYTLRHNRFZHUBRYAPDI
008 | Collision at 012345fp! Hash: BRTCZZUPEWUDXYLDOYXN
009 | Collision at 012345g~! Hash: ARXAYDGRIVOTJHQMQODA
010 | Collision at 012345g
011 | ! Hash: QHDECATSOVRLICNBUUDL
... (truncated - too many lines)
Full output: unable to upload
@sly root good hash
:incoming_envelope: :ok_hand: applied timeout to @sly root until <t:1700489800:f> (10 minutes) (reason: newlines spam - sent 104 newlines).
The <@&831776746206265384> have been alerted for review.
@sly root :x: Your 3.12 eval job timed out or ran out of memory.
001 | KHXVIZHPFWBJLTNCEYBD
002 | ZQDXBXDVTFHZMPVEFXXX
003 | CXPPESFWHKXQQOPDQPFT
lmao
!unmute 467290739219496960
:incoming_envelope: :ok_hand: pardoned infraction timeout for @sly root.
oopsie
it's funny that bot still evaluated the provided code
lmao
ok i see the problem
Does the datetime library default to GMT?
it defaults to not being tz aware
you should basically always use datetime.now(UTC) (after importing both from datetime)
absolutely love the result
before
def _K(R, N):
while N>0:
_D=N%100
R.append(10 if _D==0 else(_D*10 if(len(str(_D)))==1 else _D))
N//=100
after
_K=lambda R,N:[(R.append(10if(_D:=N%100)==0else(_D*10 if(len(str(_D)))==1else _D)),(N:=N//100))for i in iter(lambda:N>0,0)]
!e ```py
import zlib
_RD=lambda X,W:((((X:=(((X:=((X&0x55)<<1)|((X&0xAA)>>1))&0x33)<<2)|((X&0xCC)>>2))&0x0F)<<4)|((X&0xF0)>>4))if W==8 else(((((X:=(((X:=(((X:=((X&0x5555)<<1)|((X&0xAAAA)>>1))&0x3333)<<2)|((X&0xCCCC)>>2))&0x0F0F)<<4)|((X&0xF0F0)>>4))&0x00FF)<<8)|((X&0xFF00)>>8))if W==16 else(((((X:=(((X:=(((X:=(((X:=((X&0x55555555)<<1)|((X&0xAAAAAAAA)>>1))&0x33333333)<<2)|((X&0xCCCCCCCC)>>2))&0x0F0F0F0F)<<4)|((X&0xF0F0F0F0)>>4))&0x00FF00FF)<<8)|((X&0xFF00FF00)>>8))&0x0000FFFF)<<16)|((X&0xFFFF0000)>>16))if W==32 else 0))
_K=lambda R,N:[(R.append(10 if(_D:=N%100)==0 else(_D*10 if(len(str(_D)))==1 else _D)),(N:=N//100))for i in iter(lambda:N>0,0)]
_W=lambda N,*R:next((_UL-(_LL-N-1)%(_UL-_LL+1)if N<_LL else(_LL+(N-(_UL+1))%(_UL-_LL+1)if N>_UL else N)for _LL,_UL in R),None)
def E(S, A=((65, 90),), D=-1, O=152):
S=zlib.compress(S.encode("utf-16le"))
_AF,_AG=1, 0
for _AC in S:
_AG=(_AG+(_AF:=(_AF+_AC)%(_AM:=65521))%_AM)
_AS=(_AG<<16)|_AF
_CC=0xFFFFFFFF
_CG=1<<(_CN:=32)|0x1EDC6F41
for _CD in S:
_CD=_RD(_CD,8)
_CC^=_CD<<(_CN-8)
for _ in range(8):
_CC<<=1
if _CC&(1<<_CN):
_CC^=_CG
_CC=_RD(_CC,_CN)
_CO=((_CON:=_CC^0xFFFFFFFF)+((_COH:=_CON)<<6)+(_COH<<16)-_COH)
S=(((_AS<<64)*(_CO<<32))<<16)&((1<<((O//4)*4))-1)
SL=len(str(S))
_R,_M,_B="",[],[]
_K(_M,S)
_M=_M[::D]
_I=0
while _I<len(_M):
_N,_J=_M[_I], 10 if len(_M)<=(_JI:=_I+1)else _M[_JI]
_B+=[(_I,_N,_J)]
_I+=2
for _G in _B:
_F=[]
_F.append(10)if _G[1]==0 else _K(_F,_G[1])
_F.append(10)if _G[2]==0 else _K(_F,_G[2])
_R+="".join([chr(_W(_N, *A))for _N in _F[::D]])
return _R
print(E("H"))
print(E("Hello"))
print(E("TestHashString"))
@sly root :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | FLMXWFYCSXSLOGLNPXUICEXD
002 | IQCCMQYJACGLHLQVIRWGCPXF
003 | TEMZHVHQXOLVRFRJJZKJLTXL
I see
So it defaults to utc?
no
So when i print datetime.now() what timezone is it outputting?
i made a rather silly one-liner
move_right = lambda board: (c := (lambda b: [[0]*row.count(0)+list(filter(lambda x: x, row)) for row in b]))([sum([[0, row[i]*2] if row[i] == row[i+1] else [row[i], row[i+1]] for i in range(0, len(row), 2)], []) for row in c(board)])
!e
board = [
[2, 2, 2, 2],
[0, 0, 4, 0],
[0, 2, 0, 2],
[2, 8, 0, 4]
]
move_right = lambda board: (c := (lambda b: [[0]*row.count(0)+list(filter(lambda x: x, row)) for row in b]))([sum([[0, row[i]*2] if row[i] == row[i+1] else [row[i], row[i+1]] for i in range(0, len(row), 2)], []) for row in c(board)])
print(move_right(board))
@candid light :white_check_mark: Your 3.12 eval job has completed with return code 0.
[[0, 0, 4, 4], [0, 0, 0, 4], [0, 0, 0, 4], [0, 2, 8, 4]]
Does that mean it does local time?
if you want local time use dt.astimezone()
!e
try:
x = ([1, 2], )
x[0] += [3, 4]
except TypeError:
print(x)
@strange basin :white_check_mark: Your 3.12 eval job has completed with return code 0.
([1, 2, 3, 4],)
I’m allowed to modify a list inside a tuple, but not the tuple itself, so it fails, but the tuple is still modified … 🤔
From what I've read, it's because the += is roughly analogous to py res = x[0].__iadd__([3, 4]) x[0] = res
and that second part causes the error, while the iadd worked inplace like normal. So it works fine if you just do that manually
!e py x = ([1, 2], ) x[0].__iadd__([3, 4]) print(x)
@fleet lintel :white_check_mark: Your 3.12 eval job has completed with return code 0.
([1, 2, 3, 4],)
!e even simpler:
!e py x = ([1, 2], ) a = x[0] a += [3, 4] print(x)
@fleet bridge :white_check_mark: Your 3.12 eval job has completed with return code 0.
([1, 2, 3, 4],)
No need for pytz?
!e
def whackysyntax[whatthe: lambda what=[]: what.append(what) or what](on_earth: whatthe):
print(ohmy:=len(whatthe.__bound__())) or ohmy < on_earth and whackysyntax(on_earth) and whackysyntax(on_earth)
whackysyntax(5)
@craggy hamlet :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 1
002 | 2
003 | 3
004 | 4
005 | 5
this new typing change is crazy
lmao
!e
thing = lambda x: id(x)
print(thing(123))
@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.
140436999413864
@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.
139634242637928
i've fixed collisions so it isn't that bad now
from typing import Any, Callable
Method = type(
"Method",
(),
{
"__init__": lambda s, f, o: [setattr(s, "f", f), setattr(s, "o", o), None][-1],
"__call__": lambda s, *a, **k: s.f(s.o, *a, **k)
}
)
def method(self: Any, *args) -> Method:
def wrapper(func: Callable[Any, ...]) -> Any:
return func(self, *args)
return wrapper
class Foo:
def __new__(cls):
return super().__new__(cls)
def func(self) -> None:
print(self.x)
@method((obj := Foo()), 1)
def __init__(self, x: int) -> None:
self.x = x
obj.func()```
Not sure if this counts as esoteric, i would call it cursed instead
!e
from typing import Any, Callable
Method = type(
"Method",
(),
{
"__init__": lambda s, f, o: [setattr(s, "f", f), setattr(s, "o", o), None][-1],
"__call__": lambda s, *a, **k: s.f(s.o, *a, **k)
}
)
def method(self: Any, *args) -> Method:
def wrapper(func: Callable[Any, ...]) -> Any:
return func(self, *args)
return wrapper
class Foo:
def __new__(cls):
return super().__new__(cls)
def func(self) -> None:
print(self.x)
@method((obj := Foo()), 1)
def __init__(self, x: int) -> None:
self.x = x
obj.func()```
@sick hound :white_check_mark: Your 3.12 eval job has completed with return code 0.
1
You don't use Method anywhere, do you? o.O
!e like this does the same thing, doesn't it?
method = lambda s, *a, **k: lambda f: f(s, *a, **k)
class Foo:
def func(self):
print(self.x)
@method((obj := Foo()), 1)
def __init_or_whatever__(self, x):
self.x = x
obj.func()
@restive void :white_check_mark: Your 3.12 eval job has completed with return code 0.
1
id is the address
!e
fib: print(__import__("functools").reduce(lambda x, y: (x[0]+x[1], x[0]), [(1,1)]*(fib-2))[0])=8
@craggy hamlet :white_check_mark: Your 3.12 eval job has completed with return code 0.
13
tested a bit and found out that O=152 still has 2 collisions every 4140 hashes
!e ```py
import zlib
_RD=lambda X,W:((((X:=(((X:=((X&0x55)<<1)|((X&0xAA)>>1))&0x33)<<2)|((X&0xCC)>>2))&0x0F)<<4)|((X&0xF0)>>4))if W==8 else(((((X:=(((X:=(((X:=((X&0x5555)<<1)|((X&0xAAAA)>>1))&0x3333)<<2)|((X&0xCCCC)>>2))&0x0F0F)<<4)|((X&0xF0F0)>>4))&0x00FF)<<8)|((X&0xFF00)>>8))if W==16 else(((((X:=(((X:=(((X:=(((X:=((X&0x55555555)<<1)|((X&0xAAAAAAAA)>>1))&0x33333333)<<2)|((X&0xCCCCCCCC)>>2))&0x0F0F0F0F)<<4)|((X&0xF0F0F0F0)>>4))&0x00FF00FF)<<8)|((X&0xFF00FF00)>>8))&0x0000FFFF)<<16)|((X&0xFFFF0000)>>16))if W==32 else 0))
_K=lambda R,N:[(R.append(10 if(_D:=N%100)==0 else(_D*10 if(len(str(_D)))==1 else _D)),(N:=N//100))for i in iter(lambda:N>0,0)]
_W=lambda N,R:((R[1]-(R[0]-N-1)%(R[1]-R[0]+1)if N<R[0]else(R[0]+(N-(R[1]+1))%(R[1]-R[0]+1)if N>R[1]else N)),None)[0]
D = 1 / -1 (default: -1)
O in [41, 2^16) (default: 64)
O*3 is the upper limit
O is the hash constant width
def E(S, A=(65, 90), D=1, O=64):
S=zlib.compress(S.encode("utf-16le"))
_AF,_AG=1,0
[_AG:=(_AG+(_AF:=(_AF+_AC)%(_AM:=65521))%_AM)for _AC in S]
_AS=(_AG<<16)|_AF
_CC,_CG=0xFFFFFFFF,1<<(_CN:=32)|0x1EDC6F41
for _CD in S:
_CC^=(_CD:=_RD(_CD,8))<<(_CN-8)
[(_CC,(_CC:=_CC<<1),(_CC:=_CC^(_CG if _CC&(1<<_CN)else 0)))for _ in range(8)][-1]
_CO=((_CON:=(_CC:=_RD(_CC,_CN))^0xFFFFFFFF)+((_COH:=_CON)<<6)+(_COH<<16)-_COH)
S=((_SN:=((((_AS<<64)(_CO<<32))<<16)<<8)&((1<<(((O3)//4)4))-1)),(_SW:=O),(int((str(_SN)((_SW//len(str(_SN)))+1))[:_SW])),(int(_SN*(10**(_SW-len(str(_SN)))))))[2]
_I,_R,_M,_B=0,"",[],[]
_K(_M,S)
_M=_M[::D]
while _I<len(_M):
_N,_J=_M[_I],10 if len(_M)<=(_JI:=_I+1)else _M[_JI]
_B+=[(_I,_N,_J)]
_I+=2
for _G in _B:
_F=[]
_F.append(10)if _G[1]==0 else _K(_F,_G[1])
_F.append(10)if _G[2]==0 else _K(_F,_G[2])
_R+="".join([chr(_W(_N,[*A]))for _N in _F[::D]])
return _R
print(E("H"))
print(E("Hello"))
print(E("TestHashString"))```
@sly root :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | LTFXNENIKTHOJRAWPHXBGCUYXEBYXLTF
002 | XXUBAUTYOZBJAAAYCCHUHEKLQJMZRXXU
003 | AVXNCBBKVNNQHKRSPUTPGHLHXRIJAAVX
!rule paid
Thank you so much for simplifying it
When i come with ideas of pointless codes, i write them too fast without thinking of a shorter way
I made these which I thought were cool (same idea)
#esoteric-python message
#esoteric-python message
!e ```py
def qr(data):
for i in data:i[0]=i[0]+i[1]%(1<<8)-1;i[3]=((i[3]^i[0])<<(1<<4)|(i[3]^i[0])>>(1<<4))%(1<<8)-1;i[2]=i[2]+i[3]%(1<<8)-1;i[1]=((i[1]^i[2])<<12|(i[1]^i[2])>>20)%(1<<8)-1;i[0]=i[0]+i[1]%(1<<8)-1;i[3]=((i[3]^i[0])<<(1<<3)|(i[3]^i[0])>>((1<<5)-(1<<3)))%(1<<8)-1;i[2]=i[2]+i[3]%(1<<8)-1;i[1]=((i[1]^i[2])<<7|(i[1]^i[2])>>25)%(1<<8)-1
#i basically gave up at this point
def flatten(input):
new_list = []
for i in input:
for j in i:
new_list.append(j)
return new_list
def hash(data):
data=data.encode()
x = [[data[i4], data[i4+1], data[i4+2], data[i4+3]] for i in range(len(data)//4)]
qr(x)
x= flatten(x)
return bytes(x)
print(hash("hello"))``` @sly root
@unique heath :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 19, in <module>
003 | print(hash("hello"))
004 | ^^^^^^^^^^^^^
005 | File "/home/main.py", line 17, in hash
006 | return bytes(x)
007 | ^^^^^^^^
008 | ValueError: bytes must be in range(0, 256)
!e ```py
def qr(data):
for i in data:i[0]=i[0]+i[1]%(1<<8)-1;i[3]=((i[3]^i[0])<<(1<<4)|(i[3]^i[0])>>(1<<4))%(1<<8)-1;i[2]=i[2]+i[3]%(1<<8)-1;i[1]=((i[1]^i[2])<<12|(i[1]^i[2])>>20)%(1<<8)-1;i[0]=i[0]+i[1]%(1<<8)-1;i[3]=((i[3]^i[0])<<(1<<3)|(i[3]^i[0])>>((1<<5)-(1<<3)))%(1<<8)-1;i[2]=i[2]+i[3]%(1<<8)-1;i[1]=((i[1]^i[2])<<7|(i[1]^i[2])>>25)%(1<<8)-1;i[0]%=(1<<8)-1;i[1]%=(1<<8)-1;i[2]%=(1<<8)-1;i[3]%=(1<<8)-1
return data
hash = lambda x:(data:=x.encode(),bytes(import("itertools").chain.from_iterable(qr([[data[i4], data[i4+1], data[i4+2], data[i4+3]] for i in range(len(data)//4)]))))[1]
print(hash("banana"))```
@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.
b'\xc1\xfek\xfe'
there we go
its not great because it truncates every char >trunc(len(data)/4)*4
but it works
looks nice
the thing is that i spent more time to make a wrapping function and making hashes to be the same length than writing the hash itself
_K=lambda R,N:[(R.append(10 if(_D:=N%100)==0 else(_D*10 if(len(str(_D)))==1 else _D)),(N:=N//100))for i in iter(lambda:N>0,0)]
_W=lambda N,R:((R[1]-(R[0]-N-1)%(R[1]-R[0]+1)if N<R[0]else(R[0]+(N-(R[1]+1))%(R[1]-R[0]+1)if N>R[1]else N)),None)[0]

i
unironically
looked at
a real
fucking
hash
(okay pseudorandom block-function but who cares)
lmao
(well, and modified it)
(a lot)
i've replaced the while and the last for-loop with list comprehensions:
before
while _I<len(_M):
_N,_J=_M[_I],10 if len(_M)<=(_JI:=_I+1)else _M[_JI]
_B+=[(_I,_N,_J)]
_I+=2
for _G in _B:
_F=[]
_F.append(10)if _G[1]==0 else _K(_F,_G[1])
_F.append(10)if _G[2]==0 else _K(_F,_G[2])
_R+="".join([chr(_W(_N,[*A]))for _N in _F[::D]])
after
[((_B:=_B+[(_I,_M[_I],(10 if len(_M)<=(_JI:=_I+1)else _M[_JI]))]),(_I:=_I+2))for _ in iter(lambda:_I<len(_M),0)]
[((_F:=[]),(_K(_F,100 if _G[1]==0 else _G[1])),(_K(_F,100 if _G[2]==0 else _G[2])),(_R:=_R+"".join([chr((A[1]-(A[0]-_N-1)%(A[1]-A[0]+1)if _N<A[0]else(A[0]+(_N-(A[1]+1))%(A[1]-A[0]+1)if _N>A[1]else _N)))for _N in _F[::D]])))for _G in _B]
i know i can do like 10if 100if and 0else but i won't because of the nasty SyntaxWarnings
cool
currently looking at SIPHASH rn
me when i look at real fucking hashes for a shitpost:
i love flattening with recursive generator functions
!e
def is_iterable(obj):
try:
for _ in obj:
return True
except:
return False
def flatten(iterable):
for item in iterable:
if is_iterable(item):
yield from flatten(item)
else:
yield item
print(list(flatten([1,[2,[3]],[4,[[[6]]]]])))
@karmic pumice :white_check_mark: Your 3.12 eval job has completed with return code 0.
[1, 2, 3, 4, 6]
!e
import json
def flatten(iterable):
return json.loads(f"[{json.dumps(iterable).replace('[','').replace(']','')}]")
print(flatten([1,[2,[3]],[4,[[[6]]]]]))
@restive void :white_check_mark: Your 3.12 eval job has completed with return code 0.
[1, 2, 3, 4, 6]
why json when you can just use list?
What do you mean?
why are you using json module, can't you just use list instead?
No. I could use str() I guess instead of the json.dumps.
oh wait yeah
but yes dumps could be replaced
!epy import json def flatten(i): return json.loads(f'[{str(i).replace('[','').replace(']','')}]') print(flatten([1,[2,[3]],[4,[[[6]]]]]))
@arctic skiff :white_check_mark: Your 3.12 eval job has completed with return code 0.
[1, 2, 3, 4, 6]
So can loads realistically
it could just be eval
!e
import json
def flatten(i):
return [int(n.replace(' ','').replace('[','').replace(']', '')) for n in f"[{str(i).replace('[','').replace(']','')}]".split(",")]
print(flatten([1,[2,[3]],[4,[[[6]]]]]))```
@serene stratus :white_check_mark: Your 3.12 eval job has completed with return code 0.
[1, 2, 3, 4, 6]
!e
def flatten(i):
return [int(filter(str.isalnum, n).__next__()) for n in f"[{str(i).replace('[','').replace(']','')}]".split(",")]
print(flatten([1,[2,[3]],[4,[[[6]]]]]))```
@serene stratus :white_check_mark: Your 3.12 eval job has completed with return code 0.
[1, 2, 3, 4, 6]
!e I don't understand what about this doesn't work py flatten=lambda l:eval(f"[{str(l).replace('[','').replace(']','')}]") print(flatten([1,[2,[3]],[4,[[[6]]]]]))
@fleet lintel :white_check_mark: Your 3.12 eval job has completed with return code 0.
[1, 2, 3, 4, 6]
!e ```py
flatten=f=lambda l:[l]if type(l)is int else sum(map(f,l),[])
print(flatten([1,[2,[3]],[4,[[[6]]]]]))
@versed eagle :white_check_mark: Your 3.12 eval job has completed with return code 0.
[1, 2, 3, 4, 6]
obviously its not generalised — but neither is string handling
since it cant handle brackets inside elements of the list
is there a way to make everything 'exist'
So if I would use a global variable that doesnt exist, I still make it return something predefined?
yes
how would I do this
!e ```py
import ctypes
class blogals(dict):
slots = ()
def getitem(s, i, __g=dict.getitem):
if i in s:
return __g(s, i)
if i in builtins.dir():
return __g(builtins.dict, i)
return i
ctypes.py_object.from_address(id(globals()) + 8).value = blogals
print(hello, world)
@versed eagle :white_check_mark: Your 3.12 eval job has completed with return code 0.
hello world
hello and world are undefined variables here
you can change the value that gets returned by changing the return i at the end there
is it always +8 I see that pop up a lot
i is the name of the variable^^
8 is the offset of ob_type in the PyObject struct
what this does is hook the type of the globals dictionary object
so that it has a custom lookup method
!e 2 shorter by switching to and-or py flatten=f=lambda l:type(l)is int and[l]or sum(map(f,l),[]) print(flatten([1,[2,[3]],[4,[[[6]]]]]))
@fleet lintel :white_check_mark: Your 3.12 eval job has completed with return code 0.
[1, 2, 3, 4, 6]
To the weirdos in #esoteric-python, I call upon your terrible wisdom to help me with this problem
Im trying to import a custom module to iterate over a file and file variables, but its iterating over itself after its run and its causing an error.
#__main__
c = __file__
print(c)
import game
a=1
b=1
print(a,b)
print(game.var_or_not(f"{c}") )
#game
def var_or_not(f):
if __file__ != f:return
vars = []
with open(f,'r') as f:
a = f.read()
a = a.split("\n")
t=1
for i in a:
while t:
try:
print(i)
exec(i)
except NameError as e:
vars.append(str(e).split("'")[1])
else:
t=0
continue
t=1
return vars
If you can use other imports, there isn't a reason to mess around with exec ```py
a.py
import inspect
def test():
calling_frame = inspect.stack()[1][0].f_globals
return calling_frame```
# b.py
import a
b = 1
c = 1
print(a.test())```
result of running `b.py`: ```
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000249D06F1D50>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\\Users\\user\\PycharmProjects\\test\\b.py', '__cached__': None, 'a': <module 'a' from 'C:\\Users\\user\\PycharmProjects\\test\\a.py'>, 'b': 1, 'c': 1}
there was a reason why i didnt use and-or but i dont remember what it is
oh right
originally the int wasnt in a list and i wanted to avoid the case where it gets 0 and tries to iterate through it
forgot to change it back lol
Guys I think I found a new standard we should use for storing constants in python, should I open a PEP for it?
class ConstantContainer:
def __init__(depth=999):
if depth == 0:
self.__CONSTANT1 = 1
self.__COSNTANT2 = 2
self._is_leaf = True
return
self._is_leaf = False
self.__whatthefuck = ConstantContainer(depth-1)
@property
def CONSTANT1():
if self.is_leaf:
return self.__CONSTANT1
else:
return self.__whatthefuck.CONSTANT1
This is genius, try modifying these constants mother f'er
!e ```py
t=type("t",(object,),{"init":lambda s:setattr(s,"d",[0]*1000),"getitem":lambda s,k:s.d[hash(k)%1000],"setitem":lambda s,k,v:s.d.setitem(hash(k)%1000,v)})
mydict = t()
mydict["x"] = 4
print(mydict["x"])``` my attempt at making a terrible hash table
@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.
4
someconst = ... # pretend i constructed a thingy here
while not someconst._is_leaf:
someconst = someconst._ConstantContainer__whatthefuck
someconst._ConstantContainer__CONSTANT1 = "something else"
i might have messed up the name mangling but whatever
i love this
!e ```py
t=type("t",(object,),{"init":lambda s:setattr(s,"d",[0]*1000),"getitem":lambda s,k:s.d[hash(k)%1000],"setitem":lambda s,k,v:s.d.setitem(hash(k)%1000,v)})
m = t()
m["x"] = 4
print(hash("x"), m[hash("x")])
@versed eagle :white_check_mark: Your 3.12 eval job has completed with return code 0.
-3785526288850116233 0
!e ```py
t=type("t",(object,),{"init":lambda s:setattr(s,"d",[0]*1000),"getitem":lambda s,k:s.d[hash(k)%1000],"setitem":lambda s,k,v:s.d.setitem(hash(k)%1000,v)})
m = t()
m["x"] = 4
print(hash("x"), m[hash("x")])
@versed eagle :white_check_mark: Your 3.12 eval job has completed with return code 0.
940446694651980887 4
there we go
string hashes being random makes it not always work, but
hash collision :3
!e
_ENV = [([exec, eval]),('hello', 50, 20, "+", "="),]
_ENV[0][0](f"{_ENV[1][0]}{_ENV[1][4]}{_ENV[0][1](f'{_ENV[1][1]}{_ENV[1][3]}{_ENV[1][2]}')}")
print(hello)
@sick reef :white_check_mark: Your 3.12 eval job has completed with return code 0.
70
Anyone wanna expand on that.
I got no more ideas.
Maybe encode _ENV[1] table, it holds the constants for the most part.
cmon thats really not that hard
should at least contain 5 more bitshifts
Give me ideas.
^
!e ```py
_ENV = [([exec, eval]),('hello', ((1<<5)-(1<<(1<<2))+(1<<((1<<2)-(1<<0)))+(1<<0))<<1, (1<<5)-(1<<4)+(1<<3)-(1<<2), "+", "="),]
_ENV[0]0
print(hello)```
@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.
70
wish granted
!e ```py
_ENV = [([exec, eval]),('hello', ((1<<5)-(1<<(1<<2))+(1<<((1<<2)-(1<<0)))+(1<<0))<<1, (1<<5)-(1<<4)+(1<<3)-(1<<2), chr((((1<<5)-(1<<(1<<2))+(1<<((1<<2)-(1<<0)))+(1<<0))<<1)-((1<<3)-(1<<0))), chr((((1<<5)-(1<<(1<<2))+(1<<((1<<2)-(1<<0)))+(1<<0))<<1)+(1<<3)+(1<<0)+(1<<1))),]
_ENV[0]0
print(hello)``` some more wish-granting
@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.
70
!e
import LoneDruid
print(LoneDruid.int_to_eso(1)
!e
import LoneDruid
print(LoneDruid.int_to_eso(1))
right now my brain is fucked
How da faq did u do that
its exec
(assuming they're both signed integers, and b is positive)
a >> b = ⌊ a / 2ᵇ ⌋
a << b = a * 2ᵇ (you dont need to floor or ceil since integers are closed under multiplication :3)
hopefully that helps
you gotta think in binary
so
lets say your number is 111 in binary
bit shifting to the left << adds a 0 to the end in binary
111₂ << 1 = 1110₂ (the ₂ means its in base-2, ₁₀ means in base-10)
in base 10 (decimal, the one you're most likely used to using unless you aren't a human, which is unlikely), given 7, bit shifting to the end would multiply by 10
7₁₀ << 1₁₀ = 70₁₀
with the same logic, if you do it in binary, a left bit shift would multiply by 2**n (like how base-10 would multiply by 10**n)
right shift is the same, however it just removes a digit from the left
why are you using subscripts to denote base
its standard practice?
no
usually one either says which base you're using, or leaves it up to context
using subscripts doesnt actually disambiguate at all because the the subscript is in an undenoted base
How would you know which he means if he's using them both?
For example, (100)10 is equivalent to 100 (the decimal system is implied in the latter) and represents the number one hundred, while (100)2 (in the binary system with base 2) represents the number four
In a positional numeral system, the radix (pl.: radices) or base is the number of unique digits, including the digit zero, used to represent numbers. For example, for the decimal system (the most common system in use today) the radix is ten, because it uses the ten digits from 0 through 9.
In any standard positional numeral system, a number is c...
ignore the (100)10 parts, its formatting issues in copy paste
It's very common to use subscripts, it's commonly known that this is in base 10 as it's made for us humans to understand it
i see it a lot in maths things
either context or they would say which base they're using
you dont notate it, because thats just as ambiguous
you just say the base
e.g., [binary], [decimal], ...
In any standard positional numeral system, a number is conventionally written as (x)y with x as the string of digits and y as its base
@versed eagle
why are you pinging
the y is subscripted in the (x)y part but formatting stuff so ignore that
literally in wikipedia
you already said that, no need to repeat yourself :p
:p
not a reason to ping me?
and that's just plainly false
Lol why are being such a prick, he was trying to help you and you're complaining about a totally normal notation
wut
how?
conventionally, numbers are written without a base denotation
?
how am i complaining
and how were they trying to help me
we're just having a conversation??
Notation An integer 𝑎
written in base 𝑏
expansion is denoted by (𝑎)𝑏
(subscript b) https://math.libretexts.org/Bookshelves/Combinatorics_and_Discrete_Mathematics/Elementary_Number_Theory_(Raji)/01%3A_Introduction/1.04%3A_Representations_of_Integers_in_Different_Bases
4₁₀ = 100₂, 5₁₀ = 101₂, 6₁₀ = 1102, 7₁₀ = 111₂
https://mathcircle.berkeley.edu/sites/default/files/handouts/2017/Maleva_BMC.pdf
do i need to continue?
what are you trying to do here
to show that using subscripts is indeed a standard way to express base
it is a somewhat standard way, yes
i never denied that
i just said that its not the most helpful or widespread
.
confsue
what you're saying is true, but irrelevant to what i said
so im confused about why you're bringing it up
okay were both confused
what does that mean
So thirsty to correct people about pointless shit smh
It absolutely is a standard way to notate bases, not ambiguous at all
what does that mean
i never said its not standard
and it is ambiguous
.
it is mostly assumed the subscript is in base 10
in a case where it isn't it'll probably be explicitly specified by a base 10 number subscript as well
true, but its not any less ambiguous
if it doesn't do this then it's not standard
you are correct, but its still not any less ambiguous than the undenotated number is
a more general assumption is that undenoted usually means decimal (base 10) which should include subscripts
e.g. 111₂ <<1 = 1110₂
in the end it's how the human processes it
it's a bit like saying writing 987 is ambiguous because it can be interpreted in any base
it's convention to have the subscript be in decimal, so it's not ambiguous
the convention is to interpret ambiguous things in a specific way
however, there exist other, equally valid ways of interpreting it, meaning that it is still ambiguous
and this is why context is important
that is what i said earlier
context determines which things are more proper to interpret than others
that is what i said
the general context interprets undenoted numbers as base 10
there isn't a context here where using a base other than decimal in the subscript is fine unless you explicitly say so otherwise
that is true for most contexts, yes
the specific context interprets numbers with a subscripted undenoted (base 10 from general context) number as numbers with a base specified by the subscript
it would be ambiguous if there were other conventions as to what base the undenoted numbers in subscript are in, like how N can be ambiguous because different definitions can include or exclude 0
but there isn't, so it's not ambiguous
do you mean ℕ?
yes
why didnt you say that then
convention is just that: convention
it doesnt remove ambiguity
Convention
A practice or procedure widely observed in a group
(widely observed) ≠ (universally observed)
this conversation isnt going anywhere i think
it would be annoying for me to fetch that unicode symbol, and it was obvious enough that you figured it out anyways without me doing that
it doesn't have to be universally observed to not be ambiguous
someone can always disagree with convention
it wasnt obvious enough
if it was, i wouldnt have had to ask for clarification
that doesn't make everything suddenly ambiguous
it doesnt. the notation itself is ambiguous. all im saying is that the convention does not make that ambiguity go away
it just sweeps it under the rug
hence making it go away
no
its still there, just ignored
i never said that we are?
i am confused about what you mean by that
anyway,
if you were given the notation (110)_10 with no other context or any knowledge of what the conventional way to write in that notation is, then sure, it would be ambiguous to you whether that was in binary, decimal, or some other base
in the current context, where it is widely accepted that the number in the base is in decimal, it wouldn't be ambiguous as to whether the base is in decimal or not, because it's conventionally in decimal
sure, you could point out that you can technically treat the number in the base as binary or some other base, but that doesn't make the situation in the general context ambiguous because there is one clear and widely used way to treat the number in the subscript
just like how sqrt(x) is not ambiguous: you could technically define it to be the negative root, but it is widely accepted that it refers to the positive root, so you aren't being ambiguous when you use sqrt(x) to refer to the positive root
now you're reiterating things that have already been said
like i said, this conversation isnt progressing at all.
i may have caused a war um oops
Thanks : D
what do you mean?
Guys using python i want to scrape a url, basically its tiktok product link
im not able to scrape it, can anyone help?
I decided to start writing blog posts about the weird stuff I do with python, the first one i wrote is about fishhook: https://chilaxan.github.io/python/2023/11/24/developing-fishhook please lmk if anyone thinks i should add anything else
Fishhook was one of my first major low level python projects. I set out with the goal to make an easy to use, dynamic python dunder hooking tool, similar to forbiddenfruit. However, I wanted to improve on the methods used in forbiddenfruit, where many of the offsets and details were hard coded.
or if there are any typos
@quartz wave ^ you might like the read, it has some details about the first version of fishhook
ooo
not really typos but I would think it's more readable if you use caps for names such as Python, CPython, ...
This is quite a lot of work to keep track off but personally I would think it's a big improvement
in your about there's a typo, "names" -> "name's" or "name is"
but honestly "I'm ..." would be better
I just fixed those typos and capitalizations, thanks
Really interesting, thanks!
is there a way to hook call operator of an every declared function using fishhook?
doing @hook(type(lambda:0)) doesn't work
that would break a lot of things, even your hook
hmm, it kinda works
i guess interpreter bypasses function.__call__ method and directly executes func.__code__ with provided args
the same thing happens with __getattribute__ of magic methods
@fleet bridge is correct, the interpreter bypasses the call dunder on function objects. I wrote some code a while ago to get it working but it required losing a ton of functionality, and still barely worked
I'll see if I can find the code or rewrite it
okay, thanks for info
i'm currently trying to do it using the c api
plus to avoid immutable variables like builtins and types
i think you can make subclass of FuncionType and hope that interpreter will not ignore overriden .__call__
FunctionType is marked as final in C, so to subclass it you should 1) unlock it 2) subclass it 3) lock it back
and then optionally change type of all existing functions (except for your hook, probably)
not sure if it will work at all
// Get the hook target dict
if ((hook_target_dict_proxy = PyObject_GetAttrString(hook_target, "__dict__")) == NULL) {
PyErr_SetString(PyExc_AttributeError, "Hook target doesn't have the __dict__ table");
Py_DECREF(hook_target);
return NULL;
}
hook_target_dict = PyDict_New();
hook_target_dict_proxy = ((_Hooky_PyDict_MappingProxyObject*)hook_target_dict_proxy)->mapping;
PyObject *key, *value;
Py_ssize_t pos = 0;
while (PyDict_Next(hook_target_dict_proxy, &pos, &key, &value)) {
_Hooky_PyObject_Print("%R %R %zu\n", pos, key, value);
}
throws a segfault lmao
still cannot convert mappingproxy to dict even though i have the underlying struct
ay0ks@fedora:...snip...$ lldb python Hooky.py
(lldb) target create "python"
Current executable set to '/usr/bin/python' (x86_64).
(lldb) settings set -- target.run-args "Hooky.py"
(lldb) run
Process 33391 launched: '/usr/bin/python' (x86_64)
Process 33391 stopped
* thread #1, name = 'python', stop reason = signal SIGSEGV: address not mapped to object (fault address: 0x9)
frame #0: 0x00007ffff7a258e9 libpython3.12.so.1.0`PyObject_Repr + 57
libpython3.12.so.1.0`PyObject_Repr:
-> 0x7ffff7a258e9 <+57>: movq 0x8(%rbx), %rax
0x7ffff7a258ed <+61>: movq 0x58(%rax), %r13
0x7ffff7a258f1 <+65>: testq %r13, %r13
0x7ffff7a258f4 <+68>: je 0x7ffff7934f2f ; PyObject_Repr.cold + 68
(lldb)
a
it's because of print
even though addresses are not null
0x7ffff7de2480 0x7fffe9f5b880 1
0x7ffff7de2900 0x7fffe9f5b8d0 2
0x7ffff7de1bf0 0x7fffe9f5b920 3
0x7ffff7de2e30 0x7fffe9f5b970 4
0x7ffff7de1a60 0x7fffe9f5b9c0 5
0x7ffff7de2240 0x7fffe9f5ba10 6
0x7ffff7de2100 0x7fffe9f5ba60 7
0x7ffff7de1848 0x7fffe9f5bab0 8
0x7ffff7de2420 0x7fffe9f5bb00 9
0x7ffff7de1bc0 0x7fffe9f5bb50 10
0x7ffff7de19c8 0x7fffe9f5bba0 11
0x7ffff7de2058 0x7fffe9f5bbf0 12
0x7ffff7de2318 0x7fffe9f5bc40 13
0x7ffff7de2a18 0x7fffe9f5bc90 14
0x7ffff7de2130 0x7fffe9f5bce0 15
...
(a lil bit of offtop but still esoteric)
fixed
while (PyDict_Next(hook_target_dict_proxy, &pos, &key, &value)) {
_Hooky_PyObject_Print("%R %R %zu\n", key, value, pos);
}
if you can grab the addresses of _PyEvalFramePushAndInit and _PyEvalFramePushAndInit_Ex you might be able to get it to work with fishhook.asm
well actually the version that has been released probably won't work
but with those addresses you could patch the asm
okay will try
this sounds like a lot of handwaving around type checking without real practical benefit
but lke why
hey, dont ping random people at 6am
from datetime import datetime
from dateutil.relativedelta import relativedelta
_PARTS = (
("years", "y"),
("months", "mo"),
("weeks", "w"),
("days", "d"),
("hours", "h"),
("minutes", "m"),
("seconds", "s"),
)
def duration(
time_x: datetime, time_y: datetime, min: bool = False, weeks: bool = False
) -> str:
"""String representation of the duration between `time_x` and `time_y`."""
start, end = sorted((time_x, time_y))
delta = relativedelta(end, start)
return " ".join(
f"{num}{' '*(min^1)}{s if min else (z[:-1] if num==1 else z)}"
for z, s in _PARTS
if (z != "weeks" or weeks)
and (num := getattr(delta, z) - ((z == "days") & weeks) * 7 * delta.weeks)
)
print(duration(datetime.utcnow(), datetime.utcfromtimestamp(1691975673)))
this should be accurate and count dst and differences in month lengths, unlike the divmod approach
how can i golf https://code.golf/prime-numbers#python beyond this
||for i in range(1,98):print(i)if 2**i%i==2or i==2else 0||
thats the best i can get it (54 bytes)
||don't use a for loop based on my 48b one||
40b is one hell of a task
ikr
i was thinking that but idk how wait dont tell me
||i got 45 with a for loop||
||i'm yet to discover that||
a (mild) hint, if any of you want it: ||De Morgan's Laws||
im gonna go to sleep now
someone ping me if something interesting happens please :3
That's very cool!
How to ensure you stay hired at your current job:
I couldn't think of this all yesterday, and finally
if (PyType_Check(hook_target)) {
PyDict_SetItemString(PyType_GetDict((PyTypeObject*)hook_target), hook_function_name, hook_function);
}
now it works even for immutable types
@hook(str)
def __call__(self, *a, **b):
print(self, a, b)
@hook(type(lambda: 0))
def unwrap(self, *a, **b):
print(self, a, b)
str.__call__(123,123)
print((lambda: 0).unwrap)
outputs
123 (123,) {}
<bound method unwrap of <function <lambda> at 0x7f44a0b1a200>>
Oh this reminds me that I need to work on my bytecode hacks to handle function types
my previous attempt
if ((hook_target_dict = PyObject_GetAttrString(hook_target, "__dict__")) == NULL) {
PyErr_SetString(PyExc_AttributeError, "Hook target doesn't have the __dict__ table");
Py_DECREF(hook_target);
return NULL;
}
hook_target_dict = ((_Hooky_PyDict_MappingProxyObject*)hook_target_dict)->mapping;
PyObject *temp_key, *temp_value;
Py_ssize_t position = 0;
while (PyDict_Next(hook_target_dict, &position, &temp_key, &temp_value)) {
if (PyUnicode_Compare(temp_key, PyUnicode_FromString(hook_function_name)) == 0) {
hook_target_original_function = PyFunction_New(
_Hooky_PyFunction_Get_Code(temp_value),
_Hooky_PyFunction_Get_Globals(temp_value)
);
break;
}
}
// ...
||i got 44b with both for loop and no for loop||
||43 again with both ways||
if (PyType_Check(hook_function)) {
PyObject* class_dict = PyType_GetDict((PyTypeObject*)hook_function);
PyObject *method_name, *method;
Py_ssize_t position = 0;
while (PyDict_Next(class_dict, &position, &method_name, &method)) {
if (!PyFunction_Check(method))
continue;
_Hooky_HookFunction(hook_target_dict, method, method_name);
}
}
@hook(str)
class str_hooks:
def print(self, *a, **b):
print(self)
print(str.print)
print("".print)
"123".print()
outputs
<function str_hooks.print at 0x7faff4801300>
<bound method str_hooks.print of ''>
123
>>> @hook(int)
... def __or__(self, *a,**b):
... print(self,a,b)
...
>>> 1|2
3
>>> 1|3
3
strange
!e ```py
from fishhook import *
@hook(int)
def or(self,*a,**b):
print(self,a,b)
1|2
@sly root :warning: Your 3.12 eval job has completed with return code 0.
[No output]
1|2 gets evaluated at compile time before your hook
here it works because you are compiling 1|2 after hook
it doesn't*
it works pretty clearly
!e ```py
from fishhook import *
@hook(int)
def or(self,*a,**b):
print(self, a, b)
compile("1|2", "", "exec")
@vast wave :white_check_mark: Your 3.12 eval job has completed with return code 0.
1 (2,) {}
yea working with constant numbers and fishhook is always going to behave interestingly, because the compile time optimizations happen before fishhook can init hooks
!e ```py
from fishhook import *
@hook(int)
def or(self,*a,**b):
print(self, a, b)
A = 1
B = 2
print(A|B)
@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 1 (2,) {}
002 | None
oh wait its not working with your hook for dunders?
you need to make sure your changes propagate to the slot functions
fishhook does this now by toggling flags and taking advantage of internal plumbing, but it would prob be easier to implement similarly to how I did if for v1 https://github.com/chilaxan/fishhook/blob/2859cef28ece63aa31d4a6456bd9610a7bed03fa/fishhook/__init__.py#L178-L181
fishhook/__init__.py lines 178 to 181
ocls_ptrs = getptrs(cls, slotdata)
pcls_ptrs = getptrs(pcls, slotdata)
for optr, pptr in zip(ocls_ptrs, pcls_ptrs):
optr.value = pptr.value```
@rugged sparrow is there a way to hook like list for example to print something everytime one is created?
gimme 5, i think so
You can hook different C-API functions to get code called when a given object is allocated, but it would be type specific, no generic way
*you could do something really nuts and install a malloc hook that records the memory allocated, and then installs a trace function to run on the next python frame that checks if the memory allocated has a type by then and if that type is the desired one to hook allocs of

!e ```py
from fishhook.asm import *
@hook(pythonapi.PyList_New, argtypes=[c_ssize_t], restype=py_object)
def list_new(size):
print('Requested List:', size)
return pythonapi.PyList_New(size)
x = list((1,2,3))```
@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.
Requested List: 0
@low lynx ^
(it says requested list 0) because list literals are allocated as empty, then appended to
I'm not talking about fishhook, the first example is the my own library, which does not work
yea but the thing is that the slot functions are scattered around in the PyTypeObject
like the __call__ is PyTypeObject->tp_call, but changing it doesn't do anything
the way I'm doing it is
static void _Hooky_HookFunction(PyObject* dict, PyObject* function, PyObject* function_name) {
if (PyDict_Contains(dict, function_name)) {
PyObject* original_function = PyDict_GetItem(dict, function_name);
PyObject* original_function_name;
if ((original_function_name = PyObject_GetAttrString(original_function, "__qualname__")) == NULL) {
PyErr_SetString(PyExc_AttributeError, "Original function doesn't have the __qualname__ attribute");
Py_DECREF(original_function);
return;
}
PyDict_SetItem(_Hooky_PatchedDict, original_function_name, original_function);
}
PyDict_SetItem(dict, function_name, function);
}```
and then
```c
hook_target_dict = PyType_GetDict((PyTypeObject*)hook_target);
// ...
_Hooky_HookFunction(hook_target_dict, hook_function, hook_function_name);
i guess i'd need to make a method table and do hook name checking
nice
thx
You need to update slot caches as well. Also, for FunctionType objects, tp_call is unused, it just moves straight to execution of the code object
static inline bool _Hooky_PyProperty_Check(PyObject* object) {
if (!PyFunction_Check(object)) {
if (PyObject_HasAttrString(object, "fget") || PyObject_HasAttrString(object, "fset") ||
PyObject_HasAttrString(object, "fdel")) {
return true;
}
}
return false;
}
class properties are so strangely designed
they're functions in the python code
but they are not in the c api
anyways now hooking properties works
Hello All,
I've a problem with the collections.namedtuple class.
In a nutshell, the string representation of the created class doesn't show up when the object is recalled. Propeties are accessible when recalled.
Expect some omiissions from the code I put together on the fly :
class Test:
def __init__(self, raw):
self.colunns = ['X', 'Y', 'Z']
self.row = collections.namedtuple("Row", self.columns)
self.append(raw)
def append(raw):
for row in raw:
row = row.copy()
dimensions = dict(zip(self.dimensions, row.pop("keys", [])))
res = self.row(**dimensions, **row)
self.rows.append(res)
x = Test(myrawdata)
x.rows
>>> [Row(page='https://ww...sition=18), <Row, len() = 5>]
See below a screenshot too
Any idea of what's getting wrong? The cose used to work in 3.9 if I'm not mistaken
just looks to me like vsc is doing its own special handling there
~~I got the same on ptpython .. so either there is a bug somehow with 3.12 .. or I don't know where to look at 😦
Actually not ... I replicated on ptpython and it seems to work there.
It's a Visual Studo code issue with the variable browser that is skrewing up
@plush halo :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/snekbox/user_base/lib/python3.12/site-packages/fishhook/fishhook.py", line 151, in force_setattr
003 | flags, should_have_null_tp_dict = unlock(cls)
004 | ^^^^^^^^^^^
005 | File "/snekbox/user_base/lib/python3.12/site-packages/fishhook/fishhook.py", line 65, in unlock
006 | cls_mem = allocate_structs(assert_cls(cls))
007 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
008 | File "/snekbox/user_base/lib/python3.12/site-packages/fishhook/fishhook.py", line 47, in allocate_structs
009 | allocate_structs(subcls)
010 | File "/snekbox/user_base/lib/python3.12/site-packages/fishhook/fishhook.py", line 48, in allocate_structs
011 | for offset, size in get_structs():
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/XRDLAZZU6YW33BTS2OYYDWOE4U
@rugged owl :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 14, in <module>
003 | print(~object)
004 | ^^^^^^^
005 | TypeError: bad operand type for unary ~: 'type'
@rugged owl :white_check_mark: Your 3.12 eval job has completed with return code 0.
Mutable[S]
@rugged owl :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 17, in <module>
003 | print(type(some_var))
004 | ^^^^^^^^^^^^^^
005 | File "/lang/python/default/lib/python3.12/typing.py", line 2220, in get_type_hints
006 | raise TypeError('{!r} is not a module, class, method, '
007 | TypeError: 0 is not a module, class, method, or function.
I feel like if anything, ~i32 should mean "everything except i32"
sorry this was supposed to be in bot commands
🤦♂️
how can I golf project euler 187 further: https://projecteuler.net/problem=187?
||l=[2]+[n for n in range(3,10**8+1)if 2**n%n==2];print(len(set(i*j for j in l for i in l)))||
A website dedicated to the fascinating world of mathematics and programming
||set comp||
||unpack operator||
||l=[2]+[n for n in range(3,10**8+1)if 2**n%n==2];print(len({i*j for j in l for i in l}))||
||where should I put the unpack||
||near the l=||
does this work? fermat should have some counterexamples in that range
especially since there's at least 1 charmichael number in there
!e
n = 3*11*17
print(n)
print(2**n%n)
@low lynx :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 561
002 | 2
probably not but its unbearably slow because its unoptimized for golfing reasons
a = 1
b = -a
c = --a
print(b)
print(c)
-(-a)
!eval
a = 1
b = -a
c = --a
print(b)
print(c)
@boreal spindle :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | -1
002 | 1
⚠️ Advent of Code day 1 part 2 spoiler ⚠️
Does anyone see a way to get this code golfed in less characters?
||py sum([int(''.join([c for c in __import__("functools").reduce(lambda a,kv:a.replace(kv[0],kv[0]+str(kv[1])+kv[0]),[("one",1),("two",2),("three",3),("four",4),("five",5),("six",6),("seven",7),("eight",8),("nine",9)],line)if 58>ord(c)>47][e]for e in(0, -1)))for line in open("i").readlines()])||
look at #1180008645384216606
cheers
and move there as well if you want to discuss aoc golfs
Here's a challenge, especially for golfers: https://oskaerik.github.io/theevalgame/
(I have a gist with my solution, but it can definitely be shortened)
this feels like the password game
oh it loaded
i don't understand rule 8
it is literally ||delete a file||
I got to rule 10 and decided I didn't feel like replacing all my stuff
how would you delete a file from a Python program?
some command thing or pathlib
idk i don't do that sorta stuff
what
i was confused by that too. "Committing" usually mean creating a file.
Someone told me to check the working directory and that made me figure it out.
Still stuck on rule 10 though.
No, but it helps finding the solution.
what the fuck
this is "esoteric" python!
It's enough to call your custom print function from the other rule.
mine is much longer, 1400 or so. Can you give a link to yours?
is the pastebin fine?
sure
slick
this is running in 32-bit is it?
you can shave a few off that it looks like.
i don't know if you want to hear what I did to remove 7 chars
this is esopy i'm sure i can handle it
||change "print:=lambda:print(()for()in())" to "print:=lambda:b,print()"||
idk how they are determining that you called it.
maybe the ast?
oh right forgot i don't need another
yeah they're checking if the Call with print is a subtree of the code's ast
you can see the rules by doing open('src/rules.py','r').read()
fucking hell
it's cooler this way
Only fair after getting asked to delete files.
down to 265c 267b with this
||```py
(b:=().class.base.subclasses().getitem({()for()in()}.sizeof()+(n:=-~'滝'.sizeof())).init.globals.getitem('builtins').getitem,print:=lambda:print(),b('import')('os').remove('password.txt'),C:=b('type')('C',(),{}))and-~n
pop in place of getitem
[(i,(_p:=lambda*x:print(*x)),(_p(i))) for i in [41+1]][0][0] fails at rule 5
a, it should be named print?
lmao
popping leads to very weird behaviour because the state of python remains the same
it's very weird
It's safe to pop after subclasses, because that makes a new list every time. Not after globals though.
here's two equivalent 257c's with that
||```py
(b:=().class.base.subclasses().pop({()for()in()}.sizeof()+(n:=-~'滝'.sizeof())).init.globals.getitem('builtins').getitem,print:=lambda:print(),b('import')('os').remove('password.txt'),C:=b('type')('C',(),{}))and-~n
```py
(f:=().__class__.__base__.__subclasses__().pop({()for()in()}.__sizeof__()+(n:=-~'滝'.__sizeof__())).__init__.__globals__,b:=f.__getitem__('__builtins__').__getitem__,print:=lambda:print(),f.__getitem__('remove')('password.txt'),C:=b('type')('C',(),{}))and-~n
bottom one tries to use the fact that the function we're grabbing from is from the os module to save characters on the import, but it miraculously breaks even||
that's all i'm doing, someone else can come up with a better golf/optimize that one if they want
I haven't investigated this. Sounds like a loophole in theevalgame: https://mastodon.social/@christmastree/111505679603046225
Content warning: Spoiler for rule 10
it is a loophole, but it isn't what they thought
__builtins__ and (...)
works as well
it's because the game, when checking rule 10, runs the code separately with __builtins__ set to {}, but doesn't actually check that the result is 42
the eval is in a try: except:, so if builtins are used it'll raise an exception and you won't pass the rule, but if you just have __builtins__ and (...), python just only evaluates __builtins__, which is falsy, and then terminates
here's a 133c with that loophole
__builtins__ and'瀧'.__sizeof__()+sum(len({print:=lambda:_})for _ in(print(),exec('import os;os.remove("password.txt")\nclass C:""')))
[s:=next(g:=(g.gi_frame.f_back.f_back.f_back for()in[()])).f_locals['self']]+[setattr(s,k,object)for(k)in dir(s)if'ru'in k]
``` 123 chars, but does not follow the spirit of the game too much
Yep, 42 alright.
it works by using a generator get a reference to the parents frame, and then replacing every rule_* function with object (which is truthy when called)
sometimes you forgot things exist https://macropy3.readthedocs.io/en/latest/
any of you here uses that sort of macro library in python ?
surprisingly hylang has a its own tiny macro level model
129c
why not put the os stuff in the class def ```py
builtins and'瀧'.sizeof()+sum(len({print:=lambda:_})for _ in(print(),exec('class C:import os;os.remove("password.txt")')))
oh that makes sense
I forgot it still runs the code in the class body
Hi all,
Let's say that I have a set or a list - still have to decide - with a variable number of dictionary inside (say up to 25K rows), and the length of these dictionary is variable itself, on average 30 items.
What could be the best way to find the longest dictionary?
A for ... next it's indeed memory/time consuming.
well it can't be a set because dictionaries aren't hashable
Good point ... so a list it will be
are you looking for a serious answer? if so, this is probably not the right channel