#esoteric-python
1 messages ¡ Page 32 of 1
!e
minimum_number=m=lambda n:~-all(sum(n)%i for i in range(2,sum(n)))and-~m(n+[1])
print(m([1, 2, 3]))
@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
1
/run
for i in range(10): print("esoteric programmer is 10x great")
The command is !e, not /run
!e
[print(text:=''.join(chr(v)for(v)in([((2**0)|((2**2))|((2**5))|((2**6))), ((2**0)|((2**1))|((2**4))|((2**5))|((2**6))), ((2**0)|((2**1))|((2**2))|((2**3))|((2**5))|((2**6))), ((2**2)|((2**4))|((2**5))|((2**6))), ((2**0)|((2**2))|((2**5))|((2**6))), ((2**1)|((2**4))|((2**5))|((2**6))), ((2**0)|((2**3))|((2**5))|((2**6))), ((2**0)|((2**1))|((2**5))|((2**6))), ((2**5)), ((2**4)|((2**5))|((2**6))), ((2**1)|((2**4))|((2**5))|((2**6))), ((2**0)|((2**1))|((2**2))|((2**3))|((2**5))|((2**6))), ((2**0)|((2**1))|((2**2))|((2**5))|((2**6))), ((2**1)|((2**4))|((2**5))|((2**6))), ((2**0)|((2**5))|((2**6))), ((2**0)|((2**2))|((2**3))|((2**5))|((2**6))), ((2**0)|((2**2))|((2**3))|((2**5))|((2**6))), ((2**0)|((2**2))|((2**5))|((2**6))), ((2**1)|((2**4))|((2**5))|((2**6))), ((2**5)), ((2**0)|((2**3))|((2**5))|((2**6))), ((2**0)|((2**1))|((2**4))|((2**5))|((2**6))), ((2**5)), ((2**0)|((2**4))|((2**5))), ((2**4)|((2**5))), ((2**3)|((2**4))|((2**5))|((2**6))), ((2**5)), ((2**0)|((2**1))|((2**2))|((2**5))|((2**6))), ((2**1)|((2**4))|((2**5))|((2**6))), ((2**0)|((2**2))|((2**5))|((2**6))), ((2**0)|((2**5))|((2**6))), ((2**2)|((2**4))|((2**5))|((2**6)))])))for(n)in(range((((-~int().__add__(-~int())).__pow__(-~int())).__add__(((-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()).__add__(-~int())))))))]
@karmic pumice :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | esoteric programmer is 10x great
002 | esoteric programmer is 10x great
003 | esoteric programmer is 10x great
004 | esoteric programmer is 10x great
005 | esoteric programmer is 10x great
006 | esoteric programmer is 10x great
007 | esoteric programmer is 10x great
008 | esoteric programmer is 10x great
009 | esoteric programmer is 10x great
010 | esoteric programmer is 10x great
oh nice 
I can see a lot of different alternatives to
~-all(sum(n)%i for i in range(2,sum(n)))
like for example
sum(sum(n)%i<1 for i in range(2,sum(n)))
but I dont see how to save another character
I guess we could do
i believe in the 2nd one you can remove the space before the for
and maybe if you use sum 3*times walrusing it into a 1character can help but idk
!e
minimum_number=m=lambda n:~all(sum(n)%i for i in range(2,sum(n)))and-~m(n+[1])
print(m([1, 2, 3]))```
@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 2, in <module>
003 | print(m([1, 2, 3]))
004 | ^^^^^^^^^^^^
005 | File "/home/main.py", line 1, in <lambda>
006 | minimum_number=m=lambda n:~all(sum(n)%i for i in range(2,sum(n)))and-~m(n+[1])
007 | ^^^^^^^^
008 | File "/home/main.py", line 1, in <lambda>
009 | minimum_number=m=lambda n:~all(sum(n)%i for i in range(2,sum(n)))and-~m(n+[1])
010 | ^^^^^^^^
011 | File "/home/main.py", line 1, in <lambda>
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/HIN2NH6SAXVQXBBNIVLVNELAEE
that one needs a &1 before and
i visualized it before
!e
minimum_number=m=lambda n:~-all(sum(n)%i for i in range(2,sum(n)))and-~m(n+[1])
print(m([1, 2, 3]))```
@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
1
oh ye. 78
minimum_number=m=lambda n:sum(sum(n)%i<1for i in range(2,sum(n)))and-~m(n+[1])
rip walrus wont help here
timed out
on which input?
[891, 30, 977, 277, 83, 7, 65, 177, 100, 19, 5, 248, 2, 502, 50, 98, 52, 891, 507, 9, 3, 653, 4, 45, 894, 2, 8, 36, 3, 5, 9, 3, 6, 858, 566, 2, 3, 64, 10, 676, 64, 38, 3, 28, 53, 8, 6, 5, 10, 81, 446, 562, 5, 71, 74, 255, 453, 261, 49, 825, 9, 2, 326, 84, 114, 21, 307, 69, 289, 67, 3, 109, 48, 937, 927, 61, 70, 2, 549, 3, 818, 88, 32, 7, 2, 46, 3, 275, 571, 47, 17, 64, 410, 981, 3, 800, 3, 458, 50, 194, 6, 732, 8, 74, 10, 240, 6, 3, 3, 245, 640, 424, 79, 95, 9, 4, 22, 10, 772, 10, 267, 369, 86, 4, 10, 2, 8, 13, 59, 35, 98, 2, 723, 564, 98, 76, 9, 846, 66, 929, 102, 5, 2, 14, 3, 9, 261, 8, 7, 48, 9, 10, 4, 4, 89, 459, 940, 868, 49, 29, 502, 16, 70, 17, 591, 98, 15, 10, 6, 24, 620, 8, 9, 3, 3, 482, 27, 8, 67, 8, 58, 307]
That doesn't time out for me locally
can't you just remove the =m
eh we can't have it if cw times it out
but its used for the recursive call
although it's probably correct
o
CW timing out is so bs ngl
Then try this 78
minimum_number=m=lambda n:any(sum(n)%i<1for i in range(2,sum(n)))and-~m(n+[1])
We are probably really close to the time limit
iirc they can remove solutions that pass 50/50
happened to one of my solutions lmao
One codegolf trick I hoped I could use with the sum version was to do s=sum, like
minimum_number=m=lambda n,s=sum:s(s(n)%i<1for i in range(2,s(n)))and-~m(n+[1])
but it unfortunately doesn't save any characters
yeah
man late-bound defaults would be so useful
sum is already kinda short so to make shortening worth you need to use sum more than 3 times and then it becomes worth i guess
sum [3]
s [1]
,s=sum [6]
6/(3-1)=3
i guess so yeah
idk if my math is right lmao đ đ
i think wilson's theorem would have a use here like they did in CGSE but hmm
so far my attempts are unsuccessful
wait a second
any(sum(n)%i<1for i in range(2,sum(n))) this part just checks prime right
yep
>>> any(sum(n)%i<1for i in range(2,sum(n)))
<stdin>:1: SyntaxWarning: invalid decimal literal
True
>>> sum(n)
6``` somethings wrong
actually it's to check if something divides sum(n) now
it's an improvement from ~-<check prime>
Techincally it is a check for if sum(n) is not a prime (i.e. sum(n) is a composite number or equal to 1)
minimum_number=m=lambda n:~-(pow(3,sum(n)-1,sum(n))==1)and-~m(n+[1])
68
test failed
m([1,1,1]) == 2, not expected value 0
you need to find the correct number
Time: 733ms Passed: 104 Failed: 1 Exit Code: 1
minimum_number=m=lambda n:~-(pow(4,sum(n)-1,sum(n))==1)and-~m(n+[1])
you just change it until it works
theres like a chance of it failing
oh my god
random chance
yep
is this even allowed
lol

The Fermat primality test is a probabilistic test to determine whether a number is a probable prime.
random chance golf fork
63 ```py
minimum_number=m=lambda n:~-pow(4,t:=sum(n)-1,t+1)and-~m([t+2])
lol
oh wow it's performant again
59 ```py
minimum_number=m=lambda n:~-4**~-sum(n)%sum(n)and-~m(n+[1])
someone needs to test what the best first number is
the 78 thing still stands as "always works"
yeah because they run random tests
the best solution
what is this science?
60b works 1/2 of the time
76 ```py
from gmpy2 import*;minimum_number=m=lambda n:1>is_prime(sum(n))and-~m(n+[1])
apparently
gmpy2 was available
genius-level golf
lmao
why
why does gmpy2 exist in cw
it's so unfair
69 ```py
from gmpy2 import*;minimum_number=lambda n:next_prime(s:=~-sum(n))+~s
nice
ik,r
what other cw installed libraries are there
scipy and numpy are iirc
this might be all pydis but i'm not sure
i mean it's xelf, you and i assume hybrid
do we have the minimum yet
check
59b probabilistic, 69b w/ package, 78b pure (degen 51c, 56c, 60c respectively)
hha sure
lol
i mean my answer to that is 47b in length
I think that is techincally also a random solution since the documentation for next_prime is
next_prime(...)
next_prime(x) returns the next probable prime number > x.
yeah but thats probably miller rabin

which is just my solution but better
but easier to golf
it has passed about 7 full test attempts i just did rn
https://docs.rs/glass_pumpkin/latest/glass_pumpkin/ just runs fermat as a pre-test
A crate for generating large prime numbers, suitable for cryptography.
so it must be extremely good at doing what it's doing
shocker
prime tester used by rsa is good at testing primes???
1 round is about 3/4 chance of being correct
nvm scratch that
i didn't call all()
!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
a = ['02', '12', '20', '21', '22', '22', '23', '24', '25', '26', '27', '28', '29', '32', '42', '52', '62', '72', '82', '92']
b = ['08', '18', '28', '38', '48', '58', '68', '78', '80', '81', '82', '83', '84', '85', '86', '87', '88', '88', '89', '98']
matching_strings = [element for element in a if element in b]
print(matching_strings)```
@glass wyvern :white_check_mark: Your 3.11 eval job has completed with return code 0.
['28', '82']
!e ```py
a = ['02', '12', '20', '21', '22', '22', '23', '24', '25', '26', '27', '28', '29', '32', '42', '52', '62', '72', '82', '92']
b = ['08', '18', '28', '38', '48', '58', '68', '78', '80', '81', '82', '83', '84', '85', '86', '87', '88', '88', '89', '98']
print([*{*a}&{*b}])
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
['82', '28']
!e ```py
from einspect import impl
from gc import get_objects
@impl(set)
def invert(self):
t = get_objects()
a = {*()}
for x in t:
try:
a.add(x)
except TypeError:
pass
return a - self
print(~{5}-~{3})
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
{ANY_ALL}
Wtf
wat
What is ANY_ALL
also since when did we switch to einspect
it's equal to 3
what object
Any_all
!e ```py
from einspect import impl
from gc import get_objects
@impl(set)
def invert(self):
t = get_objects()
a = {*()}
for x in t:
try:
a.add(x)
except TypeError:
pass
return a - self
x=(~{5}-~{3})
print(type(x.pop()))
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
<class 're._constants._NamedIntConstant'>
Ok
But this isn't correct behaviour. If I invert a set, and then create a new object, that object should still be part of the set.
there is a practical solution which is to have a regular set and a flag denoting whether it's inverted
then __contains__ just flips based on the flag, and pop() returns a random object (and adds it to the inner set) from gc if inverted
Technically it is intersection of sets and not union
can this be count as golfing?
def stringy(size):
return ('10'*((size//2)+(r:=size%2))).__getitem__(slice(None, [None, -1][r]))
for the problem at
https://www.codewars.com/kata/563b74ddd19a3ad462000054/train/python
well, could you elaborate on the code?
It's not the best or the easiest way to solve it but I'm just playing around, so given size 4 for example, if we multiply the string '10' by half of that we get what we need '1010', but it's not always even, 3 for example, you will multiply it once so you will get '10' and missing a '1' so from open parenth 3 what I'm doing is + 1 if the size is even so I can get a '1010' in case of 3, then the other part of the line is about removing that extra zero in the end again depending on size given if it's even or odd,, i made a slice object that would either stop and not include the last element (-1) or include it (None; meaning all of the string) and choosing between those depends on remainder again which I put into a variable when I firstly calculated it at parenth 3, and I did this choice using the double brackets trick, first one is a list and the other is the index that depends on a boolean value. i hope I managed to explain it, cuz it's hard to explain on a single line lol
@livid geyser
Why not "10"*(size//2)+"1"*(size%2)?
@quartz wave, hi, sorry for the ping, you remember you helped me 2 weeks ago with the golfing code? Just letting you know: I finally got it under 1k, exactly 999 bytes. Thanks for help back then! <3
Or maybe ("10"*99999)[:size]
yeah that was one of the solutions I had but I wanted to try this method
and this is the best approach yeah
("10"*(-~size//2))[:size] if you want it to work for any number
idk what the ~ does
same as -1-x
Bitwise not
-~x is essentially x+1 but with higher precedence than multiplication/division
so -~size//2 is the same as (1+size)//2?
Yeah
Yep, just without the brackets :)
The ~ and - both are unary operators, so they come first
alr thx for the help, I'm going to look more into bitwise operations
Although 1+size//2 would also work in this case regardless of precedence
Or I guess you could just use size on its own
("10"*size)[:size]
stringy=lambda s:("10"*s)[:s]
would work but not the same yeah, you always add one without the brackets when it's odd, but in the other you add even if it's even idk lol
Since it's getting sliced to the correct length either way
yeah yeah
It doesn't matter as long as it's at least as long as size itself
ik, i'm just trying not to get confused, and how it solved a problem I had when I tried to solve it initially, so I had smth like return ('10'*((size//2)+1)).__getitem__(slice(None, [None, -1][size%2])) but it didn't work cuz I had extra in the end so I added the remainder part to when to add that one, but now I can add the one before the floor division and the problem should be solved: return ('10'*((-~size//2))).__getitem__(slice(None, [None, -1][size%2])) I know this __getitem__ part can just be made with the [:size] and could avoided the problem from the start and tha'ts how I solved it firstly, but I just wanted to only use whether the size is even or odd so I ended up with this so it can work
i had extras with even number cuz of how it always add, like I said in what I'm repying to. But not it only adds a 1 after the whole operation when it's even
if condition:
do_this()
do_this() if condition else None
condition and do_this()
not condition or do_this()
while condition:
do_this()
break
(__:=__import__("itertools").filterfalse,
*__(lambda _:do_this(),
[*__(lambda _:not _,[condition])]))
_.__code__=[(_:=(lambda:...)
).__code__.__class__(0,0,0,0,1,67,
b't\x00r\x07t\x01\x83\x00\x01\x00d'
b'\x00S\x00d\x00S\x00', (None,),
('condition', 'do_this'),(),"","_",1,
b'\x04\x01\n\x01\x04\xff')][0];_()
(lambda: ..., do_this)[condition]()
That's a good one
what does ... do? nth? it says it's a pass statement or smth. This is cool damn. I love this golfing thing
@austere mauve :white_check_mark: Your 3.11 eval job has completed with return code 0.
(<class 'bool'>, <class 'int'>, <class 'object'>)
... is a syntax for constant Ellipsis
True is similar to 1 and False is similar to 0.
!e ```py
print(...)
print(Ellipsis)
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Ellipsis
002 | Ellipsis
... doesnt do anything special by itself
some libs can interpret however they want. numpy for example uses ... for slices
i see, lambda allow you to have inner functions that you can index?
no, im not indexing lambda
im indexing tuple that contains two functions: do-nothing-lambda and do_this function
My next way with itertools: ```py
[*map(lambda :(),import("itertools").takewhile(lambda _ condition,[do_this]))]
I can't believe that I missed this
for _ in range(condition):
do_this()
Going further with integer-similar booleans:
try:
1/condition
except:
do_this()
exec("do_this" + "()"*condition)
Even better:
exec("do_this()"*condition)
for _ in iter(lambda: condition, True):
do_this()
break
similar to while-example there 
!e exec("")
@gleaming linden :warning: Your 3.11 eval job has completed with return code 0.
[No output]
@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 | eval("")
004 | File "<string>", line 0
005 |
006 | SyntaxError: invalid syntax
Ah, eval doesn't allow empty strings
It has already been done
Here is another one (similar to the one before, but instead of creating a new function, it uses an existing one):
exec(do_this.__code__.replace(co_code=do_this.__code__.co_code*condition+b"d\x00S\x00"))
But it is the mix of earlier concepts, not a "brand new" approach.
how about ```py
exec(do_this.code.replace(co_code=~condition%2*b"d\x00S\x00"+do_this.code.co_code))
Isn't it just rewording of the above example? Well, it definitely accomplishes the task of being even less readable.
@fleet bridge ended up writing an extension module to get the memory writes to work, now im working on making sure it works crossplatform
A bit more invasive, exception-based approach:
import sys
_=sys.excepthook
sys.excepthook=lambda a,b,c:[setattr(sys,"excepthook",_),do_it()]
assert ~-condition
what golfing are we doing now
!e print(âHello Worldâ)
!e print(âHello Worldâ)
!e exec(âprint(âHello Worldâ)â)
Ah
!e print('dumb bot')
why
Thanks
the bot works perfectly fine
ig
this is probably the wrong channel then
Youâre right. I missed the bot commands channel
103 cw kata ```py
first_non_repeating_letter=lambda s:s[(t:=len([*iter(map(s.lower().count,s.lower()).next,1)])):t+1]
102 ```py
first_non_repeating_letter=f=lambda s,t=0:f(s,t+1)if-~len(S:=s.lower())-t>1<S.count(S[t])else s[t:t+1]
100 ```py
first_non_repeating_letter=lambda s:s[(t:=len([*iter(map((S:=s.lower()).count,S).next,1)])):t+1]
97 ```py
first_non_repeating_letter=lambda s:[*s,""][len([*iter(map((S:=s.lower()).count,S).next,1)])]
91 ```py
first_non_repeating_letter=lambda s:next((x for x in s if 2>s.lower().count(x.lower())),"")
first_non_repeating_letter=lambda*a:type("",(),{"__eq__":lambda*s:1})()
that can probably be shortened more but i gtg now :<
very cheaty
I think that's against codewars policy
could you explain how this one works?
It's cheating: It's a function that returns an object that's equal to everything. Presumably the function is tested like this:
assert first_non_repeating_letter("aabbc") == "c"
which... yeah.. works.
how can an object be equal to everything?
Objects can define a method called __eq__ that gets another object to compare to and returns whether it's equal to the other object.
If that method always returns True (or equivalent), it is equal to everything.
!e
class ETE:
def __eq__(self, other):
return True
print(23 == ETE())
@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
I think you also can set trace function, and then fix result to be correct
Or look at bytecode of checking function
That's surely longer though
Yes, but might be interesting for someone
lol...
lmao
class F(str):__eq__=lambda*_:1
first_non_repeating_letter=F
in general type() calls are verbose and not super golfy
!e
class F:self.__eq__=lambda*_:1
first_non_repeating_letter=F
print(first_non_repeating_letter("moonman") == n)```
@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 | class F:self.__eq__=lambda*_:1
004 | File "/home/main.py", line 1, in F
005 | class F:self.__eq__=lambda*_:1
006 | ^^^^
007 | NameError: name 'self' is not defined
!e
class F(str):self.__eq__=lambda*_:1
first_non_repeating_letter=F
print(first_non_repeating_letter("moonman") == n)```
@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 | class F(str):self.__eq__=lambda*_:1
004 | File "/home/main.py", line 1, in F
005 | class F(str):self.__eq__=lambda*_:1
006 | ^^^^
007 | NameError: name 'self' is not defined
ic
!e
class F(str):__eq__=lambda*_:1
first_non_repeating_letter=F
print(first_non_repeating_letter("moonman") == n)```
@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 4, in <module>
003 | print(first_non_repeating_letter("moonman") == n)
004 | ^
005 | NameError: name 'n' is not defined
!e
print(len("""
class F(str):__eq__=lambda*_:1
first_non_repeating_letter=F"""))```
@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
111
that's definitely not 111 chars
real
59
!e
print(len("""
class F(str):__eq__=lambda*_:1
first_non_repeating_letter=F"""))```
@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
60
\n in the beginning
if we're doing this why not just ```py
class first_non_repeating_letter(str):eq=lambda*_:1
can you use __eq__=slice or does the method descriptor not bind
yeah it's possible
!e
__import__("fishhook").hook(str)
def __eq__(): return True
first_non_repeating_letter=lambda _:""
print(first_non_repeating_letter("m") == "n")```
@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
first_non_repeating_letter=F()
you must create instance
!e
import fishhook
fishhook.hook(str)
def __eq__(): return True
first_non_repeating_letter=lambda _:""
print(first_non_repeating_letter("m") == "n")```
@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
__eq__ takes 2 args, not 0
"".join would be a shorter version of lambda _:"" :)
!e
__import__("fishhook").hook(str,name="__eq__")(lambda*_:1)
first_non_repeating_letter="".join
print(first_non_repeating_letter("m") == "n")
@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.
1
you can also just use str or am I missing something?
You're right
Doesn't matter if it's empty though
empty will evaluate to false:
!e
__import__("fishhook").hook(str,name="__eq__")(lambda*_:1)
first_non_repeating_letter=str
print(first_non_repeating_letter("m") == "n")
@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.
1
!e ```py
class F(str):eq=str
first_non_repeating_letter=F
print(bool(first_non_repeating_letter("repeatrepeat") == ""))
@austere mauve :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
first_non_repeating_letter=__import__("fishhook").hook(str,name="__eq__")(lambda*_:1)
this also works
fishhook in cw?
cw?
codewars
this from codewars?
here
oh đ
I've found the shorter always-true condition function: id instead of lambda*_:1
!e ```py
class first_non_repeating_letter(str):eq=id
print(bool(first_non_repeating_letter("repeatrepeat") == ""))
print(bool(first_non_repeating_letter("a") == "a"))
print(bool(first_non_repeating_letter("aAd~~fGDF") == "G"))
@austere mauve :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | True
002 | True
003 | True
Is it possible to it shorter in any way?
feels like the bool is cheating
in a vibe sense
1 == True so 1 is fine, an arbitrary int is ehh
still truthy but changes the expected output a little too much
my idea: py class first_non_repeating_letter(str):__ne__=callable but __eq__ doesnt delegate to __ne__ :(
this works for all strings without :'\0' symbol
!e ```py
class first_non_repeating_letter(str):eq=all
print(first_non_repeating_letter("repeatrepeat") == "")
print(first_non_repeating_letter("a") == "a")
print(first_non_repeating_letter("aAdfGDF") == "G")fGDF") == "\0")
print(first_non_repeating_letter("aAd
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | True
002 | True
003 | True
004 | True
>>> all('\0')
True
``` why? i dont get it
ah, iterating over string returns characters, not their int values
and all 1-char strings are truthy
class f(str):__eq__=id
__getattr__=lambda*s:f
45
The task requirement is that there is a callable first_non_repeating_letter. Of course, because we are analyzing "cheating" solutions, it doesn't matter whether there is such variable, we only want that test suites succeed with as little code as possible. As in python there is no script-wide __getattr__ magic method, when trying to access first_non_repeating_letter, your function won't be called. Also, even if your code would work, it is likely that it would actually break the tests suite as any variable (like the module for creating tests) would become this class. We want to pass the tests, not crash them.
it works
you can test it
it's because module level getattr
the test does from solution import first_non_repeating_letter
which calls the module level getattr to be called
here ya go
Special names
__getattr__and__dir__can be also used to customize access to module attributes. The__getattr__function at the module level should accept one argument which is the name of an attribute and return the computed value or raise anAttributeError. If an attribute is not found on a module object through the normal lookup, i.e.object.__getattribute__(), then__getattr__is searched in the module__dict__before raising anAttributeError. If found, it is called with the attribute name and the result is returned.
depend on how it's tested
yeah
if it's a module or execed then rad!
but anyway, i hope that cleared up the confusion :3
i gtg now so have a nice day everyone <3
byee
Technically this could break on non-CPython, if you'd get id 0. Or is it guaranteed that the id of an object is non-zero?
it is only guaranteed to be an integer distinct from the id()s of other living objects
im not the one who came up with the id trick ÂŻ_(ă)_/ÂŻ
though if CPython isnt guaranteed, dir works
how does this work?
that's possible?
pypy does not return addresses for id, so it might be possible to get an id of zero
waht do we golf now
it's not against the specification
and it could happen in cpython, if you were using a platform that would allocate userspace memory there
which basically doesn't exist, outside of embedded stuff
who would've guessed all the golfing practice actually came in useful
1 lemon for the first person who deciphers this
d_col = [...]
c_col = [...]
res = sum(y if max(i if x else 0 for i, x in zip(range(4, 51), c_col)) <= j else 0 for j,y in zip(range(4, 51), d_col))
d_col = [...]
c_col = [...]
rng = range(4, 51)
res = sum(y for j, y in zip(rng, d_col) if max(i for i, x in zip(rng, c_col) if x) <= j)
d_col = [...]
c_col = [...]
rng = range(4, 51)
res = sum( # sum
y for j, y in zip(rng, d_col) # of all items in D
# such that
if max( # last
i # index
for i, x in zip(rng, c_col) if x # of nonzero value in C
) <= j # less than index of item in D
)
C D
2 7
0 7
0 7
0 7
2 7
2 7 <= sum of all D from here
0 7
0 7
0 7
0 7
0 7
correct!
đĽł
you get one lemon đ
i put it in my nickname
specifically, C is a checkmark meaning absolute / delta
so if we did a transfer, we'd just put the deltas
if we did a stocktaking, we'd put the actual number and put a check
that formula does a tally of the lastest stocktaking + all the deltas since then
How do this in the shortest way possible?
a + (b * [1, -1][CONDITION])
if I have two variables a, and b and based on a condition I would either add b to a or the negative or b to a (subtract it from it), and that's what I have
a+(b*(1|-CONDITION))?
hello my esoteric lovers
# Method 1 - clean cut approach
name = input("> What's your name?")
if name == "bedros":
print("- Welcome!")
else:
print("- Hm, you're not allowed here")
# The logic is easy to comprehend - if the name is bedros, allow, else restrict
#Method 2 - Inverted approach
name = input("> What's your name?")
if name != "bedros":
print("- Hm, you're not allowed here")
else:
print("- Welcome!")
# The logic is still easy to comprehend -
# if the name is not bedros, do not allow - otherwise, allow
# Method 3 - "i dont like typing" approach
name = input("> whats ur name?\n- ")
if name!="bedros": print("not allowed")
else: print("allowed")
# Method 4 - why more code when can less
print("allowed" if input("> whats ur name\n-") == "bedros" else "not allowed")
# Method 5 - i dont know what to call this
for i in [["allowed","> whats ur name\n","bedros","not allowed"]]: print(i[0] if input(i[1]) == i[2] else i[3])
# Method 6 - i dont know what to call this v2
[print(x[0] if input(x[1]) == x[2] else x[3]) for x in [["allowed","> whats ur name\n","bedros","not allowed"]]]
# Method 7 - when will this end
[["allowed","> whats ur name\n","bedros","not allowed"]].sort(key = lambda x : print(x[0] if input(x[1]) == x[2] else x[3]))``` here I lay out some methods to get a task done in the most esoteric way, starting from normal ways and increasing in a scale of esoteric-ness
Interested to see what the people here come up with đ
i use .sort as a foreach which I personally find hilarious đ
a foreach to access one element, which makes it even funnier for me
I want to see how much funnier this can be đ
print("not "*(0<0 .from_bytes(input("> whats ur name\n").encode('u8'))-108187616440179)+"allowed")
đ
ego destruction
here i was making a code triangle and bro pulls up with the .encode classic obfuscation method and got me weeping
[["allowed","> whats ur name\n","bedros","not allowed"]].sort(key = \
lambda x : print(x[0]\
if input(x[1]) == x[2] \
else x[3])\
)```
not by much i mean i know this is where the esoteric python pros live, always funny to see stuff like this
i'm on my first steps to joining this cult
their natural habitat
truly
i fear the day we let the esoteric pros release code into prod
how funny would it be if one day, the esoteric pros decided to raid github and make PRs saying cleaned code with the most esoteric code "fix" known to man
encryption with esoteric
obfuscate the whole codebase behind b64 encoding and pass it through eval
i got a better one ```py
print("not "(0!=0 .from_bytes(b'%c'~-(t:=input("> whats ur name\n")).count("")%(*map(ord,t),))-hash(0x2000626564726f72))+"allowed")
i love this đ
That all is pretty simple. You can tell what this code is doing by looking at it.
ghost ping because file upload - https://paste.pythondiscord.com/WGRA
trueâŚ
t-twue... :3
Thanks, didn't know that. Now I know why your code didn't work for me - to test it I used interactive shell.
An example code for cheating cw challenges: for each task there are tests which it has to pass. To check it, a simple comparison equation is needed. If you create an object that always successfully matches with any object, it should solve most of the challenges on cw. The actual part of the cheating solution is the first line class <required_function_for_challenge>(str):__eq__=id. id is used here as always-truthful function. Before lambda*_:1 was used but id is shorter. It works, because id just returns pointer address and of course, no python object would be located on address 0. The class inherits from str in order to also pollute the __init__ function.
Ah, I see. Wouldnât work for negative cases though, right?
id cant be negative
At least in CPython
But it is not important
Every nonzero id would work
Vut?
It increases in a scale, I never claimed to be good at it đ
It's not so much a scale of how esoteric it is, more just a scale of how stupid it is - it's all quite simple, I agree, but it has a certain element of humor, using Python in a way that makes someone go "well... why???"

No, I mean; some test cases may check if a == b (positive?) in which this solution would work, but in the inverse a != b, it wouldnât work
Do NOT run in qpython
huh
Crash
whar
Wanted to see what it would give when ran and it crashed my phone
Mega trolled
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
all of the test cases are ==
this is guaranteed because we can see the test cases
Ah okay
Havenât done cw challenges before
Leetcode is more extensive I think
they (cw) give example test cases which you can see, and then have more extensive tests which you cant
BUT they show you stderr and stdout of your code
so you can use inspect or open(__main__.__file__), etc. to print the contents of the test cases
.kata
alr so
recursion?
works here too
but about normal solution - just a loop
or math formula
57b w/o recursion
send cood
solution=lambda x:sum(x for x in range(x)if{x%3,x%5}&{0})
54b w/ recursion ```py
solution=s=lambda x:0<(x:=x-1)and s(x)-~-(x%3>0<x%5)*x
solution=lambda x:sum(x for x in range(x)if x%3|x%5)//2
``` less bytes, but answer is approximate
you are so good...
actually this worked by luck with random input
normally it won't work
52b luck ```py
solution=s=lambda x:x>2and s(x:=x-1)-~-(x%3>0<x%5)*x
52b ```py
solution=lambda x:sum({*range(0,x,3),*range(0,x,5)})
51b missed that negative x should return 0
solution=s=lambda x:x and s(x:=x-1)-~-(x%3>0<x%5)*x
why -~- instead of +1- when it's the same number of characters? Are you only wanting to obfuscate it or is it faster?
there is *x in the end
doesn't this fail when -1 is inputted
yea can't have it
Is that even valid input
Additionally, if the number is negative, return 0.
@quartz wave hi!
this is your repo, right? https://github.com/thatbirdguythatuknownot/sniplections
i'm interested in pypreprocessor.py and have several questions:
- why you choose
$defsyntax instead of#def? - why do you need to surround
$macro$with$? isnt a name itself enough to trigger substitution?
this
would allow us to run black/mypy on this code
also:
- is there a way to make it work with mypy such that mypy sees expanded version? maybe it is possible by using codec:
# coding: preprocessor, and i imagine that if this codec is defined at the moment mypy tries to read the file, coding will be triggered and will be able to preprocess file and give preprocessed version to mypy - (i dont think this would work for pyright)
>>> solution=s=lambda x:x and s(x:=x-1)-~-(x%3>0<x%5)*x
>>> solution(-10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
File "<stdin>", line 1, in <lambda>
File "<stdin>", line 1, in <lambda>
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded```
-
$defbecause#is already used for comments -
i don't want regular names to conflict with macro names
-
idk about making it work with mypy
ok, thanks
yeah
there are solutions which will work with every problem there, but they're longer cause you end up hooking builtin functions
50b
solution=s=lambda x:x>2and s(x:=x-1)+x-x**4%15%2*x
x**4%15%2 is a check for if x and 15 are coprime
How could it be incorrect if it works when you run the code?
i have no idea why your code gives correct result
That -5 in your calc should be 10
bruh, i forgot about that

I dont know if this is the right channel to ask but im using bs4 and requests for a code im working on, however the link im testing on stay constant even though im changing it?
wrong channel
!e
solution=s=lambda x:x>2and s(x:=x-1)+x-x**4%15%2*x
print(s(10))
@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | /home/main.py:1: SyntaxWarning: invalid decimal literal
002 | solution=s=lambda x:x>2and s(x:=x-1)+x-x**4%15%2*x
003 | 23
!e
solution=s=lambda x:x>2&s(x:=x-1)+x-x**4%15%2*x
print(s(10))
@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 2, in <module>
003 | print(s(10))
004 | ^^^^^
005 | File "/home/main.py", line 1, in <lambda>
006 | solution=s=lambda x:x>2&s(x:=x-1)+x-x**4%15%2*x
007 | ^^^^^^^^^
008 | File "/home/main.py", line 1, in <lambda>
009 | solution=s=lambda x:x>2&s(x:=x-1)+x-x**4%15%2*x
010 | ^^^^^^^^^
011 | File "/home/main.py", line 1, in <lambda>
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/IJW2ABXK65XTVACB337LCT2NLU
!e
solution=s=lambda x:x>2 & s(x:=x-1)+x-x**4%15%2*x
print(s(10))
@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 2, in <module>
003 | print(s(10))
004 | ^^^^^
005 | File "/home/main.py", line 1, in <lambda>
006 | solution=s=lambda x:x>2 & s(x:=x-1)+x-x**4%15%2*x
007 | ^^^^^^^^^
008 | File "/home/main.py", line 1, in <lambda>
009 | solution=s=lambda x:x>2 & s(x:=x-1)+x-x**4%15%2*x
010 | ^^^^^^^^^
011 | File "/home/main.py", line 1, in <lambda>
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/EL4ZY37D4ASQARVIS7K3IAYCIU
Bitand & will never work as a replacement for and here. The and is there to stop the function from recursively calling itself when x<=2.
Think of it like a codegolfed version of 0 if x <= 2 else ...
i love the new 3.12 cpython update ```pycon
from ast import *
print(unparse(parse("""...""",optimize=1)))
print(''.join([chr(x) for x in (110, 111, 116, 32)]) * (0 != 0 .from_bytes(bytes([37, 99]) * ~-(t := input(''.join([chr(x) for x in (62, 32, 119, 104, 97, 116, 115, 32, 117, 114, 32, 110, 97, 109, 101, 10)]))).count(''.join([chr(x) for x in ()])) % (*map(ord, t),)) - hash(2305951196830134130)) + ''.join([chr(x) for x in (97, 108, 108, 111, 119, 101, 100)]))
dafuq
print("Hello world")
!e
# double_numbers.py
num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for item in num_list:
num_list[num_list.index(item)] = item * 2
print(num_list)
@hazy void :white_check_mark: Your 3.11 eval job has completed with return code 0.
[16, 2, 12, 4, 10, 6, 14, 8, 18]
here is a challenge: explain the output
!e this might help understand what's going on
num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for item in num_list[::-1]:
num_list[num_list.index(item)] = item * 2
print(num_list)
@proper vault :white_check_mark: Your 3.11 eval job has completed with return code 0.
[2, 4, 6, 8, 10, 12, 14, 16, 18]
doubled things get found first by .index
since they're earlier in the list
!e
# double_numbers.py
num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in range(len(num_list)):
item = num_list[i]
num_list[num_list.index(item)] = item * 2
print(num_list)
@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.
[16, 2, 12, 4, 10, 6, 14, 8, 18]
There is not much to explain
There is a bit of negative indexing going on, but other than that there is nothing weird going on
https://www.codewars.com/kata/57d93978950d8486a3000def/train/python
find_number=lambda c,d=100,b=50,a=1,i=1:[exec("def f(c,d,b,a,i):\n\twhile 1:\n\t\ti+=1\n\t\tif(x:=c(b))==0:return b\n\t\tb-=x*d/(2**i)"),(locals()['f'](c,d,b,a,i))][-1]
use instead of \t
what
how do you type it
space
@gleaming linden :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello
And does it have to be 1 line?
well thats my goal
oh yeah
i just was inconsistent when i first tried so had error
im not sure how can i do it without defining a new function cuz return wont work without a function
can i execute code right in the context of the current function so return will work somehow?
I don't think so
oh wait im dumb
not with exec at least
i can just exec("def find_number(c,d=100,b=50,a=1,i=1):\n while 1:\n i+=1\n if(x:=c(b))==0:return b\n b-=x*d/2**i")
lets go 103 chars 1 line solution
exec("def find_number(c,d=100,b=50,a=1,i=2):\n while 1:\n if(x:=c(b))==0:return b\n b-=x*d/2**i;i+=1")
``` does this work?
exec("def find_number(c,d=100,b=50,a=1,i=4):\n while 1:\n if(x:=c(b))==0:return b\n b-=x*d/i;i*=2")
``` how about this?
nice
since you're just using i for 2**i you may as well just multiply by 2 instead of adding 1
exec("def find_number(c,d=100,b=50,a=1,i=1):\n while 1:\n if c(b)==0:return b\n b-=c(b)*d/i;i*=2")
97 đ
What are you guys saving from using exec?
1lining
Oh, so it is not to make shorter code?
yes
1lining with exec is kinda... meh
yeah but its still 1 line, just like ;
i dont really care what methods are used đ¤ˇ
Btw here is a 78b
def find_number(f):
for a,b,c in[L:=[0,100,0]]*99:x=L[f(x)]=(b+c)/2
return x
nice
I really like using x=L[f(x)]=(b+c)/2 for codegolfing binary searches
I use this trick quite a lot when codegolfing
thats cool
Would exec be shorter for the for loop?
77b
def find_number(f):
for a,b in[L:=[100,0]]*99:x=L[f(x)//2]=(a+b)/2
return x
73b
def find_number(f):
for L in[[100,0]]*99:x=L[f(x)//2]=sum(L)/2
return x
one million years later
- guys in #esoteric-python compressing the last uncompressed bit of code in the world to 1 byte
def find_number(f):
L=[100,0];exec("x=L[f(x)//2]=sum(L)/2;"*99)
return x
Not sure if that's shorter
Does that even run?
!e
def find_number(f):
L=[100,0];exec("x=L[f(x)//2]=sum(L)/2;"*99)
return x
n = 5
def f(y):
if y < n:
return -1
elif y == n:
return 0
else:
return 1
print(find_number(f))
@distant salmon :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 14, in <module>
003 | print(find_number(f))
004 | ^^^^^^^^^^^^^^
005 | File "/home/main.py", line 3, in find_number
006 | return x
007 | ^
008 | NameError: name 'x' is not defined
Oh what
I think exec in the global space works as you'd expect. But it works slightly different in local space
!e
exec("x=13")
print(x)
@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.
13
!e
def f():
exec("x=13")
print(x)
f()
@distant salmon :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 4, in <module>
003 | f()
004 | File "/home/main.py", line 3, in f
005 | print(x)
006 | ^
007 | NameError: name 'x' is not defined
I'm not actually sure what scope x ends up in for that case.
it doesn't
That's what I'm obseving, from what I can tell it exists but you can't refer to it.
!e But this works, so where is it? py def f(): exec("x=13") exec("print(x)") f()
@fleet lintel :white_check_mark: Your 3.11 eval job has completed with return code 0.
13
!e
def f():
exec("x=13")
print("x" in locals())
print(locals()["x"])
f()
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | True
002 | 13
there ya go
!e I still don't understand why it doesn't work, if the locals look the same py def f(): x = 13 print(locals()) f() def g(): exec("y=13") print(locals()) g()
@fleet lintel :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | {'x': 13}
002 | {'y': 13}
locals() is different than the local variables
Keys added to [locals] that are not lexically local variables remain visible in [locals], but do not dynamically become local variables.
72b
def find_number(f):
for L in[[0,100]]*99:x=L[f(x)>0]=sum(L)/2
return x
That 100 is a little bit frustrating. Had the limit been smaller then I could have just put 99, and had the limit been larger, then I could have just used something like 1e5.
So 100 is the smallest value that needs 3 bytes
68b
def find_number(f):
x=y=100
while y:=y/2:x-=~f(x-y)and y
return x
67b
def find_number(f):
x=y=100
while y:x+=~f(x-y)*(y:=y/2)
return x
61b
def find_number(f):
x=y=50
while y:=y/2:x-=f(x)*y
return x
Totally legit 51b solution
find_number=lambda f:f.__closure__[0].cell_contents
what's the goal
It is this problem
oh interesting
!e there is a cool trick: you can add x: ... to make it a local var: ```py
def f():
x: foo
exec('x = 42')
print(x)
print(locals())
f()
@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 6, in <module>
003 | f()
004 | File "/home/main.py", line 4, in f
005 | print(x)
006 | ^
007 | UnboundLocalError: cannot access local variable 'x' where it is not associated with a value
!e
def f():
x = 2
exec("x = x + 1; print(x)")
print(x)
exec("print(x)")
f()
y = 2
def f():
exec("y = y + 1; print(y)")
print(y)
exec("print(y)")
f()
z = 2
exec("z = z + 1; print(z)")
print(z)
exec("print(z)")
@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 3
002 | 2
003 | 2
004 | 3
005 | 2
006 | 3
007 | 3
008 | 3
009 | 3

Consistency sucks
iirc there's a pep to fix lots of that
eval does the job better than exec
wdym
eval executes code better than exec
again, wdym
(i hope so)
!e
def f():
x = 2
eval("f'{(x := x + 1) and print(x)}'")
print(x)
exec("print(x)")
f()
y = 2
def f():
eval("f'{(y := y + 1) and print(x)'")
print(y)
exec("print(y)")
f()
z = 2
exec("z = z + 1; print(z)")
print(z)
exec("print(z)")
@humble portal :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 6, in <module>
003 | f()
004 | File "/home/main.py", line 3, in f
005 | eval("f'{x := x + 1 and print(x)}'")
006 | File "<string>", line 1, in <module>
007 | ValueError: Invalid format specifier '= x + 1 and print(x)' for object of type 'int'
!e
def f():
x = 2
eval("f'{(x := x + 1) and print(x)}'")
print(x)
exec("print(x)")
f()
y = 2
def f():
eval("f'{(y := y + 1) and print(x)}'")
print(y)
exec("print(y)")
f()
z = 2
exec("z = z + 1; print(z)")
print(z)
exec("print(z)")
@humble portal :x: Your 3.11 eval job has completed with return code 1.
001 | 3
002 | 2
003 | 2
004 | Traceback (most recent call last):
005 | File "/home/main.py", line 13, in <module>
006 | f()
007 | File "/home/main.py", line 10, in f
008 | eval("f'{(y := y + 1) and print(x)'")
009 | File "<string>", line 1
010 | f'{(y := y + 1) and print(x)'
011 | ^
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/L5I22GYEQ6YA6GNF3D2THQLZCU
not inside f strings
!e
def f():
x = 2
eval("f'{(x := x + 1) and print(x)}'")
print(x)
exec("print(x)")
f()
y = 2
def f():
eval("f'{(y := y + 1) and print(y)}'")
print(y)
exec("print(y)")
f()
z = 2
exec("z = z + 1; print(z)")
print(z)
exec("print(z)")
@humble portal :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 3
002 | 2
003 | 2
004 | 3
005 | 2
006 | 3
007 | 3
008 | 3
009 | 3
you made that more complicated than it had to be
my bad lol
it's fine
Btw the output is exactly the same
mhm
Because eval and exec works almost the same
eval and exec do essentially the same thing, besides the restriction on statements in eval
yeah đ¤ ah, it was eval can return the output, but exec cant
eval evaluates an expression
!e
def f():
x = 2
eval("f'{(x := x + 1) and print(x)}'")
print(x)
exec("print(x)")
f()
y = 2
def f():
eval("f'{(y := y + 1) and print(y)}'")
print(y)
exec("print(y)")
f()
z = 2
eval("f'{(z := z + 1) and print(z)}'")
print(z)
exec("print(z)")
@humble portal :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 3
002 | 2
003 | 2
004 | 3
005 | 2
006 | 3
007 | 3
008 | 3
009 | 3
they don't need to be in fstrings đ
print(var := val)
those are the illegal way to run code in eval haha
well you can also just call exec
!e
def f():
x = 2
eval("f'{(nonlocal x := x + 1) and print(x)}'")
print(x)
exec("print(x)")
f()
y = 2
def f():
eval("f'{(nonlocal y := y + 1) and print(y)}'")
print(y)
exec("print(y)")
f()
z = 2
eval("f'{(z := z + 1) and print(z)}'")
print(z)
exec("print(z)")
yes you are right đ i thought i was onto something
eval('''exec("""
...
""")''')
you are, sort of
đ
but the fstrings aren't needed
walrus is enough
After helping on a recursive list implementation last night, I wanted to do it with python's native recursive list abilities. Thoughs? py def create_recursive_list(input_list): output = [] for item in reversed(input_list): output = [item, output] exec(f"output{'[1]' * len(input_list)} = output") return output
!e
exec(f"""def create_recursive_list(i):\n o=[]\n m=[1]*len(i)\n for x in i:\n o=[x,o]\n exec(f"o{'m'} = o")\n return o""")
print(create_recursive_list([1,2,3]))
@karmic pumice :white_check_mark: Your 3.11 eval job has completed with return code 0.
[3, [2, [1, []]]]
It never got the recursion, it should be [1, [2, [3, [...]]]]
Yeah, the strings are a bit mixed. I got it work, here's the expanded py exec(""" def create_recursive_list(i): o=[] m='[1]'*len(i) for x in i[::-1]: o=[x,o] exec(f"o{m} = o") return o""")
added reverse for the order
one liner again plus a few condenses py exec("def create_recursive_list(i):\n o=[]\n for x in i[::-1]:o=[x,o]\n exec(f\"o{'[1]'*len(i)} = o\");return o")
create_recursive_list=lambda i:(o:=[],m:='[1]'*len(i),list(o:=[x,o]for x in i[::-1]),exec(f"o{m}=o"),o)[4]
import pytcc
t = pytcc.TCC()
def get_byte(ptr: int) -> int:
return t.build_to_mem(
pytcc.CCode(
f'int main() {{ return *(unsigned char*)({ptr}); }}',
)
).run()
def set_byte(ptr: int, value: int) -> None:
t.build_to_mem(
pytcc.CCode(
f'int main() {{ *(unsigned char*)({ptr}) = {value}; return 0; }}',
)
).run()
đ¤ˇââď¸
Ooo that's useful for my asm patcher
interesting

sadly i dont know c
Combining my extremely basic knowledge and google, here is how it works:
ptr points to the memory address
unsigned char* says to treat that address as an unsigned number (not confusing at all) (size can differ too???)
*( dereferences the pointer to get the actual value.
Not exactly sure why the set against a dereference works, but I found return 0 is needed otherwise the C code thinks an error happened.
i see so kinda similar to rust
Because rust is kinda similar to C
return 0 is requred because otherwise it will return anything that is stored in eax register, which is a bit not good
That makes sense from what I know of assembly.
During testing i did printf(...) inside main, and declared main as returning void, and forgot to return from it, and in result main was returning result of printf (number of characters printed), despite it being declared as returning void
97
create_recursive_list=lambda i:(o:=[],[o:=[x,o]for x in i[::-1]],exec(f'o{"[1]"*len(i)}=o'),o)[3]
i knew there was something fishy about the tuple
create_recursive_list=lambda i:(m:=(o:=[]),[o:=[x,o]for x in i[::-1]],exec(f'm[:]=o'),o)[3]
91
def create_recursive_list(i):m=o=[];[o:=[x,o]for x in i[::-1]];m[:]=o;return o
78
The execute finally falls
uses ;, that's cheating
still a one liner
not a one expressioner
and its just as cheating as this one
I see it as it's in the language, so it's fine unless stated otherwise.
-20 bytes if you drop the long func name
Wouldnt it make more sense to define the recursive list as
!e
def create_recursive_list(i):
m=o=[]
[o:=[x,o]for x in i[::-1]]
m+=o,
return m[0]
print(create_recursive_list([1,2,3]))
?
@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.
[1, [2, [3, [[...]]]]]
This definition would also make it so if i=[], then the result is [[...]].
Currently the answer for i=[] is [], which is not much of a recursive list
!e
def create_recursive_list(i):m=o=[];[o:=[x,o]for x in i[::-1]];m[:]=o;return o
print(create_recursive_list([]))
def create_recursive_list(i):
m=o=[]
[o:=[x,o]for x in i[::-1]]
m+=o,
return m[0]
print(create_recursive_list([]))
@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | []
002 | [[...]]
I do agree that [] should be [[...]], but I like [1, [2, [3, [...]]]] a lot better for lists with content since that lets you either do res, list = list or list = list[1] infinitely, while [1, [2, [3, [[...]]]]] breaks at the recursive step.
Theoretically it should actually be [, [...]] to follow that property.
something like this should work, right?
def create_recursive_list(a):
r=[a];[r:=[e,r]for e in a[::-1]];return r
It doesn't get the recursion [1, [2, [3, [[1, 2, 3]]]]]
Ah ok, ye [1, [2, [3, [...]]]] makes sense, but then
This should be
def create_recursive_list(i):m=o=[];[o:=[x,o]for x in i[::-1]];m[:]=o;return m
``` and not
```py
def create_recursive_list(i):m=o=[];[o:=[x,o]for x in i[::-1]];m[:]=o;return o
oh right
sorry, im too tired for this lmao
!e
def create_recursive_list(i):m=o=[];[o:=[x,o]for x in i[::-1]];m[:]=o;return m
print(create_recursive_list([1,2,3]))
def create_recursive_list(i):m=o=[];[o:=[x,o]for x in i[::-1]];m[:]=o;return o
print(create_recursive_list([1,2,3]))
@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | [1, [2, [3, [...]]]]
002 | [1, [2, [3, [1, [...]]]]]
its the same thing
no
So the thing is [][0] is an index error, so whatever the "empty" recursive list is should also give an index error if you try to index it, so maybe [[...]] is correct.
In [54]: x=create_recursive_list([1,2,3])
...: for _ in range(100):
...: print(x[0],end=' ')
...: x = x[1]
...:
1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1
!e
print('With return o:')
def create_recursive_list(i):m=o=[];[o:=[x,o]for x in i[::-1]];m[:]=o;return o
A = create_recursive_list([1,2,3])
for _ in range(5):
print(A)
x, A = A
print('With return m:')
def create_recursive_list(i):m=o=[];[o:=[x,o]for x in i[::-1]];m[:]=o;return m
A = create_recursive_list([1,2,3])
for _ in range(5):
print(A)
x, A = A
def create_recursive_list(a):r=[a];[r:=[e,r]for e in a[::-1]];a[:]=r;return a
@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | With return o:
002 | [1, [2, [3, [1, [...]]]]]
003 | [2, [3, [1, [...]]]]
004 | [3, [1, [2, [...]]]]
005 | [1, [2, [3, [...]]]]
006 | [2, [3, [1, [...]]]]
007 | With return m:
008 | [1, [2, [3, [...]]]]
009 | [2, [3, [1, [...]]]]
010 | [3, [1, [2, [...]]]]
011 | [1, [2, [3, [...]]]]
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ZFYH4AU55CIYT7DXPA7REX2BMY
See how nice the return m version is
still the same values
no
explain how these are different
just that one has an extra expansion
The more I think about it, the more I agree that create_recursive_list([]) should be [[...]]
See the output. They are different
the extra [1, [...]] doesn't matter
!e
It does matter
def create_recursive_list(i):m=o=[];[o:=[x,o]for x in i[::-1]];m[:]=o;return o
A = create_recursive_list([1,2,3])
A[0] = 15
print(A)
def create_recursive_list(i):m=o=[];[o:=[x,o]for x in i[::-1]];m[:]=o;return m
A = create_recursive_list([1,2,3])
A[0] = 15
print(A)
@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | [15, [2, [3, [1, [...]]]]]
002 | [15, [2, [3, [...]]]]
>>> a_r[1][1][1], a_r[1][1][1] is a_r
[1, [2, [3, [...]]]], False
>>> b_r[1][1][1], b_r[1][1][1] is b_r
[1, [2, [3, [...]]]], True
where a_r is the result of return o and b_r is the result of return m
both with the same input, [1, 2, 3]
does that clear up your confusion with how its different, or do you want more explanation?
Hey guys,
Has anyone recently starting working with Python at work or learning in college? I am an old CS grad but recently started my career as a full stack dev. Stack is mainly Django.
This isn't the right channel for this, you'd have more luck in #web-development, or #python-discussion for just general talking, or #1035199133436354600 for questions.
Someone from #python-discussion said I can talk about it here. But I will move to #web-development. Thank you
whoever said that was very mistaken
Making a shallow copy of most mutable types:
y = type(x)(x)
if you need to do that multiple times, this will be cheaper (21 chars setup, 7 chars actually doing it vs the previous 10). you'd need to do it at least 7 times to break even with the other approach, 8 to make a net negative in size
from copy import copy
y=copy(x)
5 times to make a net negative: ```
from copy import copy as c
y=c(x)
same 5 times but one byte less: ```
c=import("copy").copy
y=c(x)
(x).__class__(x)
Almost symmetrical
c=__import__("copy").copy
from copy import copy
from copy import copy as c
c=lambda x:type(x)(x)
So type(x)(x) is always better
isnt copy.copy a full copy while type(x)(x) is a shallow one?
Ah
if you're just importing it as copy
from copy import*
a free 4 bytes in exchange for namespace pollution
not a bad deal
!e
alphabet = dict(zip(list(map(str.lower, [*__import__('this').__dict__['d'].keys()])), [*range(1,27)]));print(alphabet)
@craggy hamlet :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | The Zen of Python, by Tim Peters
002 |
003 | Beautiful is better than ugly.
004 | Explicit is better than implicit.
005 | Simple is better than complex.
006 | Complex is better than complicated.
007 | Flat is better than nested.
008 | Sparse is better than dense.
009 | Readability counts.
010 | Special cases aren't special enough to break the rules.
011 | Although practicality beats purity.
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/QMWLEK4HXHPS4LF4MZJ6K75PUY
hello esoteric python channel, this is my import this alphabet
this is what full output looks like
guys, i need help. how do i output something without using print, sys.stdout or sys.stderr. my best attempt was to hook exceptions and replace the traceback with something else
open(1).write('hello world')
If your goal is to print to stdout or stderr, you cant do that without touching stdout or stderr, directly or indirectly
If it is for codegolf, then a fun thing to do isinput('Hello, World!\n')
There is also
sys.stdout.write('Hello, World!\n')sys.stdout.buffer.write(b'Hello, World!\n')os.write(1, b'Hello, World!\n')
sys.stdout is just a unicode wrapper for sys.stdout.buffer. sys.stdout.buffer internally prints to stdout using os.write
I don't think stdout is callable
how is this esoteric
python solutions to my programming class's basic problems ```py
Problem 1: Create a program that will display Passed if the grade is greater than 74
int(input())>74!=print("Passed")
Problem 2: Create a program that will display the average of two numbers
print(eval('+int(input())'*2)/2)
oh they're the same length
wow
ops
Edit: Fixed it
int(input())>74<print("Passed")
``` đ
On another note, I didn't know that x<y!=f() was a thing.
!e
def f():
print('f')
def g():
print('g')
def h():
print('h')
f()!=g()!=h()
@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | f
002 | g
wouldn't that error
well stdout looks alright but it errors
thats arguably just a warning at that point
>>> 1 // print
1
>>> 1 // str
'1'
>>> '123' // int
123
>>>
>>> (print @ repr @ str) (5)
'5'
>>> (print @ len @ str) (123)
3
sauce code for this?
~~```py
@fishhook.hook(object)
def matmul(a: object, b: object, /) -> object:
if not callable(a):
return NotImplemented
if not callable(b):
return NotImplemented
@functools.wraps(b)
def f(*args, **kwargs):
return a(b(*args, **kwargs))
return f
@fishhook.hook(object)
def __floordiv__(a: object, b: object, /) -> object:
if not callable(b):
return NotImplemented
return b(a)
@fishhook.hook(object)
def __rfloordiv__(a: object, b: object, /) -> object:
if not callable(a):
return NotImplemented
return a(b)
~~ py
@fishhook.hook(object)
def matmul(a: object, b: object, /) -> object:
if not callable(a):
return NotImplemented
if not callable(b):
return a(b)
@functools.wraps(b)
def f(*args, **kwargs):
return a(b(*args, **kwargs))
return f
@fishhook.hook(object)
def __rfloordiv__(a: object, b: object, /) -> object:
if not callable(a):
return NotImplemented
return a(b)
.bm
of all operators, why //?
Sadly I don't think it's possible, but it would be really funny to overwrite as so it functioned like in C#.
damn. is there any way to like directly write to the buffer using dis or something
or some weird ctypes hook
It is inspired by wolfram mathematica language
There a // b is equivalent to b(a), and a @ b @ c is equivalent to a(b(c))
I kinda like it
its interesting
i seen it before so i dont really have an opinion for it, but its interesting
here's a challenge for you all:
figure out what this does. deobfuscating it is fine, but that's not the goal of the challenge â the challenge is to figure out why it does what it does
yes, the name is a hint (albeit not a very helpful one)
a more helpful hint is that ||the argument S is a str||
bonus points if you can golf it shorter by 5 or more bytes (not including the function name)
lsp=lambda S,n=0:S and((N:=len(S)-n)>0<len(s:=[c for i in range(len(S)+1-N)if(c:=S[i:i+N])==c[::-1]])and max(s)or lsp(S,n+1))
I believe I have it, it || gets the longest sub-list in S that has reflectional symmetry [::-1] using a window size of len(S) - n ||
!e
lsp=lambda S,n=0:S and((N:=len(S)-n)>0<len(s:=[c for i in range(len(S)+1-N)if(c:=S[i:i+N])==c[::-1]])and max(s)or lsp(S,n+1))
lsp("banana")```
@unique heath :warning: Your 3.11 eval job has completed with return code 0.
[No output]
!e
lsp=lambda S,n=0:S and((N:=len(S)-n)>0<len(s:=[c for i in range(len(S)+1-N)if(c:=S[i:i+N])==c[::-1]])and max(s)or lsp(S,n+1))
print(lsp("banana"))```
@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
anana
!e
lsp=lambda S,n=0:S and((N:=len(S)-n)>0<len(s:=[c for i in range(len(S)+1-N)if(c:=S[i:i+N])==c[::-1]])and max(s)or lsp(S,n+1))
print(lsp("banana", 3))```
@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
nan
is it just
banana
anana
anan
||yes! it calculates the longest substring that is a palindrome of a string||
wait no the output was nan
!e
lsp=lambda S,n=0:S and((N:=len(S)-n)>0<len(s:=[c for i in range(len(S)+1-N)if(c:=S[i:i+N])==c[::-1]])and max(s)or lsp(S,n+1))
print(lsp("sdfadsfsadf", 3))```
@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
sfs
!e
lsp=lambda S,n=0:S and((N:=len(S)-n)>0<len(s:=[c for i in range(len(S)+1-N)if(c:=S[i:i+N])==c[::-1]])and max(s)or lsp(S,n+1))
print(lsp("firefox", 3))
@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
x
!e
lsp=lambda S,n=0:S and((N:=len(S)-n)>0<len(s:=[c for i in range(len(S)+1-N)if(c:=S[i:i+N])==c[::-1]])and max(s)or lsp(S,n+1))
print(lsp("firefox"))
@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
x
so like ||```py
def longest_substring_palindrome(string, n=0):
if string:
N = len(string) - n
if N > 0:
s = []
for i in range(n + 1):
c = string[i:i+N]
if c == c[::-1]:
s.append(c)
if s:
return max(s)
return lsp(string, n + 1)
return string
god damnit cereal you spoiled it
||that's right! its interesting to see how it distorts as others deobfuscate it lol||
Here's my "de-obfuscated" version, I did a lot less than cereal. The debugger carried me || py def lsp(big_s, little_n=0): big_n = len(big_s) - little_n res_1 = big_n > 0 r = len(big_s) + 1 - big_n print(r) little_s = [c for i in range(r) if ( c := big_s[i:i + big_n] ) == c[::-1] ] res_2 = 0 < len(little_s) and max(little_s) or lsp(big_s, little_n + 1) return big_s and (res_1 and res_2)
I am still a bit confused on the parameter n though, is it window size? ||
oh wow that's a mess
also
is lsp("banana", 5) supposed to have "n" as the result
|| It's just because of the max ||
you already solved the purpose of it, but here's a fairly large hint for deobfuscating it ||the whole n argument and recursion thing was just a way to loop through a range until a condition was met but in a shorter (more golfed) way||
ah
im not at my computer rn but in a bit ill send an unobfuscated version of it
||```py
def longest_substring_palindrome(string):
if string:
length = len(string)
for n in range(length):
window_size = length - n
substrings = []
for i in range(n + 1):
substring = string[i : i + window_size]
if substring == substring[::-1]:
substrings.append(substring)
if substrings:
return max(substrings)
return string
121 -> 114 ```py
lsp=lambda S,n=0:(N:=len(S)-n)and((s:=[c for i in range(n+1)if(c:=S[i:i+N])==c[::-1]])and max(s)or lsp(S,n+1))or S
114 -> 110 ```py
lsp=lambda S,n=0:(N:=len(S)-n)and(max([c for i in range(n+1)if(c:=S[i:i+N])==c[::-1]]or[""])or lsp(S,n+1))or S
110 -> 106 ```py
lsp=lambda S,n=0:S[n:]and(max(c for i in range(n+len(S))if(c:=S[i:i+len(S)-n])==c[::-1])or lsp(S,n+1))or S
106 -> 99 ```py
lsp=lambda S,n=0:S and(max(c for i in range(n+len(S))if(c:=S[i:i+len(S)-n])==c[::-1])or lsp(S,n+1))
ooo nice
here's the original implementation, if you're interested
||```py
def longest_subpalindrome(string):
for sp_len in range(len(string), -1, -1):
sp_list = []
for sp_idx in range(len(string) + 1 - sp_len):
sp_cand = string[sp_idx : sp_idx + sp_len]
if sp_cand == sp_cand[::-1]:
sp_list.append(sp_cand)
if sp_list:
return max(sp_list)
@versed eagle @quartz wave 80 >:)py lsp=lambda i:i if i==i[::-1] else max(lsp(i[1:]),lsp(i[:-1]),key=len)if i else""
ooo nice
lsp=lambda i:i==i[::-1]and i or max(lsp(i[1:]),lsp(i[:-1]),key=len)if i else""
some test case doesn't work
either that or it's taking too long
which
one of these ```py
lsp("aishfgaioshgasagioioioioiaioioioioi");lsp("aishfgaioshgasag");lsp("banana");lsp("");lsp("abcd")
the first one takes a really long time
It will take a while, it's basically binary search with all repetitions.
because worst case is 2**len(S) function calls
mk then 68 ```py
lsp=lambda i:i if i==i[::-1]else max(lsp(i[1:]),lsp(i[:-1]),key=len)
holy moly ```pycon
len("aishfgaioshgasagioioioioiaioioioioi")
35
2**35
34359738368
34359738368*100/1e+9
3435.9738368
... yeah
The funny thing is it started as a stack based design with s+=[i[1:],i[:-1]] but then I realized it would make the recursive not have to deal with n anymore.
Such a code golf moment
66 i think ```py
lsp=lambda i:i!=i[::-1]and max(lsp(i[1:]),lsp(i[:-1]),key=len)or i
Should it be "c"?
Interesting, in the case of key=len the tie-breaker is just the first element
started here
so revert to 110?
Hold on, brain idea
96 py lsp=lambda i:i if i==i[::-1] else max(sorted([lsp(i[1:]),lsp(i[:-1])])[::-1],key=len)if i else""
82 with the optimizations py lsp=lambda i:i!=i[::-1]and max(sorted([lsp(i[1:]),lsp(i[:-1])])[::-1],key=len)or i
And an even worse performance now!
branch
still-somewhat-performant version
110 -> 102 ```py
lsp=lambda S,n=0:S and(max([c for i in range(n+1)if(c:=S[i:i+len(S)-n])==c[::-1]]or[""])or lsp(S,n+1))
102 -> 101 ```py
lsp=lambda S,n=0:S and(max([c for i in range(n+1)if(c:=S[i:i+len(S)-n])==c[::-1]]or[0])or lsp(S,n+1))
# [edit: doesnt work]
lsp=lambda S,n=0:S and(max(*[c for i in range(n+1)if(c:=S[i:i+len(S)-n])==c[::-1]],"")or lsp(S,n+1))
>>> lsp("aishfgaioshgasag");lsp("banana");lsp("");lsp("abcd");lsp("nasdklfjlksdkla");lsp("cab")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
ValueError: max() iterable argument is empty
yeah i got the same error
im looking for the typo
cause what i typed in my terminal works :<
there needs to be more than 1 argument for max() with variable arguments to work like an iterable
and if the listcomp is empty that'll do the same thing as max("")
ah i had brackets around the string in the not messed up version
which, now that i look at it
also doesnt work
whatever
it'd not be shorter anyway
@quartz wave and @fleet lintel
both of you get a coin for figuring out what the function is
and both of you get a bonus coin for golfing it further
đŞ x2
heres a cookie đŞ
thanks for participating lol
yayy
had a weird idea: what would it take to get a tuple containing itself
basically what i want is a ((...)), in the same way that a here:
a = []
a.append(a)
assert(id(a) == id(a[0]))
is a [[...]], aka a list containing itself
the fundamental issue here is that tuples are immutable
but maybe there's still a chance if i dip into fucking around with C extensions or something?
you can definitely do it with a C extension
đ?
yeah just ```c
PyObject *func(PyObject *self)
{
PyObject *a = PyTuple_New(1);
if (a == NULL) {
Py_DECREF(a);
return NULL;
}
Py_INCREF(a);
PyTuple_SET_ITEM(a, 0, a);
return a;
}
oh hell yeah gimme a minute
>py
Python 3.12.0b4 (tags/v3.12.0b4:97a6a41, Jul 11 2023, 13:49:15) [MSC v.1935 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class A:
... def __repr__(self):
... return repr(self.x)
...
>>> a = A(),
>>> a[0].x = a
>>> a
((...),)
that's one way
here's it with ctypes ```pycon
from ctypes import *;a = (1,);py_object.from_address(id(a)+object.basicsize+tuple.itemsize).value = a
a
((...),)
a[0]
((...),)
a[0][0]
((...),)
a[0][0][0]
((...),)
no they arent
There definitely was a way to do that with some broken iterables...
Several months ago (or years?) it was mentioned here or in #internals-and-peps
IIRC you used length_hint and GC to get a reference to the tuple early, thus being able to yield it
there it is
it is indeed __length_hint__ trick
chilaxan is genius
!e ```py
def primes() -> None:
r1, r2, r3, r4, r5 = 1, 0, 1, 0, 0
while 1:
if r3 and r2 > 1: r3 -= 1; r4 += 1
elif r1 and r2: r1 -= 1; r5 += 1
elif r2: r2 -= 1; r4 += 1
elif r4 and r5:
r1 += 1; r3 += 1; r4 -= 1; r5 -= 1
if not r4 and r1 == r3:
print(end=f'{r1:5} ')
elif r4: r2 += 1; r4 -= 1
elif r5: r1 += 2; r2 += 2; r3 -= 2; r5 -= 1
elif r1: r1 -= 1
else: r1 += 2; r2 += 2; r3 -= 1
primes()
@fleet bridge :x: Your 3.11 eval job timed out or ran out of memory.
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593 599 601 607 613 617 619 631
#esoteric-python message
#esoteric-python message
oh, i already posted that code...
>>> 'Enter several numbers: ' // input // str.split // (lambda x: map(int, x)) // list // sum // print
Enter several numbers: 1 2 3 4 5
15
!e
import timeit
timeit.timeit("print(_it)", number=5)``` doesnt really fit the general theme but just dropping this here
@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | repeat(None, 4)
002 | repeat(None, 3)
003 | repeat(None, 2)
004 | repeat(None, 1)
005 | repeat(None, 0)
> .\cpython-main\PCbuild\amd64\python.exe
Python 3.13.0a0 (heads/main-dirty:0b76892, Sep 1 2023, 20:54:51) [MSC v.1937 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 'Enter several numbers: ' |> input |> str.split |> map(int, $) |> list |> sum |> print
Enter several numbers: 1 2 3 4 5
15
how does $ work?
how it understands which parts of expressions should become a part of lambda?
why is map(int, $) equivalent to lambda $: map(int, $) and not map(int, lambda $: $) ?
the neat part is that it doesn't put them in a lambda
huh
it's substitution
>>> from dis import dis;dis("'Enter several numbers: ' |> input |> str.split |> map(int, $) |> list |> sum |> print")
0 0 RESUME 0
1 2 LOAD_NAME 0 (print)
4 PUSH_NULL
6 LOAD_NAME 1 (sum)
8 PUSH_NULL
10 LOAD_NAME 2 (list)
12 PUSH_NULL
14 LOAD_NAME 3 (str)
16 LOAD_ATTR 9 (split + NULL|self)
36 LOAD_NAME 5 (input)
38 PUSH_NULL
40 LOAD_CONST 0 ('Enter several numbers: ')
42 CALL 1
50 CALL 1
58 LOAD_NAME 6 (map)
60 PUSH_NULL
62 LOAD_NAME 7 (int)
64 SWAP_N 4
66 CALL 2
74 CALL 1
82 CALL 1
90 CALL 1
98 RETURN_VALUE
>>> ~(int, '1 2 3' // str.split) // map // list
[1, 2, 3]
so there is no runtime tricks, it is done entirely by compiler
yep
sort of ```pycon
((1,2,3), {'sep':'-'}) |> print(*$[0], **$[1])
1-2-3
i think i now completely undestand how it works
is anyone still messing with that code challenge?
If you are referring to the longest palindromic substring, I did some research last night, and I believe the minimum possible with the constraints is 84 py lsp=lambda s:s if s==s[::-1]else max(sorted([lsp(s[1:]),lsp(s[:-1])])[::-1],key=len)
That's because the shortest palindrome finder I could find or create is 57 with py lsp=lambda s:s if s==s[::-1]else [lsp(s[1:]),lsp(s[:-1])]
so the only possible optimization (without renaming the lambda) would be in the sort/max, but I am not aware of any other shorter method.
66b
lsp=lambda s:s!=s[::-1]and max(lsp(s[1:]),lsp(s[:-1]),key=len)or s
@distant salmon
lol
lsp=lambda s:s!=s[::-1]and max(lsp(s[1:]),lsp(s[:-1]),key=lambda x:(len(x),x))or s
Idk if it is correct or works at all
https://github.com/RocketRace/hoopy
This is in a somewhat workable state now!
That looks to be correct, I was always trying to lambda the sort instead of the max xD
lsp=lambda s:s!=s[::-1]and max(lsp(s[1:]),lsp(s[:-1]),key=lambda x:(len(x),x))or s
lsp=lambda s:s if s==s[::-1]else max(sorted([lsp(s[1:]),lsp(s[:-1])])[::-1],key=len)
``` it is 2 chars shorter 
From here I really donât see any further progress, everything is doing the max possible with the min footprint
hoopy/runtime.py lines 354 to 355
"<": "<<",
">": "<<",```
isnt that a typo?
this has a bug as specified by herald
#esoteric-python message ye I already got told about that
In my oppinion longest palindromic substring is not unique, so any one of them should be ok in the output
Btw why is everyone using lsp, shouldnt it be lps?
Just because herald named it, from Longest SubPalindrome. And the reason for having to take the last alphabetically is because herald said so.
https://en.wikipedia.org/wiki/Longest_palindromic_substring the standard name for it is longest palindromic substring
In computer science, the longest palindromic substring or longest symmetric factor problem is the problem of finding a maximum-length contiguous substring of a given string that is also a palindrome. For example, the longest palindromic substring of "bananas" is "anana". The longest palindromic substring is not guaranteed to be unique; for examp...
Again 2 chars shorter
lsp=t=lambda s:s!=s[::-1]and max(sorted([t(s[1:]),t(s[:-1])])[::-1],key=len)or s
lsp=t=lambda s:s!=s[::-1]and max(t(s[1:]),t(s[:-1]),key=lambda x:(len(x),x))or s
Does it not work with the if else base?
Using and or is 2 characters shorter than if else. Independent of that you can save 2 more characters using lsp=t=...
its 4 right?
all good python programs should be at least 70% red underlines
Can we print "\n" in python?
wrong channel
!e @sick hound try this
print(1)
__import__('sys').stdout.write(int.__doc__[len(int.__doc__.splitlines()[0])])
print(2)
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1
002 |
003 | 2
Nice, first try
real
Anyone here with extensive xpath experience? I'm not sure this is the right channel, but I can't actually find a channel that "fits perfectly"
maybe open help thread?
Yeah - I may have to. This is weird and not really exclusive to Python; just banging my head and not really getting anywhere. Good suggestion @fleet bridge ! Thanks!
Has someone tried making python case insensitive?
import codecs
def decode(input: bytes, errors: str = 'strict') -> tuple[str, int]:
return input.tobytes().decode().lower(), len(input)
def encode(input: str, errors: str = 'strict') -> tuple[bytes, int]:
raise NotImplementedError
def search(name: str) -> codecs.CodecInfo | None:
if name == 'case_insensitive':
return codecs.CodecInfo(encode, decode)
return None
codecs.register(search)
import a
# a.py
# coding: case_insensitive
PRINT('hI!')
For I In Range(10):
Print(I)
reminds me of pascal case-insensitivity
But now strings will be case insensitive as well?
Pretty cool you're able to do it with so little code
is this one lineable nicely```py
commands = []
command = self
while isinstance(command, Command):
commands.append(command)
command = command.parent
return commands```?
Depends on what you mean by "nicely".
You might be able to use iter magic to replace the while loop, but not sure about the command reassignment
two arg iter doesnt work here unfortunately
!e ```py
from future import annotations
import dataclasses
@dataclasses.dataclass
class Node:
parent: Node | None
value: int
self = Node(Node(Node(Node(None, 1), 2), 3), 4)
^^^^^^^^^^^^^ - root node
commands = []
command = self
while isinstance(command, Node):
commands.append(command)
command = command.parent
commands2 = [(self, self:=self.parent)[0] for _ in iter(lambda: isinstance(self, Node), False)]
assert commands == commands2
print(*commands, sep='\n')
print(*commands2, sep='\n')
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Node(parent=Node(parent=Node(parent=Node(parent=None, value=1), value=2), value=3), value=4)
002 | Node(parent=Node(parent=Node(parent=None, value=1), value=2), value=3)
003 | Node(parent=Node(parent=None, value=1), value=2)
004 | Node(parent=None, value=1)
005 | Node(parent=Node(parent=Node(parent=Node(parent=None, value=1), value=2), value=3), value=4)
006 | Node(parent=Node(parent=Node(parent=None, value=1), value=2), value=3)
007 | Node(parent=Node(parent=None, value=1), value=2)
008 | Node(parent=None, value=1)
(my code reassigns self, but it is easy to change)
issue is parent isnt Self | None
its Self | Something | None
oh wait
that still works
yeah
why not
?
this is the wrong channel, and probably the wrong server, for.. whatever that is
After reading esoteric python for some time
I understand it more
didn't we just talk about this?
oh, i figured out the reason of the attributeerror. turns out instead of passing a uleb128 instance to the dataclass [here](#python-discussion message), i'm passing the result of the len function, which is an int
Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.

