#esoteric-python
1 messages ยท Page 24 of 1
!e exec(type((lambda:0).__code__)(0, 0, 0, 0, 1, 0, b'\x97\x00t\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00d\x02\xa6\x01\x00\x00\xab\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00d\x00S\x00', ("hi chat",), ("print",), (), "", "", "", 0, b"", b""))
@vast wave :warning: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
[No output]
hm
You will get it 
i'm just fucking around at this point, i know what i did wrong in the first place
i found this online ๐ญ
fun
btw the aoc code golfs are available again for a short period of time
so if any of you guys want to archive certain golfs, now's the time to go grab them
fun
Golfing brainf looks fun
i would rather walk all the way down to africa and back than to golf brainfuck again
?
!e This can likely be shorter```py
p="++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."
s=[i:=0];c=''
for o in p:c+=' '*i+[f'i+=1\n{" "i}if i>=len(s):s+=[0]','i-=1','s[i]+=1','s[i]-=1','print(end=chr(s[i]))','s[i]=ord(import("sys").stdin.read(1))','while s[i]:','s','']['><+-.,['.find(o)]+'\n';i+=(92-ord(o))(o in'][')
exec(c)
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello World!
That one has an unlimited stack size, which is atypical so it can be shortened by removing that feature too
this is the shortest "alphabet" that i could come up with which could still do everything that normal python could do
.__()nameldgtribusc
got a shorter one
.__()excmhrlnasd
shorter one
()exlchrbo+~
iirc, brainfuck officially is meant to have a stack size of 30000
You can reduce python 2 to exc"%=\n and python 3 to exc"%0()
hey guys
open(0).readlines()
is just for esoteric codes or is common to see them in normal codes i hope you can get my question
that reads from stdin until it reads an EOF
python isnt bad
Lol i made a script that draws trees for you wherever you click
i think you're a bit lost
this is not the channel you're looking for
this is for esoteric python
Yes, I know, but I was playing with it and I didn't like it for certain things (recursive stuff in particular). Here is a better optimized version:
p="++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."
s=[i:=0]*30000;c=''
for o in p:c+=' '*i+['i+=1','i-=1','s[i]+=1','s[i]-=1','print(end=chr(s[i]))','s[i]=ord(open(0).read(1))','while s[i]:','s','']['><+-.,['.find(o)]+'\n';i+=(92-ord(o))*(o in'][')
exec(c)
rewriting it as a join might be shorter
I need to try it
here is that:
p="++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."
s=[i:=0]*30000
exec(''.join(' '*i+['i+=1','i-=1','s[i]+=1','s[i]-=1','print(end=chr(s[i]))','s[i]=ord(open(0).read(1))','while s[i]:','s','']['><+-.,['.find(o)]+(0*(i:=i+(92-ord(o))*(o in']['))or'\n')for o in p))
prob longer
@quartz wave might want to take a look at this
https://github.com/brain-lang/brainfuck/blob/master/brainfuck.md#:~:text=single%2C unsigned 8-bit number does yours follow this spec?
and each cell is an unsigned 8bit digit
no but I could fix it pretty easy by appending ;i=i%256
and stopping negative numbers is more tricky
i=(i or 0)%256
!e py print(-1%256)
@rugged sparrow :white_check_mark: Your 3.11 eval job has completed with return code 0.
255
Oh yeah I don't need to worry about it
ya
let me go back to the one that has an unlimited stack
p="++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."
s=[i:=0];c=''
for o in p:c+=' '*i+[f'i+=1\n{" "*i}if i>=len(s):s+=[0]','i-=1','s[i]+=1','s[i]-=1','print(end=chr(s[i]))','s[i]=ord(open(0).read(1))','while s[i]:','s','']['><+-.,['.find(o)]+';s[i]%=256\n';i+=(92-ord(o))*(o in'][')
exec(c)
should work as intended
cereal has a collection
of brainfuck interpreters
thats wayyyy too verbsoe
yeah it's fairly verbose
but the idea is more how they do it, not how short it is
it's easy up shorten once you've gotten a good idea working
afaik this is working and follows the spec
anyway im gonna go back to being a sleeping gremlin since im not supposed to be awake rn
gn
gn
Noice
Now if you can make it autogenerate structure definitions that would be cool
Is there any specific reason that range implements a count method? Won't the result always be 0 or 1?
| count(...)
| rangeobject.count(value) -> integer -- return number of occurrences of value
i think its part of the Sequence abc
that checks out
!e
from collections.abc import Sequence
print(Sequence.count.__doc__)
@solid basalt :white_check_mark: Your 3.11 eval job has completed with return code 0.
S.count(value) -> integer -- return number of occurrences of value
also no
count is equality, not identity. That optimization can't be made
!e
class Foo:
def __eq__(self, other):
return True
r = range(100)
print(r.count(Foo()))
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
100
there is actually a fast path for bool / int exact items though, in that case it returns 1 or 0 without iterating the whole thing
What other stuff are there that would be fun to golf?
lots of things you could golf
for example a function that calculates the nth digit of pi in decimal
oh super interesting case
I was only thinking in terms of counting ints
yeah I had an idea before to optimize (float) in range() comparison before
since it took a very long time to return False, but apparently you can't just optimize it because someone may have a custom object that is equal to one of the range elements and therefore in is true
at what?
i didn't know i had that
why is Sequence a keyword
discord has very bad highlighting rules
Don't blame Discord directly, blame highlight.js developers
They don't fix issues with individual lexers
import ctypes
globals_type=ctypes.py_object.from_address(id(globals())+8)
class new_globals(dict):
__slots__=()
def __getitem__(self,name,bound1=dict,globals_type=globals_type):
try:
globals_type.value = bound1
combinators = {
'S': lambda x:lambda y:lambda z:x(z)(y(z)),
'K': lambda x:lambda y:x,
}
if name[0] in locals()['self'] or name[0] in combinators:
result=combinators[name[0]]
for combinator in name:
if combinator in combinators:
result=result(combinators[combinator])
elif combinator in locals()['self']:
result=result(locals()['self'][combinator])
else:
return self[name]
return result
return self[name]
finally:
globals_type.value=__class__
globals_type.value = new_globals
I = SKK
U = SII
U(print) # <built-in function print>
print(I(1)) # 1
SKI combinator calculus
(heavy inspiration from this channel)
why locals()['self']?
name lookup is builtins -> locals -> globals, so it intuitively should work
but I haven't tested myself
Not quite
It's locals, enclosed, globals, builtins
Builtins is the last thing that's checked, not the first
7.13. The nonlocal statement
nonlocal_stmt ::= "nonlocal" identifier ("," identifier)*
``` The [`nonlocal`](https://docs.python.org/3/reference/simple_stmts.html#nonlocal) statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.
Names listed in a [`nonlocal`](https://docs.python.org/3/reference/simple_stmts.html#nonlocal) statement, unlike those listed in a [`global`](https://docs.python.org/3/reference/simple_stmts.html#global) statement, must refer to pre-existing bindings in an enclosing scope (the scope in which a new binding should be created cannot be determined unambiguously).
yes i'm aware
Why __class__ variable is not compiled to LOAD_CONST <class 'Foo'> ?
Because class must be places in co_consts tuple at method creation time, and at this moment class doesn't exist
Thank you
What is esosteric python? Can someone give a summary?
I would describe it as "anything that goes deliberately and shamelessly against the grain of mainstream python programming"
also the channel topic I guess
well it's not really a constant
it's sort of like a cell / closure variable
Python/compile.c lines 1745 to 1754
/* Cook up an implicit __class__ cell. */
int res;
assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
res = PyDict_SetItem(u->u_cellvars, &_Py_ID(__class__),
_PyLong_GetZero());
if (res < 0) {
compiler_unit_free(u);
return 0;
}```
i know, but i dont know any case where you want to change value __class__ variable
it just can't be known at the time when constants are compiled
it cant be known ever can it?
you sort of build the function code first, then you can find out if it is in a class
cause class in subclasses is the subclass
I don't think so
!e
class Foo:
def abc(self):
print(__class__)
class SubFoo(Foo):
pass
SubFoo().abc()
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
<class '__main__.Foo'>
cause the whole rationale behind not allowing Self in staticmethods atleast for me was that you couldnt ever have it always return the enclosing class
maybe im just misremembering though
you can very easily, it's just not statically inferable
when a class method returns a cls() instance the type checkers can infer the Self type
Yeah but I thought I ran this test for staticmethods and just normal methods and concluded that since there was no way to access the current enclosing class in a staticmethod, there was no way that Self would ever work (inheritance wise)
I'm trying to load the thread I had for the pep but discord is being bad and is just hanging
well i have no idea ig its just lost to time, i dont particularly want to go through the comment history of https://docs.google.com/document/d/1ujuSMXDmSIOJpiZyV7mvBEC8P-y55AgSzXcvhrZciuI/edit#
why is there a big ร in the middle of the docs file
idk people must have just messed with it after finding it on typing-sig
@gleaming linden have u ever heard of clash of code?
well here is coode golf game mode
it is cool
it is kinda like leet code
questions
but who can do it in least amount of code
join up
๐
done
t,s=map(int,open(0))
print(t*s//60)
print(int((int(input()) / 60)*int(input())))
open(file, mode='r', buffering=- 1, encoding=None, errors=None, newline=None, closefd=True, opener=None)```
Open *file* and return a corresponding [file object](https://docs.python.org/3/glossary.html#term-file-object). If the file cannot be opened, an [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError "OSError") is raised. See [Reading and Writing Files](https://docs.python.org/3/tutorial/inputoutput.html#tut-files) for more examples of how to use this function.
*file* is a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object) giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed unless *closefd* is set to `False`.)
how could you use for inputs?
oh
didn't know that
that's smart
@gleaming linden wanna go again
sure
I need to learn pyth
@gleaming linden how do u do it
print(sum((n*3, n*5)[n%2] for n in [int(input()) for _ in range(int(input()))]))
[1:] to get rid of the first one
I came up with a 56 in the first minute lol
๐ฆ
something like ```py
_,*n=map(int,open(0))
print(...)
22c lol
it would be like 2-3c in pyth
yup same
@gleaming linden samething again
yup
print(1000-int(input())*2)
can't do 1e3 because floats
ya
are there any harder ones?
ah, sad
oof
how about a normal one then?
what's this
clash of code
why does co_consts contain None when None isn't used in the function?
seems like a waste of space
!e e.g.
f = lambda: "not None"
print(f.__code__.co_consts)
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
(None, 'not None')
I suspect so the compiler doesn't need to figure out all paths where you implicitly return
ah
fair
however, for a lambda that shouldnt be necessary?
since afaik lambdas have no way of implicitly returning
just not super worth it in general, extra None reference is just 8 bytes
!e
def test():
return "hi"
print(test.__code__.co_consts)
@calm loom :white_check_mark: Your 3.11 eval job has completed with return code 0.
(None, 'hi')

for a single function, yeah
hm python always inserts None as the default return value whether u explicitly provide a return or not
thats cool
it shouldnt be necessary for lambda functions though
yeh
could be possible to remove it for lambdas, yeah
funny reason
wait nvm im thinking of the wrong null
this is why
im sure none finds a way into lambdas as well
wait nevermind lambdas don't have a none anywhere
you're right
weird
!e
from einspect import view
f = lambda: "not none"
view(f.__code__.co_consts).remove(None)
print(f())
print(f.__code__.co_consts)
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | not none
002 | ('not none',)
apparently still works if you remove the None from the tuple
hm?
!e ```py
from einspect import view
f = lambda: "not none"
view(f.code.co_consts).remove(None)
print(eval(f.code))
print(f.code.co_consts)
@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | not none
002 | ('not none',)
the fuck
yeah no that shouldnt work
!e ```py
from einspect import view
f = lambda: "not none"
target = f.code.replace(co_consts=("not none",))
print(target.co_consts)
print(eval(target))
@vast wave :x: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
('not none',)
yeah
pretty sure that the fields on a code object are just for show, the actual value is cached
.replace() makes a new code object with the given params tho, that's why the previous one didn't segfault but this one did
oh wait no
the None did get removed, it still works because it's accessing the memory at index 1 which isn't freed
I guess there is no check for the size of co_const and they directly access the memory at index 1
so if we try to access None in that function it will be the string at index 0
undefined behavior 
!e
from einspect import view
f = lambda: "not none" + None
view(f.__code__.co_consts).remove(None)
print(f())
print(f.__code__.co_consts)
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | not nonenot none
002 | ('not none',)
might just be accessing the memory that used to be there
i guess
using einspect might what fucks this one up
directly killing the pointer to None but not killing the reference to "not none" still being where it was before
well, I follow what list does, when you pop items it doesn't deallocate the memory
so you can technically unpop a list by reverting ob_size back
!e
from einspect import view
ls = [1, 2, 3]
ls.pop()
ls.pop()
print(ls)
with view(ls).unsafe() as v:
v.size += 2
print(ls)
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | [1]
002 | [1, 2, 3]
!e ```py
import base64 as b
import zlib, dis
exec(zlib.decompress(b.a85decode(b'GhRjND/\,^&H88.@I[c#g,'7UKdK\B9p>8Yp5L6=4s-o]O@6?^;"ltC^2@u>m8>1kND9D(SAsPCO=*&dQJm'Y1jFiNQJJE=3U%mZu"Ci:?nII@+$fL8M,4)X=Ii5@AB%?)"iqga95;[4R/>D4lF).3IC2#75AstE59.#=+N"[DC\\]e&3[>!\\IZA%9f!k,)Q#g4J@AYBB&*Zs3:RT1i9>V"=LThTt)"e_hnH1No:8\'3rSEbc^8eGP*\'/S=(/D4g=1="&l;-a%QQK8:LJ^5.Qh:^F:Z=Vds/Mdi7oBGpm0nh,A+5bu=>7^BK'Psr7hL0PQ0,>"m&^Q"pIPB6@k-^%9eg!<8O]]>jBMeW^jPdaa".5ZG^CfUBPX1%b6<#$2a[3C+AkWS8R2nr%bf-p#b4A;Gi]kZUr#5#X#s^"Ja$Xh[I;Nn4EEra5,M2T"]!.Wn^H+:23'l-0um&Pmu"7AhC/bNBMP/g?1TGH2ho0hneV5$&Co<JR$TLal-W&e\U+sHV<6n=hqW;8KHOMlRB\R9!b;;p2<RuY@6?::usu@CN9F-3R]n'8P2\/:,XQKk6.MLdt@9DZU;V);8Tlhn8>/bE+Ra;B9et_)@hFTuK1RP;bG0fp,pD_[6l(rU;Li1QA.UB%d!i;!0(nHkDuJ1,LR(r\8KVQ[Lg?9Y=:0t::,P"PJMVQik:=7\1D;@.tn3:C^nP20@YCUsTD1gB$e0Qd7gW4I\LrHJkPD'@]-MSOkbT'eNKh4G#U@[XT%GjDNh7r[n#tDXa!n3ojE'^HDF&gQNHs=rH3K1Qle3+F.6/is=8U(i@R&t[(E8HUEDVjQT6+!-_Ci1-Un;#Z/ALfB=RFnQ>"&Hh&7@=5raeikW/&61!hi0=TLZX8&W)c`),')A(#VF(o5ku:n)FHV&q"Z)f]V;B_>24^U"I%7#"16n8eXj+b2?M(^T&iJ5-@*c"@HS4i8U%kS".pqkjjK@.66JL-K\q-V4')))
a = Assembler()
nc = a.consts_create_or_get
i = a.insn
i("RESUME",0)
i("LOAD_CONST", nc("not null"))
i("RETURN_VALUE")
co = a.pack_code_object()
print(co.co_consts)
dis.dis(co)
print(eval(co))
@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | ('not null',)
002 | 0 RESUME 0
003 | 2 LOAD_CONST 0 ('not null')
004 | 4 RETURN_VALUE
005 | not null
its possible to not have none in it
well yeah if you manually provide the bytecode
but it might negatively affect speed to have that work in the compiler
at that point just accept that its 1 byte
8 bits
no wait im stupid
fuck i need to retake comp sci
I suppose it could be 8 bits if we have 8 bit python ๐
IIRC the first value in co_consts is the docstring
!e
def x():
"""test"""
print(x.__code__.co_consts)
@sudden osprey :white_check_mark: Your 3.11 eval job has completed with return code 0.
('test', None)
Not sure
if it's None, it just shouldnt be present
It seems like the function object relies on it being there to set it's __doc__ https://github.com/python/cpython/blob/0a22aa0528a4ff590854996b8854e9a79120987a/Objects/funcobject.c#L157
Objects/funcobject.c line 157
PyObject *consts = code_obj->co_consts;```
Sort of makes sense, and I guess a slight optimization over a separate field on the code object since it can be shared if the func uses none
I guess, yeah, although afaict lambda functions aren't really special cased so the actual objects are the same as normal function/code objects.
Is there even any way of telling the difference other than the name 
yeah you're right
that's fixed in some version in 3.12
oh nice
it doesn't actually remove the first thing
The compiler now removes all unused constants from code objects (except the first one, which may be a docstring).
ok maybe not
i'm gonna go test
yep
i'm gonna add a path in my modified cpython for that
fixed ```diff
-
// The first constant may be docstring; keep it always. -
index_map[0] = 0;
-
// If it's a docstring, keep it. -
index_map[0] = PyUnicode_Check(PyList_GET_ITEM(consts, 0)) ? 0 : -1;
>>> from dis import dis
>>> dis("lambda:2")
0 0 RESUME 0
1 2 LOAD_CONST 0 (<code object <lambda> at 0x000001C93A4F7220, file "<dis>", line 1>)
4 MAKE_FUNCTION 0
6 RETURN_VALUE
Disassembly of <code object <lambda> at 0x000001C93A4F7220, file "<dis>", line 1>:
1 0 RESUME 0
2 LOAD_CONST 0 (2)
4 RETURN_VALUE
Won't that break docstrings? When the function object is created how does it know if the first value is the docstring or not?
PyUnicode_Check checks if it's a string
doesn't seem to break ```pycon
def abc():
... """
... doc
... """
...
abc.code.co_consts
('\n\tdoc\n\t', None)
If there's no docstring, but you return a string
Won't that string be set as the docstring?
getting started on esoteric, its pretty fun ๐
!e
f = lambda c, n: (lambda np: (exec(compile(c, "<string>", "exec"), np), np[n]))({})[1]
code = """
def fn():
print("hello, world")
"""
fn = f(code, "fn")
fn()```
@kindred stone :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello, world
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Hello world lol
002 | 12345
a = 2
b = 3
c = 4
a, b, c *= 2 # a => 4, b => 6, c => 8
Cell In[4], line 1
a, b, c *= 2 # a => 4, b => 6, c => 8
^
SyntaxError: 'tuple' is an illegal expression for augmented assignment
the fact that this fails makes me sad
i get why but
???!
0 size augmented assignment 
!e
, *= 2
@languid hare :x: Your 3.11 eval job has completed with return code 1.
001 | File "/home/main.py", line 1
002 | , *= 2
003 | ^
004 | SyntaxError: invalid syntax
@languid hare :x: Your 3.11 eval job has completed with return code 1.
001 | File "/home/main.py", line 1
002 | (,) *= 2
003 | ^
004 | SyntaxError: invalid syntax
@languid hare :x: Your 3.11 eval job has completed with return code 1.
001 | File "/home/main.py", line 1
002 | () *= 2
003 | ^^
004 | SyntaxError: 'tuple' is an illegal expression for augmented assignment
ok fair enough
!e so that means ```py
from einspect import view
a = lambda: "big boobs"
v = view(a.code.co_consts)
del v[:]
v.extend(["the cat", "big boobs"])
print(a.code.co_consts)
print(a.doc)
@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
None
no it doesn't
sadge
!e ```py
from einspect import view
a = lambda: "big boobs"
v = view(a.code.co_consts)
del v[:]
v.extend(["the cat", "big boobs"])
print(a.code.co_consts)
print(a.doc)
@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | ('the cat', 'big boobs')
002 | None
.__doc__ is not dynamic
Yes. It is set once at function creation time, and you can set it to other value after function is created
def create_function(code_string: str, var_to_extract: str):
code = compile(code_string, "<string>", "exec")
namespace = {}
exec(code, namespace)
return namespace[var_to_extract]
its just a different way of executing code, similar to eval
Hi there it's my first time posting on here but I was wondering if someone could help me with Pytorch specifically
Esoteric Python request:
Find a way to override the assignment operator (=) by any means neccesary. Be it modification of the locals dictionary or some runtime hooking. Preferably portable (i.e work when passed between function calls and stack frames). By overriding I mean detecting an assignment and even prevent it, so for example
x=5
# override
x=4
print(x) # -> 5
!e ```py
x = 4
ั
= 5
print(x)
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
4
easy
sneaky boi
(legit)
alr give me like an hour
ill be able to get on my computer then
i don't wanna type on mobile
from types import CodeType
from sys import _getframe, exit
import dis
orig = _getframe().f_code
code = orig.co_code
payload = list(code)
allow_assign = True
for idx, op in enumerate(code):
if op == dis.opmap["STORE_NAME"] and orig.co_names[code[idx+1]] == "x":
if allow_assign:
allow_assign = False
else:
payload[idx] = dis.opmap["POP_TOP"]
exec(orig.replace(co_code=bytes(payload[176:])))
exit(0)
# Everything after this is the input code
x = 5
x = 4
print(x)
Works on my machine
@lunar marsh
That works, could adapt it into a tracer function to make it work between frames I suppose.
!e
import ast
import inspect
import sys
from functools import cache
class Final:
def __new__(cls, obj):
stack = inspect.stack(1)
c_stack = stack[1:]
c_frame_info = c_stack[0]
c_frame = c_frame_info.frame
def _trace(frame, _event, _arg= None):
info = inspect.getframeinfo(frame)
node = ast.parse(info.code_context[0].strip())
if isinstance(node.body[0], ast.Assign):
raise SyntaxError(f"cannot assign to final variable {obj!r}")
return _trace
cls._enable_trace()
c_frame.f_trace = _trace
return obj
@cache
@staticmethod
def _enable_trace() -> None:
if not sys.gettrace():
sys.settrace(lambda *args: None)
x = Final(100)
print(x)
x = 5
print(x)
@dry mirage :x: Your 3.11 eval job has completed with return code 1.
001 | 100
002 | Traceback (most recent call last):
003 | File "/home/main.py", line 32, in <module>
004 | x = 5
005 | ^
006 | File "/home/main.py", line 32, in <module>
007 | x = 5
008 | ^
009 | File "/home/main.py", line 17, in _trace
010 | raise SyntaxError(f"cannot assign to final variable {obj!r}")
011 | SyntaxError: cannot assign to final variable 100
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/otigivotuw.txt?noredirect
(Ignoring the disregard for instruction opcodes and arguments >:( )
I like it, have not seen code_context before
you also have access to the caller dictionary
so you can check if x is bound to anything else via eval exec globals() and error as well
Though this will fail when ran in the REPL right?
the f_trace usage is pretty smart
I've seen it before in my testing but never really explored it
yeah, none of the source inspect works in repl
!e ```py
import sys
class Final:
slots = ['value']
def init(self, value):
self.value = value
frames = {}
def tracefunc(frame, event, arg):
for dct_name in ['f_globals', 'f_locals']:
mp = getattr(frame, dct_name)
for key, value in mp.items():
if isinstance(value, Final) and hasattr(value, 'value'):
frames.setdefault(frame, {}).setdefault(dct_name, {})[key] = value.value
for key, value in frames.get(frame, {}).get(dct_name, {}).items():
mp[key] = value
return tracefunc
sys.settrace(tracefunc)
def foo():
x = Final(100)
print(x, type(x))
x = 1
print(x, type(x))
foo()
@rugged sparrow :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 100 <class 'int'>
002 | 100 <class 'int'>
doesn't seem to want to work for global scope but it works for locals
you still set f_locals for the module frame iirc
fizzbuzz = lambda x: [
div3 := x % 3 == 0,
div5 := x % 5 == 0,
result := "",
div3 and [
result := result + "fizz",
],
div5 and [
result := result + "buzz",
],
result or [
result := str(x),
],
result,
][-1]
for i in range(1, 101):
print(fizzbuzz(i))
proof that python supports braces instead of indentation, and that lambdas allow multiple lines :P
(you can also use set notation for the "if statements", as long your results are all hashable)
@fleet bridge :x: Your 3.11 eval job has completed with return code 1.
001 | File "/home/main.py", line 1
002 | from __future__ import braces
003 | ^
004 | SyntaxError: not a chance
!e ```py
if 1 == 1: {
print("wrong")
}
@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
wrong
!e
if 1 == 1: {
right := {},
print(right)
}
@radiant anchor :x: Your 3.11 eval job has completed with return code 1.
001 | {}
002 | Traceback (most recent call last):
003 | File "/home/main.py", line 1, in <module>
004 | if 1 == 1: {
005 | ^
006 | TypeError: unhashable type: 'dict'
!e ```py
if 1 == 1: {
right = {}
print(right)
}
@vast wave :x: Your 3.11 eval job has completed with return code 1.
001 | File "/home/main.py", line 2
002 | right = {}
003 | ^^^^^^^^^^
004 | SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
oh right
.
!e ```py
fizzbuzz = lambda x: {
div3 := x % 3 == 0,
div5 := x % 5 == 0,
result := "",
div3 and (
result := result + "fizz",
),
div5 and (
result := result + "buzz",
),
result or (
result := str(x),
),
result,
}.pop()
for i in range(1, 101):
print(fizzbuzz(i))
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | False
002 | False
003 | False
004 | False
005 | False
006 | False
007 | False
008 | False
009 | False
010 | False
011 | False
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/katoxoliwa.txt?noredirect
you could use a dict
you could have a dict with "line numbers"
hashable_thingy:
something,
hashable_thingy:
something_else,
}```
something like that
could be done
as long as you keep even numbers of stuff
and have every other line be hashable
shouldnt be too hard, yeah?
!e ```py
@lambda :()
class a:pass
if 1 == 1: {
a:"something",
a:print("something else")
}
@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
something else
!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.
By default, your code is run on Python 3.11. A python_version arg of 3.10 can also be specified.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!
!e
if 1 == 1: {
...:"something",
...:print("something else")
}
@radiant anchor :white_check_mark: Your 3.11 eval job has completed with return code 0.
something else
i1 = [False, True, False, False, True, True, False, True, False, True, True, True, False, False, True, False, False, False, True, False, True, True, True, False, False, False, True, False, False, False, False, False, False, True, False, True, False, True, True, True, False, True, True, False, True, False, False, True, False, True, True, True, False, False, False, False, False, True, True, True, False, False, False, False]
i111 = ""
for i in i1: i2 = int(i); i111 += str(i2)
i11 = int(i111, 2);i1111 = i11.bit_length() + 7 // 8;i111111 = i11.to_bytes(i1111, "big");i11111 = i111111.decode();print(i11111)
!e
i1 = [False, True, False, False, True, True, False, True, False, True, True, True, False, False, True, False, False, False, True, False, True, True, True, False, False, False, True, False, False, False, False, False, False, True, False, True, False, True, True, True, False, True, True, False, True, False, False, True, False, True, True, True, False, False, False, False, False, True, True, True, False, False, False, False]
i111 = ""
for i in i1: i2 = int(i); i111 += str(i2)
i11 = int(i111, 2);i1111 = i11.bit_length() + 7 // 8;i111111 = i11.to_bytes(i1111, "big");i11111 = i111111.decode();print(i11111)
@mystic hull :white_check_mark: Your 3.11 eval job has completed with return code 0.
๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝMr. Wipp
lmao finally
:incoming_envelope: :ok_hand: applied mute to @sick hound until <t:1679246074:f> (10 minutes) (reason: duplicates rule: sent 4 duplicated messages in 10s).
The <@&831776746206265384> have been alerted for review.
Ayyy
!e import math; import numpy; sine = lambda from_, to_, amp_, step_: (math.sin(s * amp_) for s in numpy.arange(from_, to_, step_)); square = lambda from_, to_, amp_, step_: ((-1 if c <= 0 else 1) for c in sine(from_, to_, amp_, step_)); print(list(square(0, 4, 1, 0.1)));
@heavy ermine :white_check_mark: Your 3.11 eval job has completed with return code 0.
[-1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1]
python one-liner folks
(
lambda math, numpy: ...
)(
__import__("math"),
__import__("numpy")
)
@heavy ermine
what this for
to avoid using semicolons
uhhhh why lambda math, numpy: ...
the math and numpy arguments are passed to your code, the ... part
then you can truly make it one line
why just not use __import__
it would save characters if you were using it a lot
ok????? how so
because it's easier to type math instead of typing __import__("math") each time
you can shorten it to just m
import math as m;import numpy as n;...
that's not one line though
technically it is. there are no \n in this code
that's cheating
its not, technically
in esoteric python it is
or, here me out,
(np:=__import__("numpy"),math:=__import__("math"))
somewhere in the beginning
of the function
just have them as default arguments in the lambda
!e
f=lambda a, np=__import__('numpy'): np.array(a).T
print(f([[0, 1, 2], [3, 4, 5]]))
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | [[0 3]
002 | [1 4]
003 | [2 5]]
!e
sum(print("test") or 0for _ in range(3))```
@bronze agate :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | /home/main.py:1: SyntaxWarning: invalid decimal literal
002 | sum(print("test") or 0for _ in range(3))
003 | test
004 | test
005 | test
!e py foo = lambda n:print(sum(print(x,end='+='[i==len(n)-1])or x for i,x in enumerate(n))) foo([1,2,3]) foo([4,5,6])
@last locust :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1+2+3=6
002 | 4+5+6=15
Heh, neat
!e ```py
foo = lambda n:print('+'.join(map(str,n))+'=%d'%sum(n))
foo([1,2,3])
foo([4,5,6])
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1+2+3=6
002 | 4+5+6=15
ok
I was expanding on the one above though
!e py foo = lambda n:print(sum(print(x,end='=+'[i<len(n)-1])or x for i,x in enumerate(n))) foo([1,2,3]) foo([4,5,6])
@last locust :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1+2+3=6
002 | 4+5+6=15
That's 1 char shorter by swapping the += to =+ and then i<len(n)-1 instead of i==len(n)-1
ok
I believe using fstring at the end would be 1 char shorter
you can save 2 chars per invocation by using *args rather than taking a list
same number of chars
+"=%d"%sum(n)
+f"={sum(n)}"
!e
f = lambda n: print(f"{'+'.join(map(str, n))}={sum(n)}")
f([1,2,3])
f([4,5,6])
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1+2+3=6
002 | 4+5+6=15
!e ```py
f = lambda n:print(eval(f"f'{{{'+'.join(map(str,n))}=}}'"))
f([4,5,6])
f([1,2,3,4,5,6,7,8,9])
@pure dew :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 4+5+6=15
002 | 1+2+3+4+5+6+7+8+9=45
a lil bit longer but way cooler
!e you guys are way overcomplicating it ```py
def f(n):print('+'.join(map(str,n))+f'={sum(n)}')
f([4,5,6])
f([1,2,3,4,5,6,7,8,9])```
@past plank :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 4+5+6=15
002 | 1+2+3+4+5+6+7+8+9=45
f=lambda n:print(eval(f"f'{{{'+'.join(map(str,n))}=}}'")) # 57
f=lambda n:print(f"{'+'.join(map(str, n))}={sum(n)}") # 53
def f(n):print('+'.join(map(str,n))+f'={sum(n)}') # 49```
it's pointless to use a lambda if you don't need to return anything py f=lambda a,b: def f(a,b):
aside from the function definition though, this improvement is obvious py print(f"{'+'.join(map(str, n))}={sum(n)}") print('+'.join(map(str,n))+f'={sum(n)}')
we've already had something of similar length for a while now?
print(f"{'+'.join(map(str, n))}={sum(n)}")
print('+'.join(map(str,n))+f'={sum(n)}')
print('+'.join(map(str,n))+'=%d'%sum(n))
the bottom one is from this
you're reinventing the wheel :P
Adds two spaces, but removes two chars:
print('+'.join(map(str,n))+f'={sum(n)}')
print('+'.join(map(str,n)),'=',sum(n))
e.g.
1+1+1=3
1+1+1 = 3
n=[1,2,3]
print(*n,sep='+',end=f'={sum(n)}')
!e ```py
n=[1,2,3]
print(*n,sep='+',end=f'={sum(n)}')
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
1+2+3=6
Is it shorter?
mhm
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
1+2+3=6
Hey,
I have a little golfing challenge.
You have a file with n lines and each line contains one word of random length with random letters.
Distance between letters A and B is 1, between C and F its 3 etc etc.
List words where distance between all the letters in the word is less than 10.
Example of a word that matches this condition is AHBINK
119
import itertools as i
p=i.pairwise
for w in open(0).read().split():all(-10<ord(i)-ord(j)<10for i,j in p(w))and print(w)
92
for w in open(0).read().split():all(-10<ord(i)-ord(j)<10for i,j in zip(w,w[1:]))and print(w)
does this work? ```py
for w in open(0):p,*a,_=w;10<max((abs(ord(p)-ord(c)),p:=c)[0]for c in a)or print(w)
yes
both 76
for w in open(0):p,*a,_=w;all(-10<ord(p)-ord(p:=c)<10for c in a)and print(w)
for w in open(0):p,*a,_=w;10<max(abs(ord(p)-ord(p:=c))for c in a)or print(w)
actually no
your's is wrong
which is a good thing
because it saves a char
75
for w in open(0):p,*a,_=w;9<max(abs(ord(p)-ord(p:=c))for c in a)or print(w)
tied 75
for w in open(0):p,*a,_=w;max(abs(ord(p)-ord(p:=c))for c in a)<10==print(w)
@sly ibex :white_check_mark: Your 3.11 eval job has completed with return code 0.
-10 0 10 20 30
wouldn't they have the same lengthdef a(a) be shorter than lambda a ?
you'd also remove the b =
kinda got offtopic here sorry```hs
ghci> t = [123, 123, 893]
ghci> (\x -> sum x)(t)
1139
```py
>>> t = [123, 123, 893]
>>> (lambda x: sum(x))(t)
1139
??
foo or print(w) -> [foo,print(w)]?
you can't call the function on the same line as it was defined without semicolons
Not shorter, but thought I'd share my entry anyway
79
for w in open(0):any(abs(ord(a)-ord(b))>9for a,b in zip(w,w[1:-1]))or print(w)```
foo is boolean, the short circuiting is necessary
i have 2 ways to make this shorter but i'm currently testing one
nvm they both don't work
ok this is kind of a crapshoot, but is there a semi-reasonable way to find where a certain string is being stored in what seems to be an absurdly convoluted and obfuscated data structure?
I've gone about trying to manually set a certain configuration for a certain class and it's apparently cached elsewhere but I can find absolutely nothing helpful in this descent into madness that some might generously call a module
um yes
search the memory
if it's interned you might have better luck with gc.get_referrers()
I mean, I can def find its physical memory location with scanner tools but I've no clue how to get from the memory location to which object actually owns that data
find the physical memory location, subtract a specific amount of bytes, use ctypes to get the str object, then gc.get_referrers() if the string is interned
that is if it's a str
for 64-bit systems, subtract 48 bytes for ASCII strings and 72 for non-ASCII strings in 3.10(?)+
seems like I'm gettin a lot of Nones back, hmm
not python but i think you guys will like this language
reminds me of perl-
bfasm ?
it should be named brainfuckasactualprogramminglanguage
bfaapl
!e def function(c):
translates = {49:11036,48:11035}
for i in c:
fill = []
for j in c:
fill.append(len(bin(ord(j))[1:]))
fill = max(fill)
i = bin(ord(i))[2:]
i = i.zfill(fill)
i = i.translate(translates)
print(i)
_('<~ร รพรพ~ff', 2)
function('<~ร รพรพ~ff')
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | โฌโฌโฌโฌโฌโฌโฌโฌโฌ
002 | โฌโฌโฌโฌโฌโฌโฌโฌโฌ
003 | โฌโฌโฌโฌโฌโฌโฌโฌโฌ
004 | โฌโฌโฌโฌโฌโฌโฌโฌโฌ
005 | โฌโฌโฌโฌโฌโฌโฌโฌโฌ
006 | โฌโฌโฌโฌโฌโฌโฌโฌโฌ
007 | โฌโฌโฌโฌโฌโฌโฌโฌโฌ
008 | โฌโฌโฌโฌโฌโฌโฌโฌโฌ
@thorny tapir :warning: Your 3.11 eval job has completed with return code 0.
[No output]
@thorny tapir :warning: Your 3.11 eval job has completed with return code 0.
[No output]
!e ```py
import sys
f = open("1.txt", 'w')
sys.stdout = f
print("Hello world")
@gleaming linden :white_check_mark: Your 3.11 eval job has completed with return code 0.
1.txt
Hello world
!e or this: ```py
from contextlib import redirect_stdout
f = open("1.txt", 'w')
with redirect_stdout(f):
print("Hello")
print("World")
@gleaming linden :white_check_mark: Your 3.11 eval job has completed with return code 0.
World
1.txt
Hello
!e ```py
import sys
with open("1.txt", "w") as sys.stdout:
print("Hello")
print("World")
@old socket :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 5, in <module>
003 | print("World")
004 | ValueError: I/O operation on closed file.
1.txt
Hello
oh I thought it worked before
Unless it's just cus of snekbox
Oh wait it did write but there is an error
it works, but you can't print anything afterward because the file is closed when you exit the with block
!e ```py
from contextlib import redirect_stdout
with open('1.txt', 'w') as file, redirect_stdout(file):
print("Hello")
print("World")
@gleaming linden :white_check_mark: Your 3.11 eval job has completed with return code 0.
World
1.txt
Hello
oh, this works too
I know you can unpack with ctx manager but I thought the enter specifically needed to return something unpackable
!e ```py
with open("1.txt", "w") as foo, bar:
print(foo, bar)
@old socket :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 | with open("1.txt", "w") as foo, bar:
004 | ^^^
005 | NameError: name 'bar' is not defined
1.txt
[Empty]
it's doing with (open("1.txt", "w") as foo), bar:
Ahh okay
!e ```py
with open('1.txt', 'w') as file:
file.write("foo\nbar\n")
with open('1.txt') as (a, b):
print(a, b)
@gleaming linden :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | foo
002 | bar
1.txt
foo
bar
cool
I wonder how secure the file stuff is on snekbox
I know there prob isn't any huge issue off the bat but I can't help but feel there is something
!e
open(1, "w").write("hello, world")
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello, world
1 is the file descriptor for stdout
its not that they could use it as stdout, it's that it is stdout
!e ```py
open("/dev/stdout", "w").write("dlrow ,olleh")
@pure dew :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 | open("/dev/stdout", "w").write("dlrow ,olleh")
004 | ^^^^^^^^^^^^^^^^^^^^^^^^
005 | FileNotFoundError: [Errno 2] No such file or directory: '/dev/stdout'

/dev is not mounted in snekbox
Since when this feature does exist?
around 2 weeks ago snekbox#159
That's awesome
Why there was not announcement about this new feature?
there's this one?
#changelog message
Totally forgot about that
!e open('file.txt', 'w').write('1\n2\n3\n4')
arr=[0]*10
with open('file.txt') as (arr[0], *arr[5:7], arr[-1]):
print(arr)
@sonic birch :white_check_mark: Your 3.11 eval job has completed with return code 0.
['1\n', 0, 0, 0, 0, '2\n', '3\n', 0, 0, '4']
file.txt
1
2
3
4
smh i'll get it
!e ```py
open('file.txt', 'w').write('1\n2\n3\n4')
arr=[0]*10
with open('file.txt') as (arr[0],*arr[5:7], arr[-1]):
print(arr)
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
['1\n', 0, 0, 0, 0, '2\n', '3\n', 0, 0, '4']
file.txt
1
2
3
4
!e open('file.txt', 'w').write('1\n2\n3\n4')
arr=[0]
with open('file.txt') as (arr[0],*arr[5:7], arr[-1]):
print(arr)
@pure dew :white_check_mark: Your 3.11 eval job has completed with return code 0.
['1\n', '2\n', '4']
file.txt
1
2
3
4
!e open('file.txt', 'w').write('1\n2\n3\n4')
arr=[]
with open('file.txt') as (arr[0],*arr[1:3], arr[-1]):
print(arr)
@pure dew :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 3, in <module>
003 | with open('file.txt') as (arr[0],*arr[1:3], arr[-1]):
004 | ~~~^^^
005 | IndexError: list assignment index out of range
file.txt
1
2
3
4
ah
๐ฅด
I'm assuming the first one is for lambdas, but the second one lies to me as I can get 2 (so there is something). The last one is what I would expect from both except the NOP which I didn't know is used
The last one is kind of what happen if I throw these into an actual function
(minus the NOP in the first two cases)
the second one is the same as the third one, except for the NOP
which makes sense, considering that they do the same thing
the NOP i assume is an artifact of the separate lines
But why does the byte code tell me there is no constant loading when I can load 2
I mean
_ becomes 2
Is it just a REPL thing
iirc that's done by sys.displayhook
yeah
Code in repl is compiled in its special mode
!e ```py
from dis import dis
c = compile('1;2', '', mode='single')
dis(c)
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 0 RESUME 0
002 |
003 | 1 2 LOAD_CONST 0 (1)
004 | 4 PRINT_EXPR
005 | 6 LOAD_CONST 1 (2)
006 | 8 PRINT_EXPR
007 | 10 LOAD_CONST 2 (None)
008 | 12 RETURN_VALUE
Cool!
And on another note, can someone explain me how the reference counting system works in Python?
The website talks about strong references and borrowed references
You can read developers guide about that
There is some introduction to capi where these words are explained
Strong references are references that if are gone, delete the object
Borrowed just means the object's strong reference is borrowed? What count is being incremented/decremented then?
the objects ob_refcnt
Thats not about destroying object. It is about when you should do PyINCREF(x) and when you shouldn't
Include/object.h lines 102 to 106
struct _object {
_PyObject_HEAD_EXTRA
Py_ssize_t ob_refcnt;
PyTypeObject *ob_type;
};```
At which point does the virtual machine stop to take a look at objects' ob_refcnt?
that's the garbage collectors job
When does it collect garbage
When .ob_type hits 0
When GC is triggered
you could try reading the source to figure that out
What if I have something like
for _ in range(1_000_000):
f()
It is not. GC isn't doing anything at this moment
But objects begin with a reference count that is greater than zero?
There is no problem.
Assignment to _ increments RC for one object and decrements for another
sorry- i meant the ob_refcnt gets decremented when going out of scope
which means the gc can collect the object if the ob_refcnt is 0
Yes, because otherwise it would be weird
Leaving scope is equivalent to deleting all local variables using del x
yeah
When in something like
print()
print()
does the garbage collector know to dereference the None from the return values
If i am not mistaken, RC==0 is none of GC business.
GC is doing graph analysis, so it is not related to deleting object with RC==0.
This behaviour is inlined (i guess) into Py_DECREF macro that checks if RC==0.
Care to elaborate? Which object's reference count is incremented and which object's is decremented?
Look at bytecode and realise that by yourself
Olds is decremented, news is incremented. Because there is one less reference to old object and one more ref to new object
is it? it used to be the gc that handled that
i guess my knowledge about that is a bit behind since i dont really mess around with the gc much
well ty for teaching me that then
Which objects are considered old? The ones in the body of the for loop after an iteration?
Well. It is also possible to think that there are 2 different GCs:
- stupid one: checks RC==0 and deletes object
- smart one: detects dead graphs, destroys references in this graphs, so every RC eventually hits 0, so stupid GC can collect every garbage object
a = old
a = new # here rc of new is incremented and rc of old is decremented
Understood
Thanks
For loop can be destructured to simpler statements, and there would be an assignment
Yeah, STORE_NAME ... (_) in my case
Interesting fact: you can use in for loop anything if you can use it before =
for a[b] in c:... is good, for example
It is called "assignment target", it means you can assign value to it and it wouldn't raise SyntaxError
Assignment target is essentially any expression with some exceptions (you cant assign to function calls, literals, ...)
In this case it is even stricter: you can delete only variable, expression.attr and expression[item]
!e
from string import ascii_uppercase, ascii_lowercase
a = list(ascii_uppercase)
c = list(ascii_lowercase)
b = 0
print(f"{a = }\n{c = }")
for a[b] in c:
b += 1
print(f"{a = }\n{c = }")
@cloud fossil :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
002 | c = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
003 | a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
004 | c = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
So cool
you can also do slices
!e
from string import ascii_uppercase, ascii_lowercase
a = list(ascii_uppercase[:10])
c = list(ascii_lowercase[:10])
b = 0
print(f"{a = }\n{c = }")
for a[b::2] in c:
b += 2
print(f"{a = }\n{c = }")
@cloud fossil :x: Your 3.11 eval job has completed with return code 1.
001 | a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
002 | c = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
003 | Traceback (most recent call last):
004 | File "/home/main.py", line 6, in <module>
005 | for a[b::2] in c:
006 | ~^^^^^^
007 | ValueError: attempt to assign sequence of size 1 to extended slice of size 5
a[b] and a[<slice>] are the same, index type is handled inside list.getitem
Wait do I need to slice c with b as well
since people usually forget
!e
from string import ascii_uppercase, ascii_lowercase
a = list(ascii_uppercase[:10])
c = list(ascii_lowercase[:10])
b = 0
print(f"{a = }\n{c = }")
for a[b::2] in c[b::2]:
b += 2
print(f"{a = }\n{c = }")
@cloud fossil :x: Your 3.11 eval job has completed with return code 1.
001 | a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
002 | c = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
003 | Traceback (most recent call last):
004 | File "/home/main.py", line 6, in <module>
005 | for a[b::2] in c[b::2]:
006 | ~^^^^^^
007 | ValueError: attempt to assign sequence of size 1 to extended slice of size 5
slices are one of the nicest features and yet people forget about them so often
How can I do this with slices
it's the same as a tuple unpacking assignment-
the amount of items needs to match
!e
from string import ascii_uppercase, ascii_lowercase
a = list(ascii_uppercase[:10])
c = list(ascii_lowercase[:10])
b = 0
print(f"{a = }\n{c = }")
for a[b:b+2:2] in c:
b += 2
print(f"{a = }\n{c = }")
@cloud fossil :x: Your 3.11 eval job has completed with return code 1.
001 | a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
002 | c = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
003 | Traceback (most recent call last):
004 | File "/home/main.py", line 6, in <module>
005 | for a[b:b+2:2] in c:
006 | ~^^^^^^^^^
007 | ValueError: attempt to assign sequence of size 1 to extended slice of size 0
They are also very non-obvious if you are doing assignment to slice or deleting slice.
For example, if you assign short sequence to slice, list will mutate and become shorter. It is tricky (and not efficient) if you are assigning to slice that is not on the end of the list
!e
from string import ascii_uppercase, ascii_lowercase
a = list(ascii_uppercase[:10])
c = list(ascii_lowercase[:10])
b = 0
print(f"{a = }\n{c = }")
for a[b], a[b+1] in c[::2]:
b += 2
print(f"{a = }\n{c = }")
@cloud fossil :x: Your 3.11 eval job has completed with return code 1.
001 | a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
002 | c = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
003 | Traceback (most recent call last):
004 | File "/home/main.py", line 6, in <module>
005 | for a[b], a[b+1] in c[::2]:
006 | ^^^^^^^^^^^^
007 | ValueError: not enough values to unpack (expected 2, got 1)
!e
from string import ascii_uppercase, ascii_lowercase
a = list(ascii_uppercase[:10])
c = list(ascii_lowercase[:10])
b = 0
print(f"{a = }\n{c = }")
for a[b], a[b+1] in c[b:b+2:2]:
b += 2
print(f"{a = }\n{c = }")
@cloud fossil :x: Your 3.11 eval job has completed with return code 1.
001 | a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
002 | c = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
003 | Traceback (most recent call last):
004 | File "/home/main.py", line 6, in <module>
005 | for a[b], a[b+1] in c[b:b+2:2]:
006 | ^^^^^^^^^^^^
007 | ValueError: not enough values to unpack (expected 2, got 1)
I'm totally not understanding how this should work
By "tricky" i mean "it is easy to make off-by-one errors"
mhm
!e weird way to copy a list (inspired by today's conversation) ```py
a = [*'abcdefgh']
print(a)
c = [' '] * len(a)
for i, c[i] in enumerate(a):
print(c)
assert a == c
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
002 | ['a', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
003 | ['a', 'b', ' ', ' ', ' ', ' ', ' ', ' ']
004 | ['a', 'b', 'c', ' ', ' ', ' ', ' ', ' ']
005 | ['a', 'b', 'c', 'd', ' ', ' ', ' ', ' ']
006 | ['a', 'b', 'c', 'd', 'e', ' ', ' ', ' ']
007 | ['a', 'b', 'c', 'd', 'e', 'f', ' ', ' ']
008 | ['a', 'b', 'c', 'd', 'e', 'f', 'g', ' ']
009 | ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
fun implementation detail: i, c[i] = value works even if i is not previously defined because:
iis assigned tovalue[0]iis loaded to stack (there is no error becauseiwas defined by previous step)c[TOS]is assigned tovalue[1]
@languid hare :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 2 0 RESUME 0
002 |
003 | 3 2 LOAD_GLOBAL 0 (tup)
004 | 14 UNPACK_SEQUENCE 2
005 | 18 STORE_FAST 0 (i)
006 | 20 LOAD_GLOBAL 2 (arr)
007 | 32 LOAD_FAST 0 (i)
008 | 34 STORE_SUBSCR
009 | 38 LOAD_CONST 0 (None)
010 | 40 RETURN_VALUE
011 | None
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ohapehimef.txt?noredirect
!e ```py
t = (0, "abc")
arr = [1]
i, arr[i] = t
print(i, arr)
@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
0 ['abc']
interesting
huh
!e ```py
arr = arr[0] = [0]
print(arr)
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
[[...]]
arr=arr [0]=[0] is pretty funny
[0] gets assigned to arr[0], which gets assigned to arr?
!e ```py
import("dis").dis(compile("a = a[0] = [1]", "", "exec"))
@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 0 RESUME 0
002 |
003 | 1 2 LOAD_CONST 0 (1)
004 | 4 BUILD_LIST 1
005 | 6 COPY 1
006 | 8 STORE_NAME 0 (a)
007 | 10 LOAD_NAME 0 (a)
008 | 12 LOAD_CONST 1 (0)
009 | 14 STORE_SUBSCR
010 | 18 LOAD_CONST 2 (None)
011 | 20 RETURN_VALUE
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ucowuriluh.txt?noredirect
god that is funky
for thing = thing2 = thing3 = value it goes thing = value, then thing2 = thing, and so on
what the fuck?
!e ```py
import ast
print(ast.dump("a = b = c = d = 1", indent=2))
!e ```py
import ast
print(ast.dump(ast.parse("a = b = c = d = 1"), indent=2))
@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Module(
002 | body=[
003 | Assign(
004 | targets=[
005 | Name(id='a', ctx=Store()),
006 | Name(id='b', ctx=Store()),
007 | Name(id='c', ctx=Store()),
008 | Name(id='d', ctx=Store())],
009 | value=Constant(value=1))],
010 | type_ignores=[])
yep
python moment
it would make a little more sense imo if it went from right to left here, like this ```py
thing = (thing2 = (thing3 = value))
https://github.com/HRLO77/forums-website/blob/main/db_funcs.py#L239
Most of the code in this does not follow pep8
db_funcs.py line 239
p = map((lambda x: (x[0], (*x[1:5], *x[6:-2], len(x[-1])-len(x[-2])))), filter((lambda x: x[0] in ids), await get_posts()))```
db_funcs.py line 400
[id, post[1] if title is None else title, post[2] if content is None else content, post[3] if date is None else date, None if fp is None and post[4] is not None else (lambda: post[4] if fp is '' else fp)(), post[5] if ip is None else ip, post[6] if pin is None else pin, f'{post[7]}' if upvotes is None else f'{upvotes}', f'{post[8]}' if downvotes is None else f'{add_downvote}', id],```
db_funcs.py lines 43 to 52
if not (await os.path.isfile(file)):file = glob.glob(f'./**/{file}', recursive=True)[0]
async with aiofiles.open(file) as f:code = await f.read()
fg = ''.join(random.sample(string.ascii_letters, k=52)) + '.py'
async with aiofiles.open(fg, 'w') as f:await f.write(code)
await os.remove(fg)
g = {i:v for i,v in globals().items()}
g['DATA'] = data
if threaded:await asyncio.to_thread(exec, [code, g, {i:v for i,v in locals().items()}])
else:exec(code, g, {i:v for i,v in locals().items()})
print(f'Flow {flow} executed {file} given type data {t} on {datetime.datetime.utcnow()} UTC.')```
!epy print('\n'.join(['abcdefghijklmnopqrstuvwxyz'[:_]for _ in range(1,26)]))
@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | a
002 | ab
003 | abc
004 | abcd
005 | abcde
006 | abcdef
007 | abcdefg
008 | abcdefgh
009 | abcdefghi
010 | abcdefghij
011 | abcdefghijk
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ohaloqoqum.txt?noredirect
!epy print('\n'.join('abcdefghijklmnopqrstuvwxyz'[:_]for _ in range(1,26)))
@last locust :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | a
002 | ab
003 | abc
004 | abcd
005 | abcde
006 | abcdef
007 | abcdefg
008 | abcdefgh
009 | abcdefghi
010 | abcdefghij
011 | abcdefghijk
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/zeyukumabe.txt?noredirect
You don't need the list 
Ok
Forgot that it also takes *args
it's a generator
!e```pg
print('\n'.join(import('string').ascii_lowercase[:_]for _ in range(1,26)))
You need the .ascii_lowercase (which makes it longer)
@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | a
002 | ab
003 | abc
004 | abcd
005 | abcde
006 | abcdef
007 | abcdefg
008 | abcdefgh
009 | abcdefghi
010 | abcdefghij
011 | abcdefghijk
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/gihahedoqi.txt?noredirect
Haven't used string in a while
!e py print("\n".join(map(chr,range(97,123))))there's also this, which is even shorter
@last locust :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | a
002 | b
003 | c
004 | d
005 | e
006 | f
007 | g
008 | h
009 | i
010 | j
011 | k
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ijocekoniy.txt?noredirect
You'd just have to add the slice logic (which thinking about it would probably make it longer)
I was wondering if there is a way to code in python without using letters?
Like with javascript
What do you define as letters?
^
Ig he is talking about jsfuck
yup
If you mean solely latin a-z then you can just use other scripts
!e ```py
print("\n".join("".join(map(chr,range(97,98+i)))for i in range(26)))
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | a
002 | ab
003 | abc
004 | abcd
005 | abcde
006 | abcdef
007 | abcdefg
008 | abcdefgh
009 | abcdefghi
010 | abcdefghij
011 | abcdefghijk
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/sicanetazi.txt?noredirect
print("\n".join("".join(map(chr,range(97,98+i)))for i in range(26)))
print('\n'.join('abcdefghijklmnopqrstuvwxyz'[:_]for _ in range(1,26)))
it's shorter
because you don't need the start argument for the range call
Ah yeah, just
s
!e ```py
import matplotlib.pyplot as plt
x = [1,3,5,6]
y = [1,6,7,8]
plt.plot(x,y)
plt.show()
@slow marsh You've already got a job running - please wait for it to finish!
Sorry, an unexpected error occurred. Please let us know!
TimeoutError:
@slow marsh
yeah ok
there needs to be more rocket emoji
wait until you see enterprise fizzbuzz though
it's unmaintained though :(
huh so apparently linus torvalds has contributed to that one
encode_rail_fence_cipher,decode_rail_fence_cipher=lambda s,n:''.join([''.join(map(''.join,zip(s[i::(k:=2*~-n)],s[k-i::k]+'็ง'))),s[::k],s[n-1::k]][(i%~-n<1)+(n-i<2)].rstrip('็ง')for i in range(n)),lambda s,n,c=0:s and''.join(map(''.join,zip(*[s[:(c:=(g:=1+(l:=len(s)-1)//(k:=2*~-n)))],*(m:=[[[],[]],[*zip(*[zip(*zip(*[iter(f'{s[c:(c:=c+l//k*2+(l%k>=i)+(l%k>=k-i))]:็ง<{g*2}}')]*2))for i in range(1,n-1)])]][n>2])[0],f'{s[c:]:็ง<{g}}',*m[1][::-1]]))).rstrip('็ง')
one liner for this https://www.codewars.com/kata/58c5577d61aefcf3ff000081
cannot be bothered to golf further
i love git-blame-someone-else
oh interesting
hey everyone! I am running an Obfuscated Python Code Competition. Should be lots of fun! Please enter or dm me if you want to be a judge: http://pyobfusc.com
Obfuscated Python competition
Can anyone help me shorten this code I wrote.
def square_digits(num):
return int("".join([str(i) for i in [int(i)**2 for i in list(str(num))]]))
It looks like a monstrosity IK hahah
square_digits=lambda n:int("".join(map(str,[int(i)**2for i in str(n)])))
@versed eagle ```py
square_digits=lambda n:int(''.join(str(int(i)**2)for i in'%i'%n))
That's much shorter DANG ty
I see '%i'
hi
hi
-
plt.show() is blocking which is why it times out
-
even if you pass
block=False, it opens a new window and doesn't save a file so you wouldn't be able to see on snekbox anyway. -
The correct way to do this is to use
plt.savefig, as follows:
!e ```py
import matplotlib.pyplot as plt
x = [1,3,5,6]
y = [1,6,7,8]
plt.plot(x,y)
plt.savefig("plot.png")
@last locust :white_check_mark: Your 3.11 eval job has completed with return code 0.
oh nice
!e print("\n".join("#"*n for n in range(10,0,-1)))
@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | ##########
002 | #########
003 | ########
004 | #######
005 | ######
006 | #####
007 | ####
008 | ###
009 | ##
010 | #
discord's search fucking sucks
It gives up
What is the use of [:_] in the context you used?
slicing at _ through the following loop list comp, [start:stop:step] iirc
Start Stop step
!e
# This comment is necessary for the code to run.
# This comment is also necessary.
# So is this one.
q = [36, 29, 0, -36, -69, -184, -165, -177, -210, -252, -296, -399]
n = 0
def __a():
pass
def __b():
global n
for i in __a.__code__.co_lines():
n += i[0] + (i[1] * i[2])
for i in range(len(q)):
print(str(__b())[10:] + chr(q[i] + n), end="")```
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
ยรฝลฦวซวจษซหฬอคฮจฮฑ
Haha it doesn't even run properly in here
Was b supposed to return something?
!e
s = (x for x in range(10))
print(list(s).__sizeof__())
print(list(s).__sizeof__())
print(list(s).__sizeof__())
@zenith geode :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 168
002 | 40
003 | 40
The generator is just exhausted the second and third time?
!e empty list takes less space than non-empty list
s = (x for x in range(10))
print(list(s))
print(list(s))
print(list(s))
@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
002 | []
003 | []
oh lmfao thanks
Nope, the code runs fine in a .py file. And removing the line the comments are on makes it throw an exception :)
!e @commands.group( help="Shows boosts count", usage="boosts", aliases=["bc"]) @blacklist_check() async def boosts(self, ctx): await ctx.send( embed=discord.Embed(title=f"Boosts Count Of {ctx.guild.name}", description="**`%s`**" % (ctx.guild.premium_subscription_count), color=0x977FD7))
@sick hound :x: Your 3.11 eval job has completed with return code 1.
001 | File "/home/main.py", line 5
002 | @blacklist_check()
003 | IndentationError: unexpected indent
That wonโt work.
The bot uses a sandbox environment so itโs not actually connected to the bot
!e
q = [36, 29, 0, -36, -69, -184, -165, -177, -210, -252, -296, -399]
n = 0
def __a():
pass
def __b():
global n
for i in __a.__code__.co_lines():
n += i[0] + (i[1] * i[2])
for i in range(len(q)):
print(str(__b())[10:] + chr(q[i] + n), end="")```
@rugged owl :white_check_mark: Your 3.11 eval job has completed with return code 0.
dยรรรปรฤลลฎฦฦลฑ
Doesnt seem to throw an exception
what python version?
oh it's 3.10
!e ```py
'some' r'eally' 'useless' + str('ings') \
- int('4nd integers'[:3 is 3]) + f'or' r'eal' +
str('this' is not 'a' 'joke')
q = [36, 29, 0, -36, -69, -184, -165, -177, -210, -252, -296, -399]
n = 0
def __a():
pass
def __b():
global n
i = next(it := __a.__code__.co_lines()) and next(it)
n += i[0]-2 + (i[1] * i[2])
for i in range(len(q)):
print(str(__b())[10:] + chr(q[i] + n), end="")
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | /home/main.py:2: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | * int('4nd integers'[:3 is 3]) + f'or' r'eal' + \
003 | /home/main.py:3: SyntaxWarning: "is not" with a literal. Did you mean "!="?
004 | str('this' is not 'a' 'joke')
005 | Hello World!
can you help me with steal sticker command (actually i want it)
cipher = lambda t, s: ''.join(chr((ord(c) - 65 + s) % 26 + 65) if c.isupper() else chr((ord(c) - 97 + s) % 26 + 97) if c.isalpha() else c for c in t)
Wondering if this can be shortend further??
cipher=lambda t,s:''.join(chr((ord(c)-65+s)%26+65)if c.isupper()else chr((ord(c)-97+s)%26+97)if c.isalpha()else c for c in t)```
I'm assuming there won't be any non-alphabetic characters?
oh nvm
cipher=lambda t,s:''.join([c,chr((ord(c)-65+s-c.islower()*32)%26+97-c.isupper()*32)][c.isalpha()]for c in t)
``` does this work?
it didn't work, it should be fixed now
cipher=lambda t,s:''.join([c,(d:=65+c.islower()*32),chr((ord(c)-d+s)%26+d)][-c.isalpha()]for c in t)
``` 100
This one works
I dont think this one works
oh wait I'm stupid
cipher=lambda t,s:''.join([c,chr((ord(c)-(d:=65+c.islower()*32)+s)%26+d)][c.isalpha()]for c in t)
97
dang 97 length
c.islower()*32 -> ord(c)&32 I think should work
cipher=lambda t,s:''.join([c,chr((ord(c)-(d:=65+(ord(c)&32))+s)%26+d)][c.isalpha()]for c in t)
``` works but needs brackets, 94
cipher=lambda t,s:''.join([c,chr(((n:=ord(c))+s-(d:=(n&96)+1))%26+d)][64<n&95<91]for c in t)
92 if it works
cipher=lambda t,s:''.join([c,chr(((n:=ord(c))+s-(d:=-~(n&96)))%26+d)][64<n&95<91]for c in t)
Same length but looks cooler
oh wait
cipher=lambda t,s:''.join([c,chr(((n:=ord(c))+s+(d:=~(n&96)))%26-d)][64<n&95<91]for c in t)
91
cipher=lambda t,s:''.join([c,chr(((n:=ord(c))+s+~(d:=n&96))%26-~d)][64<n&95<91]for c in t)
90
cipher=lambda t,s:''.join([chr(((n:=ord(c))-s-~(d:=n&96))%26-~d),c][not n^32]for c in t)
86^
What are we trying to golf now
>>> cipher('abcdefgh',1)
'bcdefghi'
``` it is a caesar cipher i guess
this doesn't work nvm
I'd ignored non-ASCII btw, given the original code only works properly for ascii. (could use [96<n|32<123] or [64<n&~32<91] to fix that, although it's +1 character)
cipher=lambda t,s:''.join([c,chr(((n:=ord(c))+s+~(d:=n&96))%26-~d)][n>>5>1]for c in t)
86
doesn't work for characters after z (cipher("abc{", 1) -> "bcdb")
@wheat river what are we trying to golf
caesar cipher
Shorten this?
pretty much
when the key is 1, all the letters get shifted by 1 (so a -> b, b -> c, etc. and z -> a)
when the key is 2, all letters get shifted by 2 (a -> c, b -> d, ..., y -> a, z -> b)
etc.
!e
exec(bytes('ๆฅฃๆกฐ็ฅใด ๆฐ ๆตกๆขโกโฑด็ โบโงๆจฎๆฅฏโกฎๆกฃโกฒๆผจๆฒๆจโฉโญใถโ ็ซโฉโฅใฒโฌ ใ โคตๆค โฆโนฃ็ฉ็ตๆฐโกฒโฉๆฑฅๆณๆ ็จโ จ็ฏโกคโฅฃโด ใค โทโซโฅณโ ใ โถโซในโฉๆฉๆ ๆคฎๆ
ณ็ฌๆ
จโคจๆ ็ฌโฅโฃๆฝฆโฒโฃๆนฉ็ โฉ','u16')[2:])
@sick hound :warning: Your 3.11 eval job has completed with return code 0.
[No output]
hehe bytes
that's longer though
oh
also, we usually count in bytes and not characters
not sure what that means
ASCII characters take up only 1 byte, but other characters (usually in degen solutions) take up more than 1 byte
eg ๆฅฃ is 1 character, but it might take up 2 or 3 bytes instead
- the function is called
cipher, you can't change that - it has to preserve case (uppercase should remain uppercase and lowercase should remain lowercase)
- it should leave non-alphabetic characters alone
>>> cipher("abcABCuvw@{", 5)
'fghFGHzab@{'
``` here's a testcase if you need one
yea, i cant get the range right with the bit shifts
wrong channel
wrong world ๐ฆ
? ๐ญ
what is a u16? utf-16?
low-level type. guessing unsigned 16-bit int
88 ```py
cipher=lambda t,s:''.join(chr([n:=ord(c),(n+s+~(d:=n&96))%26-~d][64<n&95<91])for c in t)
no it is actually an alias for utf16
wow, docs are now in dark theme! awesome!
since when?
python/python-docs-theme#44
It's been in progress for... 3 years apparently. Was finally merged last week
i love it
Looks like it only applies to the dev docs (i.e. py3.12) atm though
I kind of like how the dark theme uses the Monokai theme for syntax highlighting despite the fact I think it's kind of overrated
Nice, good find
!e
unused=b'\x50K\3\4'+b'\0'*26+b'+(\xca\xcc+\xd1P\xcfHL\xceNMQ\xc8\xc9\xcfQ\xd7\4\0PK\1\2'+b'\0'*6+b'\1'+b'\0'*9+b'\x15'+b'\0'*7+b'\13'+b'\0'*17+b'__\x6da\x69n__.\x70y\x50K\5\6'+b'\0'*8+b'9\0\0\0003\0\0\0'
i=__import__
i("runpy").run_path(i("py_compile").compile(__file__))
@radiant anchor :white_check_mark: Your 3.11 eval job has completed with return code 0.
hacked lol
Files with disallowed extensions can't be uploaded: .pyc
Is this somehow encoding text in the operators?
thatโs so stupid lol. why would it prioritise a zip when it has a pyc headerโฆ
I have sever, root and intermediate certs. Where should these be uploaded so that i don't get SSL error when I establish a connection to the url endpoint using python get and post methods?
Basically i have a python script to access a url endpoint
That fails as we have a self signed certificate
But i have all the self signed certificate with me
The root intermediate server and chain
Now which among these should I add to make the secure post request to the url?
And where should these be added?
This is the wrong channel for this sort of question; #โ๏ฝhow-to-get-help
no
Hey
I'm trying to golf something
Basically i need to find all numbers in a file that are a power of 3
What I'm doing rn is
print(len(*"".join(["","1"][math.log(int(i.strip()),3)] for i in open("file.txt")))
And i get some weird results from it
I forgot that i do .is_integet() after that log()
It gives me a generator object genexpr
What is this queue parameter in airflow??
this isn't a help channel
Depends
!e ```py
class Whatever:
def init(self, msg, amount):
self.msg = msg
self.amount = amount
def print(self):
print(f"#{self.amount}: {self.msg*self.amount}")
fake_inst = type("", (), {})()
Whatever.init(fake_inst, "message ", 10)
Whatever.print(fake_inst)
@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
#10: message message message message message message message message message message
instances are for losers
this is a โ instance
fake_inst = type("", (), {})()
shhh
no one needs to know
You can just do Whatever.__init__(Whatever, "message ", 10), no need for the fake instance :P
โซ,l[i]+=x
?
!e ```py
l=l[0]=[0]
l[0]+=l,
print(l)
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
[[...], [...]]
@rain sluice
thx lemme try it
is l supposed to be the value
or the list
beginner python programmer so pretty new
you shouldn't be in this channel then
then where
that'll take ages
maybe try and ask in #python-discussion or open a thread in #1035199133436354600 because this channel will only confuse you the further you try to investigate here
X=[1,2,3,4,5]
y=[(X.insert(xi*2, 'inserted'), 5-xi)[-1]
for xi in tuple(X)]
print(X, y, sep='\n')```
?
Is it possible to shorten this into one line?
class Solution(object):
def searchInsert(self, nums, target):
x = nums
if target in nums:
return x.index(target)
else:
x.append(target)
return x.index(target)
I tried doing this but it turns out x.appen(target) returns a None.
return nums.index(target) if target in nums else nums.index(nums.append(target))
This should work
return nums.index(target) if target in nums else (len(nums), nums.append(target))[0]
it works thank you
return (nums.append(target), nums.index(target))[1]
The thing is, it shouldn't append if it's there
I just realized I forgot to add .sort() to the thing rip
(+class)
Solution = type("Solution", (object,), {"searchInsert": lambda self, nums, target: nums.index(target) if target in nums else (len(nums), nums.append(target))[0]})
Solution=type("Solution",(),{"searchInsert":lambda s,n,t:(t in n and(n.index(t),)or(len(n),n.append(t)))[0]})
Nice
Solution=type("Solution",(),{"searchInsert":lambda s,n,t:(t in n or n.append(t),n.index(t))[1]})
``` does this work?
Solution=type("Solution",(),{"searchInsert":lambda s,n,t:[n.append(t)]*(t in n)and n.index(t)})
I'm pretty sure that appends t no matter what
def perfect(n):
divs = [1]
i = 2
while i != n and n != 1:
if n % i == 0:
divs.append(i)
i +=1
else:
i +=1
dsum = sum(divs)
if dsum == n and n != 1:
return True
else:
return False
is this a "good" answer to the perfect number question?
That's not the right channel for such a question
but yes, this is a good answer
!e
def perfect(n):
divs = [1]
i = 2
while i != n and n != 1:
if n % i == 0:
divs.append(i)
i +=1
else:
i +=1
dsum = sum(divs)
if dsum == n and n != 1:
return True
else:
return False
print(perfect(6))
@finite blaze :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
i think the class name isn't needed
also short circuiting optimizations (87) ```py
Solution=type("",(),{"searchInsert":lambda s,n,t:1>(t in n)==n.append(t)or n.index(t)})
just using the class is shorter (82) ```py
class Solution:
def searchInsert(s,n,t):
if(t in n)<1:n+=t,
return n.index(t)
I'd say a "good" answer would be not using brute force and using euclid-euler and lucas-lehmer
and for your current solution first loop can be replaced by a for loop
and
if cond:
return True
else:
return False
is just return cond
class Solution:searchInsert=lambda s,n,t:1>(t in n)==n.append(t)or n.index(t)
what if list.appendindex existed
what would its behaviour be?
actually what about list.indexdefault
what would its behaviour be?
same thing as n.indexdefault(t) in what we're trying to do above
yeah ik that. im asking which part of that you're trying to do
i already knew that it would be for what you were doing above
what im asking is which part of that it would be used for
i.e., what would it do (hence the question, "what would its behaviour be")
like append if the value isn't in the list and return its index?
ah
it would be so simple
we could just do staticmethod(list.indexdefault)
hmm, is there a way to add other functions to lists etc?
staticmethod(list.indexdefault)
lambda s,n,t:n.indexdefault(t)
ok
that'd be interesting, but not very practical i think
yay ```pycon
a = []
a.indexdefault(2)
0
a
[2]
!e fishhook ```py
from fishhook import hook_cls
@hook_cls(list)
class _:
def indexdefault(self, value):
for i, obj in enumerate(self):
if obj == value:
return i
i = len(self)
self.append(value)
return i
a = []
print(a.indexdefault(2))
print(a)

