#esoteric-python

1 messages ¡ Page 32 of 1

sick hound
#

/run

print("x")
unique heath
#

!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]))
night quarryBOT
#

@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.

1
sick hound
#

/run

for i in range(10): print("esoteric programmer is 10x great")
gleaming linden
#

The command is !e, not /run

karmic pumice
# sick hound /run ```py for i in range(10): print("esoteric programmer is 10x great") ```

!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())))))))]
night quarryBOT
#

@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
distant salmon
#

oh nice pythonk
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

karmic pumice
#

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

unique heath
#

!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]))```
night quarryBOT
#

@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

quartz wave
#

i visualized it before

unique heath
#

!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]))```
night quarryBOT
#

@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.

1
distant salmon
karmic pumice
#

rip walrus wont help here

distant salmon
quartz wave
# distant salmon 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]
distant salmon
unique heath
#

can't you just remove the =m

quartz wave
karmic pumice
quartz wave
#

although it's probably correct

unique heath
#

o

karmic pumice
distant salmon
quartz wave
#

ok

#

it's good

karmic pumice
#

iirc they can remove solutions that pass 50/50

#

happened to one of my solutions lmao

distant salmon
#

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

karmic pumice
quartz wave
#

man late-bound defaults would be so useful

karmic pumice
# karmic pumice yeah

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 💀 🚟

quartz wave
#

i think wilson's theorem would have a use here like they did in CGSE but hmm

#

so far my attempts are unsuccessful

unique heath
#

wait a second

#

any(sum(n)%i<1for i in range(2,sum(n))) this part just checks prime right

quartz wave
#

yep

unique heath
#
>>> any(sum(n)%i<1for i in range(2,sum(n)))
<stdin>:1: SyntaxWarning: invalid decimal literal
True
>>> sum(n)
6``` somethings wrong
quartz wave
#

it's an improvement from ~-<check prime>

distant salmon
unique heath
#

minimum_number=m=lambda n:~-(pow(3,sum(n)-1,sum(n))==1)and-~m(n+[1])
68

unique heath
#

shit

#

it sometimes fails

quartz wave
#

m([1,1,1]) == 2, not expected value 0

unique heath
#

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

unique heath
#

yep

quartz wave
#

is this even allowed

unique heath
#

lol

distant salmon
unique heath
quartz wave
unique heath
#

lol

quartz wave
#

oh wow it's performant again

unique heath
#

speed

#

its like a worse miller-rabin

quartz wave
#

59 ```py
minimum_number=m=lambda n:~-4**~-sum(n)%sum(n)and-~m(n+[1])

unique heath
#

someone needs to test what the best first number is

quartz wave
#

the 78 thing still stands as "always works"

unique heath
#

IT PASSED

#

use 40 as the number

#

hacky as fuck

quartz wave
#

60 bytes?/

#

nvm

#

40 works the same as 4

#

still fails

unique heath
#

it works sometimes

low lynx
#

yeah because they run random tests

unique heath
#

the best solution

sick hound
#

what is this science?

quartz wave
#

59b for "works 1/4 of the time", 78b for "works all the time"

#

wait a minute

unique heath
#

60b works 1/2 of the time

quartz wave
#

76 ```py
from gmpy2 import*;minimum_number=m=lambda n:1>is_prime(sum(n))and-~m(n+[1])

#

apparently

#

gmpy2 was available

unique heath
#

genius-level golf

quartz wave
#

70 ```py
from gmpy2 import*;minimum_number=lambda n:next_prime(~-sum(n))-sum(n)

#

wtf

unique heath
#

lmao

quartz wave
#

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

unique heath
#

nice

quartz wave
#

it's so unfair

#

damn it

unique heath
#

ik,r

quartz wave
#

what other cw installed libraries are there

low lynx
#

scipy and numpy are iirc

quartz wave
#

this might be all pydis but i'm not sure

low lynx
#

i mean it's xelf, you and i assume hybrid

unique heath
#

lol

#

okay but i thought of the idea

quartz wave
#

do we have the minimum yet

unique heath
#

check

quartz wave
#

59b probabilistic, 69b w/ package, 78b pure (degen 51c, 56c, 60c respectively)

unique heath
#

should i ask the pygenners to see if they can golf isprime

#

the mortals

quartz wave
#

hha sure

unique heath
#

bet

#

no one responded

quartz wave
#

lol

quartz wave
distant salmon
unique heath
#

yeah but thats probably miller rabin

low lynx
unique heath
#

which is just my solution but better

low lynx
#

significantly better

#

fermat is really unreliable

#

especially if u only do it once

unique heath
#

but easier to golf

quartz wave
unique heath
quartz wave
#

so it must be extremely good at doing what it's doing

unique heath
#

shocker

#

prime tester used by rsa is good at testing primes???

#

1 round is about 3/4 chance of being correct

quartz wave
#

i didn't call all()

glass wyvern
#

!E

night quarryBOT
#
Missing required argument

code

#
Command Help

!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!

glass wyvern
#

!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)```
night quarryBOT
#

@glass wyvern :white_check_mark: Your 3.11 eval job has completed with return code 0.

['28', '82']
quartz wave
night quarryBOT
#

@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.

['82', '28']
unique heath
#

tf

#

oh

#

union of sets

quartz wave
#

!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})

night quarryBOT
#

@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.

{ANY_ALL}
fleet bridge
#

Wtf

unique heath
#

wat

fleet bridge
#

What is ANY_ALL

unique heath
#

also since when did we switch to einspect

quartz wave
fleet bridge
#

Hmm

#

That makes sense

#

But what is this object?

quartz wave
fleet bridge
#

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()))

night quarryBOT
#

@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.

<class 're._constants._NamedIntConstant'>
fleet bridge
#

Ok

restive void
#

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.

earnest wing
#

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

distant salmon
sick hound
livid geyser
sick hound
#

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

gleaming linden
mortal grotto
#

@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

gleaming linden
#

Or maybe ("10"*99999)[:size]

sick hound
sick hound
gleaming linden
sick hound
#

idk what the ~ does

mortal grotto
#

same as -1-x

gleaming linden
#

Bitwise not

#

-~x is essentially x+1 but with higher precedence than multiplication/division

sick hound
#

i see

#

nice

gleaming linden
#
"10"*(size//2)+"1"*(size%2)
("10"*(-~size//2))[:size]
#

2b less

sick hound
#

so -~size//2 is the same as (1+size)//2?

gleaming linden
#

Yeah

mortal grotto
#

Yep, just without the brackets :)

sick hound
#

what about the precedence

#

oh you mean easier to write yeah I get it now

mortal grotto
#

The ~ and - both are unary operators, so they come first

sick hound
#

alr thx for the help, I'm going to look more into bitwise operations

gleaming linden
#

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]
sick hound
#

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

gleaming linden
#

Since it's getting sliced to the correct length either way

sick hound
#

yeah yeah

gleaming linden
#

It doesn't matter as long as it's at least as long as size itself

sick hound
#

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

sick hound
austere mauve
#
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];_()
fleet bridge
#
(lambda: ..., do_this)[condition]()
austere mauve
#

That's a good one

sick hound
austere mauve
#

bool is a subclass of int

#

!e ```py
print(bool.mro)

night quarryBOT
#

@austere mauve :white_check_mark: Your 3.11 eval job has completed with return code 0.

(<class 'bool'>, <class 'int'>, <class 'object'>)
fleet bridge
austere mauve
#

True is similar to 1 and False is similar to 0.

fleet bridge
#

!e ```py
print(...)
print(Ellipsis)

night quarryBOT
#

@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | Ellipsis
002 | Ellipsis
austere mauve
#

Wait...

#

I didn't understand the question 😅

sick hound
#

yeah lol

#

it's cool tho the .__mro__

#

it tracks the super classes

fleet bridge
#

... doesnt do anything special by itself
some libs can interpret however they want. numpy for example uses ... for slices

sick hound
#

i see, lambda allow you to have inner functions that you can index?

fleet bridge
#

no, im not indexing lambda

#

im indexing tuple that contains two functions: do-nothing-lambda and do_this function

sick hound
#

oh i see alr, it's the output yeah

#

need to revise my lambdas

#

thx

austere mauve
#

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()
gleaming linden
#
exec("do_this" + "()"*condition)
austere mauve
#

Even better:

exec("do_this()"*condition)
fleet bridge
#
for _ in iter(lambda: condition, True):
  do_this()
  break
fleet bridge
gleaming linden
night quarryBOT
#

@gleaming linden :warning: Your 3.11 eval job has completed with return code 0.

[No output]
gleaming linden
#

Oh what

#

It works?

#

!e eval("")

night quarryBOT
#

@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
gleaming linden
#

Ah, eval doesn't allow empty strings

quartz wave
#

is if simply not allowed

#

or what r we doing here

gleaming linden
austere mauve
#

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.

quartz wave
#

how about ```py
exec(do_this.code.replace(co_code=~condition%2*b"d\x00S\x00"+do_this.code.co_code))

austere mauve
#

Isn't it just rewording of the above example? Well, it definitely accomplishes the task of being even less readable.

rugged sparrow
#

@fleet bridge ended up writing an extension module to get the memory writes to work, now im working on making sure it works crossplatform

austere mauve
#

A bit more invasive, exception-based approach:

import sys
_=sys.excepthook
sys.excepthook=lambda a,b,c:[setattr(sys,"excepthook",_),do_it()]
assert ~-condition
unique heath
#

what golfing are we doing now

smoky coral
#

!e print(“Hello World”)

#

!e print(‘Hello World’)

#

!e exec(“print(‘Hello World’)”)

versed eagle
#

unicode quotes dont work

#

don't use them

smoky coral
#

Ah

versed eagle
#

use the ascii quotes

#

" and '

smoky coral
#

!e print('dumb bot')

versed eagle
#

why

smoky coral
#

Thanks

versed eagle
#

the bot works perfectly fine

smoky coral
#

I know, I’m just messing around

#

More interesting than Hello World

versed eagle
#

ig

versed eagle
smoky coral
#

You’re right. I missed the bot commands channel

quartz wave
#

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())),"")

versed eagle
#
first_non_repeating_letter=lambda*a:type("",(),{"__eq__":lambda*s:1})()
#

that can probably be shortened more but i gtg now :<

low lynx
#

I think that's against codewars policy

finite blaze
restive void
finite blaze
#

how can an object be equal to everything?

restive void
#

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())
night quarryBOT
#

@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.

True
fleet bridge
#

I think you also can set trace function, and then fix result to be correct

#

Or look at bytecode of checking function

restive void
fleet bridge
#

Yes, but might be interesting for someone

earnest wing
#
class F(str):__eq__=lambda*_:1
first_non_repeating_letter=F
#

in general type() calls are verbose and not super golfy

unique heath
#

lmfao

#

also it doesnt need to inherit from str

earnest wing
#

needs to take args

#

compatible with one string argument

unique heath
#

!e

class F:self.__eq__=lambda*_:1
first_non_repeating_letter=F

print(first_non_repeating_letter("moonman") == n)```
night quarryBOT
#

@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
unique heath
#

!e

class F(str):self.__eq__=lambda*_:1
first_non_repeating_letter=F

print(first_non_repeating_letter("moonman") == n)```
night quarryBOT
#

@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
unique heath
#

ic

#

!e

class F(str):__eq__=lambda*_:1
first_non_repeating_letter=F

print(first_non_repeating_letter("moonman") == n)```
night quarryBOT
#

@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
unique heath
#

!e

print(len("""
class F(str):__eq__=lambda*_:1
first_non_repeating_letter=F"""))```
night quarryBOT
#

@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.

111
earnest wing
#

that's definitely not 111 chars

unique heath
#

real

dreamy pier
#

59

unique heath
#

!e

print(len("""
class F(str):__eq__=lambda*_:1
first_non_repeating_letter=F"""))```
night quarryBOT
#

@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.

60
dreamy pier
#

\n in the beginning

unique heath
#

ah

#

thats more cheating than my fermat golf lol

quartz wave
unique heath
#

lol

#

classes are glorified functions

earnest wing
#

can you use __eq__=slice or does the method descriptor not bind

quartz wave
unique heath
#

!e

__import__("fishhook").hook(str)
def __eq__(): return True
first_non_repeating_letter=lambda _:""

print(first_non_repeating_letter("m") == "n")```
night quarryBOT
#

@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.

False
fleet bridge
unique heath
#

!e

import fishhook
fishhook.hook(str)
def __eq__(): return True
first_non_repeating_letter=lambda _:""

print(first_non_repeating_letter("m") == "n")```
night quarryBOT
#

@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.

False
unique heath
#

waht

#

gtg

restive void
#

!e

__import__("fishhook").hook(str,name="__eq__")(lambda*_:1)
first_non_repeating_letter="".join

print(first_non_repeating_letter("m") == "n")
night quarryBOT
#

@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.

1
wheat river
restive void
austere mauve
#

No

#

For empty string, no

restive void
#

Doesn't matter if it's empty though

austere mauve
#

empty will evaluate to false:

restive void
#

!e

__import__("fishhook").hook(str,name="__eq__")(lambda*_:1)
first_non_repeating_letter=str

print(first_non_repeating_letter("m") == "n")
night quarryBOT
#

@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.

1
austere mauve
#

!e ```py
class F(str):eq=str
first_non_repeating_letter=F

print(bool(first_non_repeating_letter("repeatrepeat") == ""))

night quarryBOT
#

@austere mauve :white_check_mark: Your 3.11 eval job has completed with return code 0.

False
wheat river
quartz wave
#

fishhook in cw?

wheat river
#

cw?

austere mauve
#

codewars

wheat river
#

this from codewars?

wheat river
#

oh 👀

austere mauve
#

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"))

night quarryBOT
#

@austere mauve :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | True
002 | True
003 | True
austere mauve
#

Is it possible to it shorter in any way?

languid hare
#

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

fleet bridge
#

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")
print(first_non_repeating_letter("aAd
fGDF") == "\0")

night quarryBOT
#

@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | True
002 | True
003 | True
004 | True
fleet bridge
#
>>> 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

versed eagle
#

45

austere mauve
# versed eagle ```py class f(str):__eq__=id __getattr__=lambda*s:f ```

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.

versed eagle
#

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

versed eagle
#

here ya go

versed eagle
# versed eagle https://docs.python.org/3/reference/datamodel.html?highlight=getattr#customizing...

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 an AttributeError. 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 an AttributeError. If found, it is called with the attribute name and the result is returned.

earnest wing
#

depend on how it's tested

versed eagle
earnest wing
#

if it's a module or execed then rad!

versed eagle
#

luckily, we get to see how it's tested

#

so we know for sure that this works

versed eagle
#

i gtg now so have a nice day everyone <3

#

byee

restive void
earnest wing
#

it is only guaranteed to be an integer distinct from the id()s of other living objects

versed eagle
#

though if CPython isnt guaranteed, dir works

rugged sparrow
#

pypy does not return addresses for id, so it might be possible to get an id of zero

unique heath
#

waht do we golf now

versed eagle
#

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

languid hare
#

who would've guessed all the golfing practice actually came in useful

#

1 lemon for the first person who deciphers this

fleet bridge
#
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
languid hare
#

correct!

fleet bridge
#

🥳

languid hare
#

you get one lemon 🍋

fleet bridge
#

i put it in my nickname

languid hare
#

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

sick hound
#

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

sick hound
#

damn, yeah I do need to learn bitwise operations

#

thx

glad cipher
#

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 👀

quartz wave
glad cipher
#

😭

sick hound
#

ego destruction

glad cipher
#

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])\
                               )```
glad cipher
sick hound
#

i'm on my first steps to joining this cult

glad cipher
#

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

glad cipher
quartz wave
# glad cipher 😭

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")

fleet bridge
vast wave
vast wave
quartz wave
#

t-twue... :3

austere mauve
austere mauve
# turbid dragon how does this work?

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.

turbid dragon
fleet bridge
#

id cant be negative

#

At least in CPython

#

But it is not important

#

Every nonzero id would work

austere mauve
fleet bridge
#

*but

#

😄

glad cipher
fringe igloo
turbid dragon
# fleet bridge id cant be negative

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

fallow leaf
vast wave
fallow leaf
#

Crash

vast wave
#

whar

fallow leaf
#

Wanted to see what it would give when ran and it crashed my phone

vast wave
#

funy

#

phone was epicly trolled

fallow leaf
#

Mega trolled

split salmon
#

!paste

night quarryBOT
#
Pasting large amounts of code

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.

split salmon
versed eagle
#

this is guaranteed because we can see the test cases

turbid dragon
#

Haven’t done cw challenges before

#

Leetcode is more extensive I think

versed eagle
#

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

turbid dragon
#

Damn cool

#

you could probably do the same in leetcode then

versed eagle
#

if the testing is done in python, yeah

#

if its done externally, no

unique heath
#

.kata

#

alr so

#

recursion?

dreamy pier
#

but about normal solution - just a loop

#

or math formula

quartz wave
unique heath
quartz wave
#
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

fleet bridge
#
solution=lambda x:sum(x for x in range(x)if x%3|x%5)//2
``` less bytes, but answer is approximate
quartz wave
#

normally it won't work

quartz wave
#

52b ```py
solution=lambda x:sum({*range(0,x,3),*range(0,x,5)})

distant salmon
ashen adder
#

why -~- instead of +1- when it's the same number of characters? Are you only wanting to obfuscate it or is it faster?

quartz wave
#

yea can't have it

distant salmon
dreamy pier
#

Additionally, if the number is negative, return 0.

fleet bridge
#

@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 $def syntax instead of #def?
  • why do you need to surround $macro$ with $? isnt a name itself enough to trigger substitution?
    this 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)
split salmon
quartz wave
fleet bridge
#

ok, thanks

versed eagle
#

there are solutions which will work with every problem there, but they're longer cause you end up hooking builtin functions

distant salmon
#

x**4%15%2 is a check for if x and 15 are coprime

fleet bridge
#

wtf

#

ill check that

#

🤔

#

i think your check is incorrect

distant salmon
fleet bridge
#

i have no idea why your code gives correct result

distant salmon
#

That -5 in your calc should be 10

fleet bridge
#

bruh, i forgot about that

distant salmon
fleet bridge
#

negative remainders are very convenient, but not in this case

#

🤦‍♂️

topaz blaze
#

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?

unique heath
#

!e

solution=s=lambda x:x>2and s(x:=x-1)+x-x**4%15%2*x
print(s(10))
night quarryBOT
#

@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
unique heath
#

!e

solution=s=lambda x:x>2&s(x:=x-1)+x-x**4%15%2*x
print(s(10))
night quarryBOT
#

@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

unique heath
#

!e

solution=s=lambda x:x>2 & s(x:=x-1)+x-x**4%15%2*x
print(s(10))
night quarryBOT
#

@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

distant salmon
#

Think of it like a codegolfed version of 0 if x <= 2 else ...

quartz wave
# vast wave ghost ping because file upload - https://paste.pythondiscord.com/WGRA

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)]))

unique heath
#

dafuq

random kiln
#

print("Hello world")

hazy void
#

!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)
night quarryBOT
#

@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]
hazy void
#

here is a challenge: explain the output

proper vault
#

!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)
night quarryBOT
#

@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]
versed eagle
#

since they're earlier in the list

distant salmon
night quarryBOT
#

@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]
distant salmon
#

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

karmic pumice
gleaming linden
#

use instead of \t

karmic pumice
#

what
how do you type it

gleaming linden
#

space

karmic pumice
#

but then it wont work

#

it needs indentation

gleaming linden
#

1 space is valid indentation

#

!e ```py
if True:
print("hello")

night quarryBOT
#

@gleaming linden :white_check_mark: Your 3.11 eval job has completed with return code 0.

hello
gleaming linden
#

And does it have to be 1 line?

karmic pumice
#

well thats my goal

karmic pumice
#

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?

gleaming linden
#

I don't think so

karmic pumice
#

oh wait im dumb

gleaming linden
#

not with exec at least

karmic pumice
#

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

gleaming linden
#
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?
karmic pumice
#

yep

#

-2chars gaming

gleaming linden
#
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?
karmic pumice
#

it works

#

but im not sure how

gleaming linden
#

nice

gleaming linden
karmic pumice
#

ahh i see

#

thats very smart

#

sub 100 chars 😎 esopy power

gleaming linden
#

And I think the walrus loses 1c

#
 c(b)c(b)
(x:=c(b))x
#

Yup

karmic pumice
#
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 🎉

distant salmon
karmic pumice
distant salmon
#

Oh, so it is not to make shorter code?

karmic pumice
#

yes

gleaming linden
#

1lining with exec is kinda... meh

karmic pumice
#

i dont really care what methods are used 🤷

distant salmon
#

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
karmic pumice
#

nice

distant salmon
#

I really like using x=L[f(x)]=(b+c)/2 for codegolfing binary searches

#

I use this trick quite a lot when codegolfing

gleaming linden
#

Would exec be shorter for the for loop?

distant salmon
distant salmon
fleet bridge
#

one million years later

  • guys in #esoteric-python compressing the last uncompressed bit of code in the world to 1 byte
gleaming linden
#
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

gleaming linden
#

Idk

#

I can't test because I'm on mobile

distant salmon
#

!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))
night quarryBOT
#

@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
gleaming linden
#

Oh what

distant salmon
#

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)
night quarryBOT
#

@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.

13
distant salmon
#

!e

def f():
    exec("x=13")
    print(x)
f()
night quarryBOT
#

@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
fleet lintel
#

I'm not actually sure what scope x ends up in for that case.

fleet lintel
#

That's what I'm obseving, from what I can tell it exists but you can't refer to it.

versed eagle
#

its like locals()['x']=13

#

it never actually gets set in the local variables

fleet lintel
#

!e But this works, so where is it? py def f(): exec("x=13") exec("print(x)") f()

night quarryBOT
#

@fleet lintel :white_check_mark: Your 3.11 eval job has completed with return code 0.

13
versed eagle
#

!e

def f():
    exec("x=13")
    print("x" in locals())
    print(locals()["x"])
f()
night quarryBOT
#

@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | True
002 | 13
fleet lintel
# versed eagle 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()

night quarryBOT
#

@fleet lintel :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | {'x': 13}
002 | {'y': 13}
versed eagle
#

Keys added to [locals] that are not lexically local variables remain visible in [locals], but do not dynamically become local variables.

distant salmon
#

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

distant salmon
distant salmon
distant salmon
#

Totally legit 51b solution

find_number=lambda f:f.__closure__[0].cell_contents
distant salmon
#

It is this problem

versed eagle
#

oh interesting

fleet bridge
night quarryBOT
#

@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
fleet bridge
#

ohh

#

nvm

#

at least it is a UnboundLocalError, not a NameError

distant salmon
#

!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)")
night quarryBOT
#

@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
distant salmon
fleet bridge
#

Consistency sucks

versed eagle
#

iirc there's a pep to fix lots of that

humble portal
versed eagle
#

wdym

humble portal
#

eval executes code better than exec

versed eagle
#

again, wdym

humble portal
#

(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)")
night quarryBOT
#

@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'
versed eagle
#

put them in parentheses

#

(var := val)

humble portal
#

!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)")
night quarryBOT
#

@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

versed eagle
#

not inside f strings

humble portal
#

!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)")
night quarryBOT
#

@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
versed eagle
#

you made that more complicated than it had to be

humble portal
#

my bad lol

versed eagle
#

it's fine

distant salmon
#

Btw the output is exactly the same

versed eagle
#

mhm

fleet bridge
#

Because eval and exec works almost the same

versed eagle
#

eval and exec do essentially the same thing, besides the restriction on statements in eval

humble portal
#

yeah 🤔 ah, it was eval can return the output, but exec cant

versed eagle
#

eval evaluates an expression

humble portal
#

!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)")
night quarryBOT
#

@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
versed eagle
#

print(var := val)

humble portal
#

those are the illegal way to run code in eval haha

versed eagle
humble portal
#

!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)")
humble portal
versed eagle
#
eval('''exec("""
...
""")''')
versed eagle
humble portal
versed eagle
fleet lintel
#

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

karmic pumice
#

!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]))
night quarryBOT
#

@karmic pumice :white_check_mark: Your 3.11 eval job has completed with return code 0.

[3, [2, [1, []]]]
fleet lintel
karmic pumice
#

hmmh i cant see whats wrong with it

#

oh i see

fleet lintel
#

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

karmic pumice
#

nice

#

my brain too fried to do the quote dancing

fleet lintel
#

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")

vast wave
fleet bridge
#
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()
#

🤷‍♂️

rugged sparrow
#

Ooo that's useful for my asm patcher

fleet lintel
# karmic pumice <:pithink:652247559909277706>

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.

karmic pumice
#

i see so kinda similar to rust

fleet bridge
#

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

fleet lintel
#

That makes sense from what I know of assembly.

fleet bridge
#

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

next flame
vast wave
next flame
#
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

fleet lintel
#

The execute finally falls

next flame
#

still a one liner

vast wave
#

not a one expressioner

next flame
fleet lintel
#

I see it as it's in the language, so it's fine unless stated otherwise.

next flame
#

-20 bytes if you drop the long func name

distant salmon
#

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]))

?

night quarryBOT
#

@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.

[1, [2, [3, [[...]]]]]
distant salmon
#

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([]))
night quarryBOT
#

@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | []
002 | [[...]]
fleet lintel
#

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.

versed eagle
#

something like this should work, right?

def create_recursive_list(a):
    r=[a];[r:=[e,r]for e in a[::-1]];return r
fleet lintel
#

It doesn't get the recursion [1, [2, [3, [[1, 2, 3]]]]]

distant salmon
distant salmon
versed eagle
#

sorry, im too tired for this lmao

distant salmon
#

!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]))
night quarryBOT
#

@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, [...]]]]]
versed eagle
fleet lintel
#

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.

next flame
# next flame its the same thing
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
distant salmon
# next flame its the same thing

!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
versed eagle
night quarryBOT
#

@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

distant salmon
#

See how nice the return m version is

next flame
#

still the same values

versed eagle
#

no

next flame
#

just that one has an extra expansion

fleet lintel
#

The more I think about it, the more I agree that create_recursive_list([]) should be [[...]]

distant salmon
next flame
#

the extra [1, [...]] doesn't matter

distant salmon
# next flame 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)
night quarryBOT
#

@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, [...]]]]
versed eagle
#

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]

versed eagle
unkempt shore
#

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.

fleet lintel
unkempt shore
versed eagle
compact raven
#

Making a shallow copy of most mutable types:

y = type(x)(x)

vast wave
#

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)

fleet bridge
#

Almost symmetrical

fleet bridge
#

So type(x)(x) is always better

rugged sparrow
fleet bridge
#

there is a copy.deepcopy

#

copy.copy is shallow

rugged sparrow
#

Ah

versed eagle
#

a free 4 bytes in exchange for namespace pollution

#

not a bad deal

craggy hamlet
#

!e

alphabet = dict(zip(list(map(str.lower, [*__import__('this').__dict__['d'].keys()])), [*range(1,27)]));print(alphabet)
night quarryBOT
#

@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

craggy hamlet
#

hello esoteric python channel, this is my import this alphabet

#

this is what full output looks like

fathom arch
#

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

fleet bridge
#

If your goal is to print to stdout or stderr, you cant do that without touching stdout or stderr, directly or indirectly

distant salmon
#

There is also

  1. sys.stdout.write('Hello, World!\n')
  2. sys.stdout.buffer.write(b'Hello, World!\n')
  3. 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

fleet bridge
unique heath
quartz wave
#

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

distant salmon
distant salmon
#

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()
night quarryBOT
#

@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | f
002 | g
quartz wave
#

well stdout looks alright but it errors

distant salmon
distant salmon
fleet bridge
#
>>> 1 // print
1
>>> 1 // str
'1'
>>> '123' // int
123
>>>
>>> (print @ repr @ str) (5)
'5'
>>> (print @ len @ str) (123)
3

fleet bridge
#

~~```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)
fleet lintel
#

Sadly I don't think it's possible, but it would be really funny to overwrite as so it functioned like in C#.

fathom arch
#

or some weird ctypes hook

fleet bridge
#

I kinda like it

versed eagle
#

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))
fleet lintel
unique heath
#

!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")```
night quarryBOT
#

@unique heath :warning: Your 3.11 eval job has completed with return code 0.

[No output]
unique heath
#

!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"))```
night quarryBOT
#

@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.

anana
unique heath
#

!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))```
night quarryBOT
#

@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.

nan
unique heath
#

is it just
banana
anana
anan

versed eagle
unique heath
#

!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))```
night quarryBOT
#

@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.

sfs
unique heath
#

!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))
night quarryBOT
#

@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.

x
unique heath
#

!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"))
night quarryBOT
#

@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.

x
quartz wave
#

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

unique heath
#

god damnit cereal you spoiled it

quartz wave
#

sor

#

y

#

:3

versed eagle
fleet lintel
# versed eagle ||that's right! its interesting to see how it distorts as others deobfuscate it...

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? ||

quartz wave
#

also

#

is lsp("banana", 5) supposed to have "n" as the result

fleet lintel
#

Can you spoiler images?

#

found it

fleet lintel
versed eagle
quartz wave
#

ah

versed eagle
#

im not at my computer rn but in a bit ill send an unobfuscated version of it

quartz wave
#

||```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

quartz wave
#

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))

versed eagle
#

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)

fleet lintel
#

@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""

versed eagle
#

ooo nice

#
lsp=lambda i:i==i[::-1]and i or max(lsp(i[1:]),lsp(i[:-1]),key=len)if i else""
quartz wave
#

either that or it's taking too long

versed eagle
quartz wave
#

one of these ```py
lsp("aishfgaioshgasagioioioioiaioioioioi");lsp("aishfgaioshgasag");lsp("banana");lsp("");lsp("abcd")

versed eagle
#

the first one takes a really long time

fleet lintel
#

It will take a while, it's basically binary search with all repetitions.

versed eagle
quartz wave
#

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

fleet lintel
#

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.

quartz wave
#

66 i think ```py
lsp=lambda i:i!=i[::-1]and max(lsp(i[1:]),lsp(i[:-1]),key=len)or i

versed eagle
#

no

#
>>> lsp("nasdklfjlksdkla")
'a'
#

simpler reproducing case

>>> lsp("cab")
'b'
fleet lintel
#

Should it be "c"?

versed eagle
#

yeah

#

in case of a tie, lexicographically greatest is supposed to win

fleet lintel
#

Interesting, in the case of key=len the tie-breaker is just the first element

quartz wave
#

so revert to 110?

fleet lintel
#

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!

quartz wave
#

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))

versed eagle
quartz wave
versed eagle
#

yeah i got the same error

#

im looking for the typo

#

cause what i typed in my terminal works :<

quartz wave
#

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("")

versed eagle
#

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

fleet lintel
#

:D

#

Also I had a great idea to type when I get home

gusty dust
#

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?

quartz wave
gusty dust
#

👀?

quartz wave
#

in fact

#

the infinite recursion case (i.e. ...) is handled in tuple.__repr__

quartz wave
# gusty dust 👀?

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;
}

gusty dust
#

oh hell yeah gimme a minute

quartz wave
#

that's one way

gusty dust
#

mm

#

not a true tuple though

#

looks the part

#

but'

quartz wave
#

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]
((...),)

gusty dust
#

dude

#

🙏

#

thank you

versed eagle
fleet bridge
proper vault
#

IIRC you used length_hint and GC to get a reference to the tuple early, thus being able to yield it

fleet bridge
#

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()

night quarryBOT
#

@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 
fleet bridge
fleet bridge
#
>>> 'Enter several numbers: ' // input // str.split // (lambda x: map(int, x)) // list // sum // print
Enter several numbers: 1 2 3 4 5
15
unique heath
#

!e

import timeit
timeit.timeit("print(_it)", number=5)``` doesnt really fit the general theme but just dropping this here
night quarryBOT
#

@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)
quartz wave
fleet bridge
#

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 $: $) ?

quartz wave
fleet bridge
#

huh

quartz wave
#

it's substitution

fleet bridge
#

i see

#

that is cool

quartz wave
#
>>> 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
fleet bridge
#
>>> ~(int, '1 2 3' // str.split) // map // list
[1, 2, 3]
#

so there is no runtime tricks, it is done entirely by compiler

quartz wave
#

yep

#

modified cpython

#
>>> (int, '1 2 3' |> str.split) |> map(*$) |> list
[1, 2, 3]
fleet bridge
#
>>> (~(1,2,3) & ~{'sep':'-'}) // print
1-2-3
#

does your $ support **$?

quartz wave
#

sort of ```pycon

((1,2,3), {'sep':'-'}) |> print(*$[0], **$[1])
1-2-3

fleet bridge
#

i think i now completely undestand how it works

balmy bear
#

is anyone still messing with that code challenge?

fleet lintel
# balmy bear 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.

distant salmon
next flame
distant salmon
#

lol

fleet bridge
#
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

earnest wing
fleet lintel
fleet bridge
#
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 ![lemon_happy](https://cdn.discordapp.com/emojis/762082156474138635.webp?size=128 "lemon_happy")
fleet lintel
#

From here I really don’t see any further progress, everything is doing the max possible with the min footprint

night quarryBOT
#

hoopy/runtime.py lines 354 to 355

"<": "<<",
">": "<<",```
fleet bridge
#

isnt that a typo?

earnest wing
#

No

#

It's the first character

quartz wave
distant salmon
#

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?

fleet lintel
distant salmon
#

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...

distant salmon
fleet lintel
#

Does it not work with the if else base?

distant salmon
fleet bridge
#
sizeof(4)
``` 💀
#

not python, but weird anyway

unique heath
earnest wing
#

all good python programs should be at least 70% red underlines

fleet bridge
#

True

#

Pyright is annoying

sick hound
#

Can we print "\n" in python?

unique heath
#

wrong channel

fleet bridge
#

!e @sick hound try this

print(1)
__import__('sys').stdout.write(int.__doc__[len(int.__doc__.splitlines()[0])])
print(2)
night quarryBOT
#

@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 1
002 | 
003 | 2
fleet bridge
#

Nice, first try

unique heath
#

real

fierce nexus
#

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"

fleet bridge
#

maybe open help thread?

fierce nexus
#

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!

serene stratus
#

Has someone tried making python case insensitive?

fleet bridge
# serene stratus 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

serene stratus
#

But now strings will be case insensitive as well?

#

Pretty cool you're able to do it with so little code

astral rover
#

is this one lineable nicely```py
commands = []
command = self
while isinstance(command, Command):
commands.append(command)
command = command.parent

    return commands```?
last locust
#

You might be able to use iter magic to replace the while loop, but not sure about the command reassignment

astral rover
#

two arg iter doesnt work here unfortunately

fleet bridge
# astral rover is this one lineable nicely```py commands = [] command = self ...

!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')

night quarryBOT
#

@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)
fleet bridge
#

(my code reassigns self, but it is easy to change)

last locust
#

Yeah, that seems about right

#

Figured you could use iter with a sentinel

astral rover
#

issue is parent isnt Self | None

#

its Self | Something | None

#

oh wait

#

that still works

fleet bridge
#

yeah

astral rover
#

forgot it took a callable

#

thanks

versed eagle
fleet bridge
#

?

versed eagle
#

this is the wrong channel, and probably the wrong server, for.. whatever that is

fluid pumice
#

After reading esoteric python for some time
I understand it more

brazen arrow
#

i want to subclass int.

#

so what should i look out for hmmm

burnt pasture
brazen arrow
#

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

Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.