#esoteric-python

1 messages ยท Page 137 of 1

coral kernel
#

but i think height = 0 is defined as x

#

guess it depends on the definition, there are several ways to express tetration

#

when i experimented with tetration, i also thought of ways to make mathematical passwords

#

my thought process was that tetration requires enormous amounts of memory and power, so what if you used something like str(3**3**3.1**2)[:-100]) as password

#

although it's quite difficult to juggle between overflow and too small

#

benefit would be that it'd be really hard to brute-force

#

actually the power-root algo could make this much more feasible

#

if you set max_iters very high

#

but it might need something with arbitrary precision, np.double doesn't look like a good fit for that

rapid sparrow
#

I tried brute-forcing

#

every upper and lower-case 5-lettee sequence

#

no match

night quarryBOT
#

@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.

P
rapid sparrow
#

it's still P, lol

coral kernel
#

oh, your snippet earlier

rapid sparrow
#

i just ran code yeah

#

not realizing it was the same I ran earlier

long fulcrum
#

how cannn I golf this py k=P=1 while k<1e4:P%k>0==print(k);P*=k*k;k+=1

dire lake
#

yo

#

I am trying out exception and error handling.

#

so i want to loop through a function until given value type is correct. In this case its an integer value or float.

#
while True:

    # Hoeveel kinderen?
    kinderen = 0
    try:
        while kinderen <= 0:
            kinderen = int(input("Hoeveel kinderen?\n"))
    except ValueError:
        print("DAT IS GEEN GETAL!")```
#

this is what i tried.

#

so after it says DAT IS GEEN GETAL! i want the console to ask again "Hoeveel kinderen?"

severe canyon
#

isnt that what it does?

#

@dire lake

errant crescent
# long fulcrum how cannn I golf this ```py k=P=1 while k<1e4:P%k>0==print(k);P*=k*k;k+=1```
k, p = 1, 1
while k < 1e4:
   p%k>0 and print(k)
   p *= k**2
   k += 1

Now shortened -

from math import prod, ceil
# numpy.prod() also works.
mult = lambda x: prod(i**2 for i in range(x))
[print(k) for k in range(ceil(1e4)) if not mult(k)%k]

** Obviously mult(multiply) function could be replaced to be inside the loop, but to keep things somewhat comprehendable, I split it into 2 parts.

severe canyon
#

!e

print(type(1e4))
night quarryBOT
#

@severe canyon :white_check_mark: Your eval job has completed with return code 0.

<class 'float'>
severe canyon
errant crescent
#

!e

k = 1
print(1e4 > k)
errant crescent
# severe canyon `range(1e4)` is not valid, since 1e4 is a float and not an int

No problemo, imma change it to numpy. Then it should work. Although it does seem odd... I tried keeping true to the original code, yet even in it he just adds 1 to it. Keeping everything as an integer

Scrape this, because its an integer anyways, imma round it up (54 < 54.59 < 55) and keep it that way. As it practically does the same thing.

severe canyon
#

still, using numpy would make it way larger than the original 45 bytes

severe canyon
#

Indeed.

errant crescent
#

Thats why I only imported the important stuff from math. [.prod() and .ceil()]

severe canyon
#

id say the original is already golfed, dont think you can do much else to shorten it

#

tried some different thing and couldnt get shorter

errant crescent
severe canyon
#

golfing isnt about being fast, if the program takes 9000 years.. it will take 9000 years hehe ๐Ÿ˜ˆ

#

but you do you :)

teal saffron
#

hey guys how work python obfuscators? and what i need to do one?

dark wharf
#

It's called sending us the code and asking us to try golfing it

#

It'll be illegible and not even do what you want it to do

#

But hey this is a free service you get what you get :)

severe canyon
#

cant ask for everything haha

long fulcrum
#

1 char can be removed but I literally have no idea where

#

No it's in python 3

#

I can see the leaderboard

#

7 people have 44 chars

severe canyon
#

oh, its a leaderboard thing

#

where?

long fulcrum
#

code.golf

severe canyon
#

i took a look at the numbers, is this just getting all primes under 10000?

long fulcrum
#

yeah

severe canyon
#

damn

long fulcrum
#

what?

severe canyon
#

im just impressed this calculates primes

long fulcrum
#

It uses Wilson's theorem

severe canyon
#

i looked at it for a little while now and i give up trying to find a way xD

#

let me know if you get the solution

#

:)

long fulcrum
#

I really doubt I'll be able to

#

Another two I struggle with on that site are evil numbers and odious numbers

#

Literally no idea how people remove 10 chars from my solution

#
[print(i)for i in range(51)if~i.bit_count()&1]```
#

That's my evil solution

#

Odious is a space instead of a ~

#

Evil you can remove 6

#

Oh odious is 6 as well i thought one was 10

golden finch
#

do I look like I have this much time? my guess is you're using zero width spaces and zero width nonjoiners

rapid sparrow
#

you can spend lots of time and have nothing to show for it except for horrified looks

golden finch
#

I mean I'm making something esoteric rn

rapid sparrow
#

oh lol

#

good

rapid sparrow
#

oh my gosh, I thought you'd love itttttt

#

et tu ?

#

come on people what channel are we in here

#

not #neat-and-elegant-python

sick hound
#

i love it but you did massacre it

#

very well

sick hound
rapid sparrow
#

what's not to like, really

#

it's how I do code golf โ›ณ ๐ŸŒ๏ธโ€โ™‚๏ธ

#

import gzip

#

work smarter not harder you know

#

I wanted to use xz or bz2 but those don't work for me so I was unable to test them

#

โšฐ๏ธ

fleet bridge
#

!e

type('',(),{'__getattr__':lambda s,a:exec(__import__('base64').b64decode(a+'='))})().cHJpbnQoIkhlbGxvIHdvcmxkISIp
night quarryBOT
#

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

Hello world!
fleet bridge
#

!e

g='__getattr__'
T=type
M=T('',(),{g:lambda s,m:__import__(m)})()
T('',(),{g:lambda s,a:exec(M.zlib.decompress(M.base64.b64decode(a+'=')))})().eJwrKMrMK9FQ8kjNyclXKM8vyklRVNIEAFQKByA
night quarryBOT
#

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

Hello world!
fleet bridge
#

zlib + base64 packed code

#

oh no, there are only 26+26+10+1 = 63 valid chars for attr

#

!e

g = '__getattr__'
T = type
M = T('', (), {g: lambda s, m: __import__(m)})()
C = T('', (), {g: lambda s, a: exec(M.zlib.decompress(M.base64.b32decode(a.replace('_','='))),{})})()
C.PCOKKVCRN3BSADH5Z4U7VCOXVQDYRSSJUIEFCQVKVAXEIQBXNXJ64PSCQOJLLJDLSZ6NTT4OT76TAZANI4VTO5CDSCPQ6NJPBDAI4MMB3RNMNSANVJV4TWGOZAHLTECENDDM2UPIRNZLJLBIEWIHXKGTKYV7YSCEJ3XTGAMFLL4DMJUIOVOJY3H3FEBVMVR52YQD6WSKVYAOZ56EP6B3HDIGXTOGGYYQILWX4CU2DRWAQTXHJ6JTYZSJMCUT6RRLD4DF6RPWA7DS2WOUIJMWPYZR6CZ7INRBCAJLYDC42VPBNRTKFUMCXH3MFYGVNW2FOWLR43NRVK45O2CVPFIOFDM3IGGOANSGJIHUKV2IYSE5XNBI7PWNTHMKBFI6HWOETDKLJRR2NSKVI6VS7466B6ABC4WO66CX423QB4VP576GCR2A4BNOVV63OB7XZ753SKR7RTYYYU5LECVSZ22MVEPQ5RA7MAZOU54CS___
night quarryBOT
#

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

False
fleet bridge
#

get compressed code:```py
import base64
import zlib

code = b"""
your code here
"""

print(base64.b64encode(zlib.compress(code, 9)))
execute compressed code:py
exec((I := import)('zlib').decompress(I('base64').b64decode('<compressed code>')))

#

i think it is most effective way to golf large code

vestal solstice
#

hm does b64 help

#

it's under 4 bytes per byte before b64

#

b64 is 1.33

#

so it's worth it i guess

#

would utf-16 give 1 to 1?

#

interesting, when it actually encodes it blows up to 1.5

#

of wait of course it does

sick hound
#

!e ```py
n=int(import("sys").argv[1:][0
])
for(i)in[range(n)]:p=print;c= (i
+( 1- n%
2) (n/2<=i))%2;a,b=[[(n- i) //
2] 2 ,[ -1 +c
+i // 2,i//2+c]][i
2 <n ]; h
=( 2
7) ( 14 +1 )
// 2; h= int(h/ (2 ( 2+ 1)
/2 )) ;L =[ 1] ( (3 -2
)
h) ;( r)=sum(L)
(1 +1 -1
1 /1 ** 11 ); (x
)= r; h=chr(int(r));f=(2 +3 2
5 )+ 0; (s
)= chr(f);X=h+h+s+s;p(X
a+2
( h+
s) [c
]
(n-2
[0,a][a>=1]-2
b)+X[::-1]*b)

night quarryBOT
#

@sick hound :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | IndexError: list index out of range
sick hound
#

oh fww

#

!e ```py
print(import('random').choice(
[( '1'
)+ chr(int(ord('ว‚')/ 10
)) +chr( 5*17 )

  • chr(2            *56)      ,
    

'' +chr( 7*11 )

  • chr(             5*23     +2
    

)+ chr(5* 23
)+ chr(10* 10
+4 )+chr( 5*
22 +2*2)+ ''

  •         chr(2*            56
    

-1 )+chr( 37

  •                            3
    

)+ chr(99 +
10 ),chr( 83
)+ ''
+chr(429)+chr(424+1)+chr(114)]))

night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

Star
severe canyon
#

kewl

sick hound
#

!e ```py
import sys
def R(H):X=int(255*(1-abs((H/60)%2-1)));C=255;return[[[[[(C,0,X),(X,0,C)][H<300],(0,X,C)][H<240],(0,C,X)][H<180],(X,C,0)][H<120],(C,X,0)][H<60]
i=0
for l in open(*(sys.argv+[0])[1:2]):print("".join("\033[38;2;%d;%d;%dm"%R(h%360)+c for h,c in enumerate(l,i)),end="\033[0m");i+=8

night quarryBOT
#

@sick hound :warning: Your eval job has completed with return code 0.

[No output]
sick hound
#

!e

def multAStrByFloat(string:str, floatInput:float):
    return string * int(floatInput) + "".join(list(string)[0:int(len(string) / int(str(floatInput).split(".")[1]))])

print(multAStrByFloat("Java Sucks", 1.2))
night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

Java SucksJava 
sick hound
#

Does this function have a purpose? Will I ever use it? Why did I even create it? All these questions have unknowable answers

severe canyon
sick hound
#

I noticed that too, fixed it already

#

!e

def multAStrByFloat(string:str, floatInput:float):
    return string * int(floatInput) + "".join(list(string)[0:int(round((len(string) * (floatInput - int(floatInput))), 0))])

print(multAStrByFloat("Java Sucks", 1.2))```
night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

Java SucksJa
severe canyon
#

hehe

#

tried golfing it:
!e

f=lambda s,n:s*int(n)+s[:int(round(n%1,2)*len(s))]
print(f("Java Sucks",1.2))
sick hound
#

!e

f=lambda s,n:s*int(n)+s[:int(round(n%1,2)*len(s))]
print(f("Java Sucks",1.2))
night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

Java SucksJa
sick hound
#

You forgot to place the code with the !e in its own message

severe canyon
#

yeah yeah whatever xD

sick hound
#

But nice that that absolutely useless piece of code got golfed

severe canyon
#

isnt that what life is about?

#

i think its a fun thing, fractional strings ๐Ÿ˜

sick hound
#

I just created that to spite a Rust programmer I know who hates that Python allows string multiplication

severe canyon
#

xDD

#

worth

#
f=lambda s,n:s*int(n)+s[:round(n%1*len(s))]

a bit smaller

sick hound
#

smoll eldritch code โ™ฅ๏ธ

severe canyon
#

:D

jolly sky
#

This entire channel is basically a big "f you" to the readibility of Python lmao

severe canyon
#

yessir

sick hound
#

We are an affront to god themself with our code!

finite blaze
#

Hey guys, quick question
Is there any way to make inputs shorter?

x1 = int(input("x1: "))
y1 = int(input("y1: "))
x2 = int(input("x2: "))
y2 = int(input("y2: "))
sick hound
#
i = input
#

and then

dark wharf
#

x1,y1,x2,y2 = [int(input(f'{t}: ')) for t in ('x1','y1','x2','y2')]

sick hound
#
x1 = int(i("x1: "))
dark wharf
finite blaze
#

Thanks, that works

finite blaze
sick hound
#

I prefer readability over efficiency

finite blaze
#

i am trying to golf my code

next flame
#

just get rid of prompts to save chars

sick hound
#

and replace x1, y1, x2, and x2 with i, j, k, and l

#

saves one character each

finite blaze
#

yeah, will do that later on

dark wharf
#

Might be a tiny bit shorter if you still want readability

#

i used to do this on my files but I called the func intput

severe canyon
#
x1,y1,x2,y2=[int(input())for i in[0]*4]

ยฏ_(ใƒ„)_/ยฏ

dark wharf
#

well call them abcd

sick hound
#

just for the lols, use emojis for the variable names while golfing ๐Ÿ‘†, ๐Ÿ‘‡, ๐Ÿ‘ˆ, and ๐Ÿ‘‰ instead of x1, y1, ...

dark wharf
#

Massive iq moment

finite blaze
#

will do will do

dark wharf
#

ah yes i write my golfed code in heiroglyphics

#

Wait no it might be

sick hound
#

Hieroglyphics make code 10% faster, add RGB lighting and you get 200% speed boost to your code

severe canyon
#

dont forget the gamer chair

dark wharf
#

Depending on the type of the glyph you pray to a different god and you get different code buffs

sick hound
#

And wear your coding socks

dark wharf
#

all my homies code in Anubis for resurrected variables

dark wharf
severe canyon
#

i need things to golf brainmon

finite blaze
#
from sympy import *
for line in open("i"):
    l = list(map(int,line.rstrip().split(",")))
    a,b,c,d = l[0],l[1],l[2],l[3]

    F,S = "",""

    D,C = 0,0

    if(a == c): F = f"y={a}"
    else:
        m = (b - d) / (a - c)

        _b = symbols('b')
        expr = solve(Eq(b,m*a+_b))
        b = float(expr[0])
        if (m).is_integer(): m = int(m)
        if (b).is_integer(): b = int(b)

        if(b) == 0: F = f"y={m}x"
        else: F = f"y={m}x+{b}" if b>0 else f"y={m}x{b}"

        D = a if a > c else c
        C = a if a < c else c

        S = "+" if C>0 else "-"

    E = r"f\left(x\right)\ =" + F.split("=")[1] + r"\cdot" + r"\sqrt{\frac{\left|\left|x-\frac{" + str(D)
    E += S + str(abs(C))
    E += r"}{2}\right|-\frac{" + str(D)

    if S == "-": E += f"+{abs(C)}"
    else: E += f"-{abs(C)}"

    E += r"}{2}\right|}{\frac{" + str(D)

    if S == "-": E += f"+{abs(C)}"
    else: E += f"-{abs(C)}"

    E += r"}{2}-\left|x-\frac{" + str(D) 
    E += S + str(abs(C))
    E += r"}{2}\right|}}"

    print(E)
#

try it

#

i am in the golfing process rn

sick hound
#

Just golf FizzBuzz

finite blaze
#

So it takes input from file

1,3,5,10

Where
x1 = 1
y1 = 3
x2 = 5
y2 = 10

#

then

#

It generates a function that will draw line between these points

#

sample output

#

and in Desmos

severe canyon
#

hmm

next flame
#

red line is from (x1 y1) to (x2 y2)

#

so what's (3,4)?

#

and these are just linear functions so you don't need sympy

finite blaze
#
1,3,5,10
3,4,5,10
finite blaze
#

from 1031 chars to 755

#

slowly getting smaller

sick hound
#

tight and warm socks

#

@severe canyon golf this

finite blaze
#

Okay, 755 chars
that would be it for now

from sympy import*
for line in open("i"):
    l=list(map(int,line.split(",")))
    a,b,c,d,F,S,D,C=l[0],l[1],l[2],l[3],"","",0,0
    if a==c:F=f"{a}"
    else:
        m=(b-d)/(a-c)
        _b=symbols('b')
        expr=solve(Eq(b,m*a+_b))
        B=float(expr[0])
        if m.is_integer():m=int(m)
        if B.is_integer():b=int(B)
        F=f"{m}x"if B==0 else f"{m}x+{B}"if B>0 else f"{m}x{B}"
        D=str(a if a>c else c)
        C=abs(a if a<c else c)
        S="+"if C>0 else"-"
    E=r"f\left(x\right)\ ="+F+r"\cdot"+r"\sqrt{\frac{\left|\left|x-\frac{"+D+S+str(C)+r"}{2}\right|-\frac{"+D+(f"+{C}"if S=="-"else f"-{C}")
    E+=r"}{2}\right|}{\frac{"+D+(f"+{C}"if S=="-"else f"-{C}")+r"}{2}-\left|x-\frac{"+D+S+str(C)+r"}{2}\right|}}"
    print(E)
#

will comeback to it later

sick hound
#
(lambda self=[___:=((([]==[]))+(([]==[]))) , 
__:=(___)*((([]==[]))+(([]==[])))**___//___ , ____:=(__)**___ , 
_______________________:=(((__))+(__))**((([]==[]))+(([]==[])))+(([]==[]))+(([]==[]))+(([]==[]))+(([]==[])) , 
_____________:=((___)) , _____________:=((___)) , _______:=(([]==[]))+(___) , _______:=((_______))+_____________ , 
______ := chr((((___)))*((((__))))**(__)+(__)//((___))) , [[((__)+(((___)))//(____)-((___))+((___)**(___)**((_______)))) , 
_________________:=(__)+(((___)))//(____)-((___))+((___)**(___)**((_______))) , 
_________________ := ((((((((((((((_________________))))))))))))))+_______ , ((_________________),~_______________________)]\
for ___ in range(__) if ((_______)) !=[(([]==[]))-(___)]]][___]: eval(type(None).__bool__.__doc__))()

import fishhook
@fishhook.hook(int)
def __repr__(self):
    stuff = {v: k for k,v in globals().items() if isinstance(v,int) and k.startswith('_')} | {1:'_'}
    x = self
    nums = []
    for elem in sorted(stuff.keys(),reverse=True):
        while x>=elem:
            nums.append(stuff[elem])
            x-=elem
    return ','.join(nums)

MESSAGE = 'Hello'
slist = []
slist.append(MESSAGE)
x = 0
for i in range(len(MESSAGE)):
    print(ord(slist[0][x]))
    x += 1```
#

golf

finite blaze
#

(i know that i can use spaces instead of tabs)

#

down to 674 by replacing tabs

next flame
finite blaze
#

๐Ÿ‘

severe canyon
#
for l in map(eval,open(0)):
 a,b,c,d=l
 if c>a:a,b,c,d=c,d,a,b
 print(f'f\left(x\\right)\ ={(dy:=d-b)/(dx:=c-a)}x+{-a*(dy/dx)+b}'+'\cdot\sqrt{\\frac{\left|'+(f1:='\left|x-\\frac{'+(t:=str(abs(dx)+1))+'+1}{2}\\right|')+'-'+(f2:='\\frac{'+t+'-1}{2}')+'\\right|}{'+f2+'-'+f1+'}}')
#

my thing so far

#

i think the only thing it cant do is vertical lines

#

not sure tho, might have made some shortcuts that dont work

finite blaze
#

Wow, how many chars?

severe canyon
#

277 i think

next flame
#
for l in open("i"):
    a,b,c,d=eval(l);print(f"{d}+{(b-d)/(a-c)}(x-{c})\{{{a}<x<{c}\}}")

86 bytes

severe canyon
#

SHEESH

finite blaze
#

Why are you mapping to "eval"?

next flame
#

eval'ing 1,3,5,10 returns a tuple

#

and then i just got rid of as much unnecessary latex as possible

#

note that the equations won't display in the equations box, but it will still render the graph

severe canyon
next flame
#

point slope go brrr

#

wait i dont even need the extra line

#
for l in open("i"):a,b,c,d=eval(l);print(f"{d}+{(b-d)/(a-c)}(x-{c})\{{{a}<x<{c}\}}")

84

finite blaze
#

Can you give me sample output please?

#

I am at my phone rn.

next flame
#
10+1.75(x-5)\{1<x<5\}
10+3.0(x-5)\{3<x<5\}
finite blaze
#

Tyty

severe canyon
next flame
#

82 bytes with ^

finite blaze
#

I didn't expect it to go as low as 84

#

Holy crap

severe canyon
#

this @next flame guy knows his math FLOOSHED

finite blaze
#

I was like, "maybe they can go down to 500 somehow..."

next flame
#

xd

severe canyon
#

welp, thats that

next problem!

finite blaze
#

Tomorrow I will have to add more features to it

#

Cuz rn it is only able to draw straight line

#

Which is not enough

severe canyon
#

want a bezier?

finite blaze
#

Yea

severe canyon
#

@finite blaze

long fulcrum
#
import sys
from fractions import Fraction as f
n=int
for i in sys.argv[1:]:x=i.split("/");j=str(f(n(x[0]),n(x[1])));y=j.split("/");print(j+"/1")if len(y)<2else print(f(n(x[0]),n(x[1])))```
#

how can this be golfed

#

its so messy

#

its meant to just reduce a fraction

severe canyon
#

how is input formatted?

long fulcrum
#

130/146

#

however if the output is ever an integer it has to be integer/1

severe canyon
#

aight

long fulcrum
#

this is a more readable version py import sys from fractions import Fraction for i in sys.argv[1:]: x=i.split("/") j=str(Fraction(int(x[0]),int(x[1]))) y=j.split("/") if len(y)<2:print(j+"/1") else:print(Fraction(int(x[0]),int(x[1])))

severe canyon
#
import sys,math
for i in sys.argv[1:]:a,b=map(int,i.split("/"));print(f'{a//(g:=math.gcd(a,b))}/{b//g}')
#

104

#

@long fulcrum

long fulcrum
#

how the hell

severe canyon
#

you find the greatest common divisor between a and b (math.gcd(a,b)) then you divide by that

#

this ensures the most reduced fraction

long fulcrum
#

oh that makes sense

#

I kinda just presumed using a module would be shorter

severe canyon
#

does input need to be from arguments?

long fulcrum
#

im honestly not sure how the input works

#

that was the only way I could find to get it working at all

#

you can try other ways here if you want

severe canyon
#

yeah ok you need to use arguments

severe canyon
#

cant you remove the ~~ ?

#

its not doing anything?

#

also it doesnt need an f string

#

in the exec

#

98 :D

long fulcrum
#

what does f=j* do

severe canyon
#

its in an exec, and we + it with i

exec('f=j*'+i) -> exec('f=j*a/b') -> f=j*a/b
#

it takes a string, and runs what is in it, this means we can change the content being run dynamically

neat marlin
#

It's mostly a pure math thing

severe canyon
#

sure!

neat marlin
sick hound
#
return list(map(lambda x: list(map(lambda a: a.split(","), x)), lines))
finite blaze
vague cairn
#
Function = (lambda:0).__class__
Code = (lambda:0).__code__.__class__
Cell = (lambda h=50:(lambda:h).__closure__[0].__class__)()```
#

You know how you can't pickle a lambda function?

#
class Pickleable:
    def __init__(self, function):
        """wraps lambda functions to make them picklable"""
        self.function = function
        fc = function.__code__

        self.code_args = (fc.co_argcount, fc.co_posonlyargcount, fc.co_kwonlyargcount,
          fc.co_nlocals, fc.co_stacksize, fc.co_flags, fc.co_code,
          fc.co_consts, fc.co_names, fc.co_varnames, fc.co_filename,
          fc.co_name, fc.co_firstlineno, fc.co_lnotab, fc.co_freevars,
          fc.co_cellvars)
        self.function_globals_module_name = function.__globals__['__name__']
        self.function_args = (function.__name__, function.__defaults__)

        self.function__closure__ = tuple([cell.cell_contents for cell in function.__closure__]) if function.__closure__ else None
    def __getstate__(self): #This tells pickle how much of __dict__ to pickle
        return {k:v
                for k,v in self.__dict__.items()
                if k != 'function'}
    def __call__(self, *a, **k):
        if hasattr(self, 'function'):
            return self.function(*a, **k)
        #don't have it, rebuild it.
        code_object = Code(*self.code_args)
        function__closure__ = tuple(Cell(value)
            for value in self.function__closure__
            ) if self.function__closure__ else None

        self.function = function = Function(
            code_object, __import__( self.function_globals_module_name).__dict__,
            *self.function_args, function__closure__)

        return function(*a, **k)```
Now you can.
vague cairn
#

which makes multiprocessing.pool easier.

potent comet
#

You could define __setstate__() too, and build the function in there, then the state doesn't have to relate to your attributes at all.

severe canyon
# finite blaze Honestly atm I have no idea whats going on :p

*eval(l) takes the 4 numbers and makes it 4 arguments to pass into the format function, which replaces, in order, the 4 {} bracket pairs, thus completing the equation.
Equation is a linear bezier curve (which is just a straight line), and is the shortest equation i could find that works

finite blaze
#

Good shit

#

I need to learn these eval() tricks

#

I only know that eval() can run code from string.
eval("print("X")")

finite blaze
#

what does the * before eval do?

severe canyon
#

It unpacks the tuple we get out of the eval, to the 4 arguments

finite blaze
prisma coral
#

๐Ÿ

severe canyon
#

๐ŸŽ

severe canyon
#

@finite blaze
i made it work for beziers with any number of points!

for l in open(0):
 e=[*eval(l)];print((r:=lambda p:str(p[0])if len(p)<2else f'((1-t){r(p[:-1])}+{r(p[1:])}t)')([(e[i],e[i+1])for i in range(0,len(e),2)]))

and i made a little sample input:

3,1,3,0,0,0,0,5,3,4
3,1,3,0,6,0,6,5,3,4
3,4,3,4.75,2.5,5
2.5,5,2.75,5.25
2.75,5.25,3,4.5,3,4

that draws:

finite blaze
#

I used this for generating my apple

import pyperclip
res = ""
for l in open("i2"):
    if l in ['\n', '\r\n']:
        pass
    else:
        s = list(map(int,l.rstrip().split(",")))
        xs1,ys1,xs2,ys2=s[::2],s[1::2],s[2::2],s[3::2]
        for i in range(int(len(s)/2) - 1):
            x1,y1,x2,y2=xs1[i],ys1[i],xs2[i],ys2[i]
            res += f'(1-t)({x1},{y1})+({x2},{y2})t'+"\n"

pyperclip.copy(res)
#

(not golfed one)

finite blaze
severe canyon
#

nope

finite blaze
#

really?

#

visual studio code returns an error

severe canyon
#

numbers and else/if dont clash

finite blaze
#

oh wait

#

it can run

#

but it shows me an error

severe canyon
#

ยฏ_(ใƒ„)_/ยฏ

finite blaze
#

anyway, where did you find these inputs?

#

or you just made them by yourself

severe canyon
#

yeah didnt take long

#

its not pretty either

finite blaze
#

nice nice

#

someone recommended me to try making cubic splines

#

I think that might be slightly easier to make inputs by yourself

#

cuz making inputs for bezier curves is kinda tough

severe canyon
#

i see

#

the wiki page for a spline gives us an algorithm for computing cubic splines

long fulcrum
#
s=[]
v=1
exec("v=s.index(v,1)if v in s[1:]else(v:=0);s.insert(0,v);print(v);"*1000)```
#

how can this be golfed further

#

its the van eck sequence

#

The first term is zero.
If the last term is new then the next term is zero.
Otherwise the next term is how far back the term occured previously.

dark wharf
#

else 0 works just fine from brief observation

long fulcrum
#

thanks

long fulcrum
#
a="My true love sent to me\n"
b="Twelve Drummers Drumming,\n"
c="Eleven Pipers Piping,\n"
d="Ten Lords-a-Leaping,\n"
e="Nine Ladies Dancing,\n"
f="Eight Maids-a-Milking,\n"
g="Seven Swans-a-Swimming,\n"
h="Six Geese-a-Laying,\n"
i="Five Gold Rings,\n"
j="Four Calling Birds,\n"
k="Three French Hens,\n"
l="Two Turtle Doves, and\n"
m="A Partridge in a Pear Tree.\n"
o=" day of Christmas\n"
p=print
q="On the "
p(f"{q}First{o}{a}{m}")
p(f"{q}Second{o}{a}{l}{m}")
p(f"{q}Third{o}{a}{k}{l}{m}")
p(f"{q}Fourth{o}{a}{j}{k}{l}{m}")
p(f"{q}Fifth{o}{a}{i}{j}{k}{l}{m}")
p(f"{q}Sixth{o}{a}{h}{i}{j}{k}{l}{m}")
p(f"{q}Seventh{o}{a}{g}{h}{i}{j}{k}{l}{m}")
p(f"{q}Eighth{o}{a}{f}{g}{h}{i}{j}{k}{l}{m}")
p(f"{q}Ninth{o}{a}{e}{f}{g}{h}{i}{j}{k}{l}{m}")
p(f"{q}Tenth{o}{a}{d}{e}{f}{g}{h}{i}{j}{k}{l}{m}")
p(f"{q}Eleventh{o}{a}{c}{d}{e}{f}{g}{h}{i}{j}{k}{l}{m}")
p(f"{q}Twelfth{o}{a}{b}{c}{d}{e}{f}{g}{h}{i}{j}{k}{l}{m}")```
#

How could I golf this

proper vault
#

I would guess that p(f"""stuff would end up shorter

#

maybe a variable for Eleven and some of the other numbers you use in 2 places, not sure

#

{o}{a}{d}{e}{f}{g}{h}{i}{j}{k}{l}
{o+a+d+e+f+g+h+i+j+k+l}

fleet bridge
#

"{q}Twelfth{o}{a}{b}{c}{d}{e}{f}{g}{h}{i}{j}{k}{l}{m}"
q+"Twelfth"+o+a+b+c+d+e+f+g+h+i+j+k+l+m

#

you can also define new vars for something which appears many times
r=o+a
s=f+g+h+i+j+k+l+m

#
a="My true love sent to me\n"
b="Twelve Drummers Drumming,\n"
c="Eleven Pipers Piping,\n"
d="Ten Lords-a-Leaping,\n"
e="Nine Ladies Dancing,\n"
f="Eight Maids-a-Milking,\n"
g="Seven Swans-a-Swimming,\n"
h="Six Geese-a-Laying,\n"
i="Five Gold Rings,\n"
j="Four Calling Birds,\n"
k="Three French Hens,\n"
l="Two Turtle Doves, and\n"
m="A Partridge in a Pear Tree.\n"
o=" day of Christmas\n"
p=print
q="On the "
r=o+a
t=j+k+l+m
s=f+g+h+i+t
u=d+e+s
v=i+t
p(q+"First"+r+m)
p(q+"Second"+r+l+m)
p(q+"Third"+r+k+l+m)
p(q+"Fourth"+r+t)
p(q+"Fifth"+r+v)
p(q+"Sixth"+r+h+v)
p(q+"Seventh"+r+g+h+v)
p(q+"Eighth"+r+s)
p(q+"Ninth"+r+e+s)
p(q+"Tenth"+r+u)
p(q+"Eleventh"+r+c+u)
p(q+"Twelfth"+r+b+c+u)
#

Eleven, Seven

#

a lot of ,\n

#

!e


N=',\n'
n='ing'+N
E='Eleven'
a="My true love sent to me\n"
b="Twelve Drummers Drumm"+n
c=E+" Pipers Pip"+n
d="Ten Lords-a-Leap"+n
e="Nine Ladies Danc"+n
f="Eight Maids-a-Milk"+n
g="Seven Swans-a-Swimm"+n
h="Six Geese-a-Lay"+n
i="Five Gold Rings"+N
j="Four Calling Birds"+N
k="Three French Hens"+N
l="Two Turtle Doves, and\n"
m="A Partridge in a Pear Tree.\n"
o=" day of Christmas\n"
q="On the "
r=o+a
R='th'+r
t=j+k+l+m
s=f+g+h+i+t
u=d+e+s
v=i+t
p=print
p(q+"First"+r+m)
p(q+"Second"+r+l+m)
p(q+"Third"+r+k+l+m)
p(q+"Four"+R+t)
p(q+"Fif"+R+v)
p(q+"Six"+R+h+v)
p(q+"Seven"+R+g+h+v)
p(q+"Eigh"+R+s)
p(q+"Nin"+R+e+s)
p(q+"Ten"+R+u)
p(q+E+R+c+u)
p(q+"Twelf"+R+b+c+u)
night quarryBOT
#

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

001 | On the First day of Christmas
002 | My true love sent to me
003 | A Partridge in a Pear Tree.
004 | 
005 | On the Second day of Christmas
006 | My true love sent to me
007 | Two Turtle Doves, and
008 | A Partridge in a Pear Tree.
009 | 
010 | On the Third day of Christmas
011 | My true love sent to me
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/afasiwipid.txt?noredirect

fleet bridge
#

904 -> 662

severe canyon
#
for n in range(12):print("On the "+['First','Second','Third','Fourth','Fifth','Sixth','Seventh','Eighth','Ninth','Tenth','Eleventh','Twelfth'][n]+" day of Christmas\nMy true love sent to me\n"+'\n'.join(["Twelve Drummers Drumming,","Eleven Pipers Piping,","Ten Lords-a-Leaping,","Nine Ladies Dancing,","Eight Maids-a-Milking,","Seven Swans-a-Swimming,","Six Geese-a-Laying,","Five Gold Rings,","Four Calling Birds,","Three French Hens,","Two Turtle Doves, and\n"][-n:]if n else[])+"A Partridge in a Pear Tree.\n")

dont wanna do more on this...

#

513

fleet bridge
#

!e

for n in range(12):print("On the "+['First','Second','Third','Fourth','Fifth','Sixth','Seventh','Eighth','Ninth','Tenth','Eleventh','Twelfth'][n]+" day of Christmas\nMy true love sent to me\n"+'\n'.join(["Twelve Drummers Drumming,","Eleven Pipers Piping,","Ten Lords-a-Leaping,""Nine Ladies Dancing,","Eight Maids-a-Milking,","Seven Swans-a-Swimming,","Six Geese-a-Laying,","Five Gold Rings,","Four Calling Birds,","Three French Hens,","Two Turtle Doves, and\n"][-n:]if n else[])+"A Partridge in a Pear Tree.\n")
night quarryBOT
#

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

001 | On the First day of Christmas
002 | My true love sent to me
003 | A Partridge in a Pear Tree.
004 | 
005 | On the Second day of Christmas
006 | My true love sent to me
007 | Two Turtle Doves, and
008 | A Partridge in a Pear Tree.
009 | 
010 | On the Third day of Christmas
011 | My true love sent to me
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/isihinowap.txt?noredirect

fleet bridge
#

!e

for n in range(12):print("On the "+['First','Second','Third','Fourth','Fifth','Sixth','Seventh','Eighth','Ninth','Tenth','Eleventh','Twelfth'][n]+" day of Christmas\nMy true love sent to me\n"+'\n'.join(["Twelve Drummers Drumming,","Eleven Pipers Piping,","Ten Lords-a-Leaping,""Nine Ladies Dancing,","Eight Maids-a-Milking,","Seven Swans-a-Swimming,","Six Geese-a-Laying,","Five Gold Rings,","Four Calling Birds,","Three French Hens,","Two Turtle Doves, and","A Partridge in a Pear Tree.\n"][10-n:]))
night quarryBOT
#

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

001 | On the First day of Christmas
002 | My true love sent to me
003 | A Partridge in a Pear Tree.
004 | 
005 | On the Second day of Christmas
006 | My true love sent to me
007 | Two Turtle Doves, and
008 | A Partridge in a Pear Tree.
009 | 
010 | On the Third day of Christmas
011 | My true love sent to me
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/umowikidok.txt?noredirect

fleet bridge
#

502

long fulcrum
#

that doesnt work unfortunately

fleet bridge
long fulcrum
#

its really weird

severe canyon
#

gives wrong output in the end

long fulcrum
#

oh one of the issues is yous dropped a , along the way

#

between the ten lords and the nine ladies

#
for n in range(12):print("On the "+['First','Second','Third','Fourth','Fifth','Sixth','Seventh','Eighth','Ninth','Tenth','Eleventh','Twelfth'][n]+" day of Christmas\nMy true love sent to me\n"+'\n'.join(["Twelve Drummers Drumming,","Eleven Pipers Piping,","Ten Lords-a-Leaping,","Nine Ladies Dancing,","Eight Maids-a-Milking,","Seven Swans-a-Swimming,","Six Geese-a-Laying,","Five Gold Rings,","Four Calling Birds,","Three French Hens,","Two Turtle Doves, and","A Partridge in a Pear Tree.\n"][11-n:]))```
severe canyon
#

yeah i did, my bad

#

i updated it above

fleet bridge
#

!e

import base64,zlib;exec(zlib.decompress(base64.b64decode('eNrlll1OwzAQhN9zilGfQGq5A/SPhxQqkgtY9bZe4diV7Tb09qxTDlALEAWe8jfj+WaTKNkHdulmNBo9OyRDWHCICVqd4LeYmsAxdSpWqxNSOBCsPxIiuYTk0VF1j7UKKbDeEdhBYU0qoA1Ed1X1sWRDG+/05Wu2vUd7CMkSZnIpjqGcviipNRxKgoy4sQjkNgaP5OL4E9kLLzZzeXjWY6qsZbfDg3Dn9C8F4m0RD8vx0luNFyGS5G8HbPitBFDkWBJFmqhJrU5CNf4JaDoKUgl2NqDplYsC3vTcdQP6ddSZ886UtBn0WCnWuc2K7eu5zFWXfOKiOyZyQq00U8RMuc1A/SuLt2WPqshR+zA0rEntB+q/M425LX13zw6seU8h5s1A/sfH1PZki74c2SBnZuHQdXlOw865/z+an/xC3b4DgIohXw==')))
night quarryBOT
#

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

001 | On the First day of Christmas
002 | My true love sent to me
003 | A Partridge in a Pear Tree.
004 | 
005 | On the Second day of Christmas
006 | My true love sent to me
007 | Two Turtle Doves, and
008 | A Partridge in a Pear Tree.
009 | 
010 | On the Third day of Christmas
011 | My true love sent to me
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/bocaraxupe.txt?noredirect

fleet bridge
#

498

severe canyon
#

no imports :)

fleet bridge
#

can i use __import__?

severe canyon
#

:)

long fulcrum
#

yep

severe canyon
#

only builtins allowed it seems

vague cairn
#

I'm also figuring I need to build a nested check to verify that any cell variables in __closure__ that happen to be lambda's also get wrapped.

sick hound
#

!e

night quarryBOT
#
Command Help

!eval [code]
Can also use: e

*Run Python code and get the results.

This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.

We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*

sick hound
#
#! /usr/bin/env python
from sys import argv
from random import randint as r

print(''.join([chr((lambda:r(33,127))())for i in range(0,int(argv[1]))]))
#

any more tricks I could use? I was thinking maybe use map function some how idk

finite blaze
#

Can't you do something like
import random
And then just use randint instead or r

dark wharf
#

Same thing with the from sys

#

import sys, random

#

Is shorter

#

or actually maybe import sys, random as r

finite blaze
#

Let me check

#

Original: 125 chars (without new lines)

#
import sys,random as r
print(''.join([chr((lambda:r(33,127))())for i in range(0,int(argv[1]))]))โ€Š
#

96

dark wharf
#

wait why the use of lambda here in the first place

#

just clocked, pretty sure we don't need it

dark wharf
finite blaze
#

There was something like
from sys,random import*

#

Or something

#

Don't remember

dark wharf
#

chr(r.randint(33,127)) for i in range ... would work here no

#

the lambda would only be necessary if you were trying this with map

dark wharf
#

It's like 2 chars shorter

grave rover
finite blaze
#

Then just use
from sys,random import*
And then you can call randint

finite blaze
#

Okay, don't remember how it worked

grave rover
#
$ python
Python 3.10.1 (main, Dec 11 2021, 17:22:55) [GCC 11.1.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from sys, random import *
  File "<stdin>", line 1
    from sys, random import *
            ^
SyntaxError: invalid syntax
dark wharf
#
import sys, random as r
print(*[chr(r.randint(33,127))for _ in range(int(sys.argv[1]))],sep='')
finite blaze
#

Can you do something like
import sys, random as s,r?

dark wharf
finite blaze
#

95

#

Without new lines

dark wharf
#

Nice, given that this one used sys. and r. properly

#

ah wait there may be shorter

#
import sys, random as r
print(''.join(chr(r.randint(33,127))for _ in range(int(sys.argv[1]))))
``` does this work?
#

Pretty sure you can throw a generator in there without brackets

#

!e

import sys, random as r
print(''.join(chr(r.randint(33,127))for _ in range(int(12))))
night quarryBOT
#

@dark wharf :white_check_mark: Your eval job has completed with return code 0.

TwUL>**(Lwi
dark wharf
#

indeed it does :)

#

so that's 1 char shorter than the * method

#

!e

import sys,random as r
exec('print(chr(r.randint(33,127)),end="");'*int(12))
night quarryBOT
#

@dark wharf :white_check_mark: Your eval job has completed with return code 0.

|1&0/;H...+b
dark wharf
#

Alright ima call this one a day

severe canyon
#
import sys,random as r
exec('print(end=chr(r.randint(33,127)));'*int(sys.argv[1]))

you can put the random as the argument for the "end"

grave rover
#

another fun one:

#

!e ```py
import sys,random as r
n=int(sys.argv[1])
print('%c'*n%(*r.sample(range(33,127),n),))

night quarryBOT
#

@grave rover :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | IndexError: list index out of range
grave rover
#

oh right

severe canyon
#

errors are fun

grave rover
#

!e ```py
import sys,random as r
n=12
print('%c'*n%(*r.sample(range(33,127),n),))

night quarryBOT
#

@grave rover :white_check_mark: Your eval job has completed with return code 0.

hr,Zf"WH3.b&
grave rover
#

sadly slightly longer since I have to use sys.argv twice

severe canyon
#

cool solution

sick hound
silver olive
#

now this is the channel i came for

plucky bane
#

@silver olive It's a good feeling right haha.

silver olive
#

I look forward to getting confused and making incorrect statements and assumptions, then feverishly editing my hasty comments

severe canyon
#

spit your wisdom

rapid sparrow
#

what is this rubbish error

#
(lambda: _:="".join("wis  dom".split()), print(_))[0])()```
#

sounds arbitrary

severe canyon
#

why would you need a lambda function here?

rapid sparrow
#

now I got it I think

#

!e

(lambda: ((_:="".join("wis  dom".split())), print(_))[0])()
night quarryBOT
#

@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.

wisdom
rapid sparrow
#

just needed parens around it

rapid sparrow
severe canyon
#

ยฏ_(ใƒ„)_/ยฏ

carmine sun
#

!e

_ = lambda _: _ -_
print(_(_)(1))
night quarryBOT
#

@carmine sun :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 |   File "<string>", line 1, in <lambda>
004 | TypeError: unsupported operand type(s) for -: 'function' and 'function'
carmine sun
#

!e
(lambda x: x() - 1)(x)

night quarryBOT
#

@carmine sun :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name 'x' is not defined
carmine sun
#

!e
(lambda x: x() - 1)(1)

night quarryBOT
#

@carmine sun :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 |   File "<string>", line 1, in <lambda>
004 | TypeError: 'int' object is not callable
carmine sun
#

!e
x = (lambda x: x() - 1)
x(x)

night quarryBOT
#

@carmine sun :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 |   File "<string>", line 1, in <lambda>
004 | TypeError: <lambda>() missing 1 required positional argument: 'x'
sick hound
#
While True:
  print("gey")
#

!e

night quarryBOT
#
Command Help

!eval [code]
Can also use: e

*Run Python code and get the results.

This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.

We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*

sick hound
#

!e While True:
print("gey")

#

oh i forgot shit i need to stop smoking

#

!e While(0):
print("gey")

wraith burrow
#

!e ```py
open('xd.txt', 'w+')

night quarryBOT
#

@wraith burrow :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | OSError: [Errno 30] Read-only file system: 'xd.txt'
wraith burrow
#

!e ```py
while True:
print('baka')

night quarryBOT
#

@wraith burrow :x: Your eval job timed out or ran out of memory.

001 | baka
002 | baka
003 | baka
004 | baka
005 | baka
006 | baka
007 | baka
008 | baka
009 | baka
010 | baka
011 | baka
... (truncated - too many lines)

Full output: too long to upload

prisma coral
#

@sick hound @wraith burrow Unless your bot commands are relevant to the channel or topic currently being discussed, please keep them to the #bot-commands channel ๐Ÿ

astral rover
#

whats the best way to get "this" from inside get_var?

this = get_var()

i feel like sys._getframe(1).f_code.co_names[-1] isnt very good

rugged sparrow
#

you can get the co_code of the upper frame and look for the STORE_* op to get the index

astral rover
#

so im looking for store name and the thing to the side of the dis.dis is the index in co_names?

rapid sparrow
#

it's the index yeah

astral rover
#

how do i get the current position in the byte code?

#

dis.get_instructions(code, first_line=frame.f_lineno) doing this doesnt seem to actually offset the instructions

maiden vapor
#

Hi, since i don't know where is the correct spot for my question, i will try here.

I have Python x64 installed in my machine (w11) I would like tat the script/program run under x86, it is that possible? giving a command or something in the running command?

eager sphinx
#

!e

encoded_sum = 2578547247865907847361716367385281948475715334894

decoded = [(num := encoded_sum >> ((160 - i) * 7)) - (num >> 7 << 7) for i in range(161)]

print("".join(map(chr, reversed(decoded))))
night quarryBOT
#

@eager sphinx :white_check_mark: Your eval job has completed with return code 0.

never gonna give you up๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ
eager sphinx
#

@gritty mesa

gritty mesa
#

Excellent

chilly imp
shut trail
#

It's for "code golfing" (trying to make your code as short as possible), Python VM languages, obfuscation, and a lot more "weird things in Python"

sick hound
chilly imp
#

Lol

sick hound
#

enter this channel and you will come out being a different man

dense nova
#
data=[(int(input("Enter roll number: ")),input("Enter name: "),int(input("Enter marks: ")))for _ in range(int(input("How many students?")))];print(f"Roll no: {roll_no}\nName: {(names:=[value[1]for value in data])[roll_nos.index(roll_no)]}\nMarks: {(marks:=[value[2]for value in data])[roll_nos.index(roll_no)]}" if (roll_no:=int(input("Enter a roll number to find: "))) in (roll_nos:=[value[0]for value in data]) else "Not found")
#

python wont accept my walrus for a list comp for no reason

#

so i have to take an extra line to declare a variable ๐Ÿ™„

dense nova
sick hound
dense nova
#

ddang

sick hound
#

wanna see cool stuff ive done xd

dense nova
#

i thought you just enter the server and kapow

dense nova
sick hound
#

!e ```py
(lambda self=[:=((([]==[]))+(([]==[]))) ,
:=(
)*((([]==[]))+(([]==[])))**
//__ , :=()** ,
_____:=((())+())**((([]==[]))+(([]==[])))+(([]==[]))+(([]==[]))+(([]==[]))+(([]==[])) ,
________:=(()) , :=(()) , :=(([]==[]))+() , :=(())+ ,
______ := chr((((
)))*((((
))))**(
)+(
)//((
))) , [[((
)+(((
)))//(
)-(())+(()**()**(()))) ,
____________:=()+((()))//(
)-((
))+(()**()**(())) ,
_________________ := ((((((((((((((_________________))))))))))))))+
__ , ((),~____)]
for ___ in range(
) if ((_)) !=[(([]==[]))-()]]][]: eval(type(None).bool.doc))()

import fishhook
@fishhook.hook(int)
def repr(self):
stuff = {v: k for k,v in globals().items() if isinstance(v,int) and k.startswith('')} | {1:''}
x = self
nums = []
for elem in sorted(stuff.keys(),reverse=True):
while x>=elem:
nums.append(stuff[elem])
x-=elem
return ','.join(nums)

MESSAGE = 'hello'
slist = []
slist.append(MESSAGE)
x = 0
for i in range(len(MESSAGE)):
print(ord(slist[0][x]))
x += 1

night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

001 | _______________________,____,____,__
002 | _______________________,____,____,_
003 | _______________________,____,____,_______,_____________,_
004 | _______________________,____,____,_______,_____________,_
005 | _______________________,____,____,_______,_______,_
dense nova
#

woah

sick hound
#

try decode the message

#

tip: its actually hello

dense nova
dense nova
sick hound
#

but you can

sick hound
dense nova
#

i'll pass

sick hound
#

i got help from 2 users to make it

#

sharing ideas and all

dense nova
# sick hound sure

this guy comes up to me, asks me to do his homework for him and im like "sure" but im thinking i'll troll him

sick hound
#

if you see cheeki or greyblue92 say hi

sick hound
#

use truthy and ascii to do some funny bullshit

dense nova
#

so the question was the user enters the info of an x number of students including roll no, name and marks, then make it so that the user can ask for a roll number and the program will display that students info, if the student exists

sick hound
#

{}=={} and []==[] are truthy and return 1

sick hound
#

pretty epic troll moment

dense nova
#

i helped him for 1 question

#

then turned evil

#
print(' '.join(map(str,sorted(list(set(map(int,input("Enter numbers seperated by commas: ").split(','))))))));data=[(int(input("Enter roll number: ")),input("Enter name: "),int(input("Enter marks: ")))for _ in range(int(input("How many students?")))];print(f"Roll no: {roll_no}\nName: {(names:=[value[1]for value in data])[roll_nos.index(roll_no)]}\nMarks: {(marks:=[value[2]for value in data])[roll_nos.index(roll_no)]}" if (roll_no:=int(input("Enter a roll number to find: "))) in (roll_nos:=[value[0]for value in data]) else "Not found");print("The numbers in the list, the largest number and the smallest number are:  (" + " ".join(list(map(str,(numbers:=[int(input("Enter a number: "))for i in range(int(input("Enter number of numbers: ")))]))))+f"), {max(numbers)}, {min(numbers)}")
``` 3 of his problems in 4 lines
#

but i joined the lines with semicolons

sick hound
#

lol

#

wow

sick hound
#
while 1:from turtle import*;from random import*;penup();speed(0);a=400;[lambda:goto(xcor()/2,(ycor()+a)/2),lambda:goto((xcor()+a)/2,(ycor()-a)/2),lambda:goto((xcor()-a)/2,(ycor()-a)/2)][randint(0,2)]();stamp()
#

one-liner that draws a sierpinski triangle

eager sphinx
#

@gritty mesa it serves as a compression algorithm lmao

#

!e

import math

def encode(s: str,  bytesize=8):
    return sum((ord(c) + 1) << (i * bytesize) for i, c in enumerate(s))

def decode(encoded_sum: int, bytesize=8):
    bit_requirement = math.floor(math.log2(encoded_sum)) + 1
    length = math.ceil(bit_requirement / bytesize)
    decoded = [
                (num := encoded_sum >> ((length - i - 1) * bytesize)) - (num >> bytesize << bytesize) - 1 
                for i in range(length)
    ]
    return "".join(map(chr, reversed(decoded)))

string = "never gonna give you up"
encoded = encode(string)
print(f"Encoded sum: {encoded}")
print(f"Number of bits needed to represent encoded sum: {math.floor(math.log2(encoded)) + 1}")
print(f"Number of bits needed to represent regular string: {len(string) * 8}")
night quarryBOT
#

@eager sphinx :white_check_mark: Your eval job has completed with return code 0.

001 | Encoded sum: 10867447704549097381156797386404350535238504898658526831
002 | Number of bits needed to represent encoded sum: 183
003 | Number of bits needed to represent regular string: 184
eager sphinx
#

c o m p r e s s i o n

#

(this is a generalized version of what i sent yesterday btw)

sly root
#

Hello, is there a method to hook type annotation?
I want to create immutable variable using class (constants)

from typing import (
    Any,
    TypeVar, 
    Generic,
)

T = TypeVar('T')


class Const(Generic[T]):
  def __init__(self):
    self.value: Any = None


var: Const[str] = "hello world"

var = "hello?" #AttributeError
#

I want to class specified as type be executed.

astral rover
#

yes this is totally possible but why would you do this over just using Final?

#

anyways assuming you only want this to work literals (any value would be slightly harder) you need to implement __class_getitem__ then have that look at the byte code and see what its being assigned to, then replace the current module in sys.modules with a new class with a __setattr__ method that would detect if the value was annotated as a constant

vague cairn
# astral rover whats the best way to get "this" from inside get_var? ```py this = get_var() ```...

I do it like this:

def code_slice(depth_or_frame=1, offset_or_slice=0, absolute=False):
    """Retrives the bytes from a given stackframe and slices
    it on the currently executing FUNCTION_CALL
    if absolute is False(default) offset=0 refers to f_lasti
    positive integers refer to after f_lasti: +2 == next instruction
    negative integers rever to before f_lasti
    slices are also supported. You probably always want multiples of 2
    """
    if isinstance(depth_or_frame, int):
        f = sys._getframe(depth_or_frame+1)
    elif hasattr(depth_or_frame, 'f_code') and hasattr(depth_or_frame, 'f_lasti'):#means isinstance(depth_or_frame, frame) except frame isn't defined locally.
        f = depth_or_frame
    #elif absolute and (hasattr(depth_or_frame, 'co_code' or hasattr(depth_or_frame, '__code__')):
        #we could adjust this to take a function or code object not only a frame object, but...
        #not right now.
    else:
        raise TypeError(f'expected depth to be int or stackframe, got {type(depth_or_frame)}:{depth_or_frame}')
                    
    if not absolute:
        if isinstance(offset_or_slice,int):
            ti = f.f_lasti + offset_or_slice#set offset
            return f.f_code.co_code[ti:ti+2]
        elif isinstance(offset_or_slice, slice):
            ti = f.f_lasti
            newslice = slice( (offset_or_slice.start or 0) + ti,
                              (offset_or_slice.stop or 0) + ti,
                              (offset_or_slice.step or 1)
                              )
            return f.f_code.co_code[newslice]
        else:
            raise TypeError('expected index or slice')
    
    if isinstance(offset_or_slice,int):
        ti = offset_or_slice#set offset
        return f.f_code.co_code[ti:ti+1]
    elif isinstance(offset_or_slice, slice):
        return f.f_code.co_code[slice(*offset_or_slice.indices(len(f.f_code.co_code)))]
    else:
        raise TypeError('expected index or slice')```
astral rover
#
            on_line = False
            return_next = False
            for instruction in dis.get_instructions(frame.f_code):
                if return_next and instruction.opname == "STORE_NAME":
                    break
                elif instruction.starts_line == frame.f_lineno:
                    on_line = True
                elif on_line and instruction.opname == "BINARY_SUBSCR":
                    return_next = True
            name = instruction.argval
```is what i have (this is for a __class_getitem__)
#

this is among other horrific things to make TypeAliases have access to there assigned name

vague cairn
#

is this so you can say things like:

a, b = destructure(d)
assert a==1234 and b is None```
astral rover
#
Inventory: TypeAlias = BaseInventory[Item]  # necessitated by TypeVar not currently supporting defaults```its for this to have  a repr with Inventory and not BaseInventory
#

and play nicely with typing

vague cairn
#

Ah, so you want your class to return different types based on the type of the variable it's going to get assigned to later.

grave rover
#

I remember a way to do this very easily, lemme try to find it

#

nvm I just had another cursed snippet I used

#
def var_length(func):
    @wraps(func)
    def inner(*args, **kwargs):
        code = stack()[1].frame.f_code
        pos = stack()[1].frame.f_lasti
        ops = list(zip(code.co_code[::2], code.co_code[1::2]))
        op = ops[int(pos / 2)+1]
        try:
            effect = stack_effect(op[0], op[1])
        except ValueError:
            try:
                effect = stack_effect(op[0])
            except ValueError:
                effect = 1
        if op[0] == opmap["UNPACK_SEQUENCE"]:
            nargs = op[1]
        elif effect < 0:
            nargs = -effect
        else:
            nargs = 0
        return func(nargs, *args, **kwargs)
    return inner

# test cases
def main():
    @var_length
    def zero(n):
        if n > 1:
            return [0] * n
        if n == 1:
            return 0


    a = zero()
    b, c = zero()
    d, e, f = zero()
    assert a is b is c is d is e is f is 0

    # ...
#

I wonder if it's somewhat doable with pyasm

vague cairn
#

I don't know nearly enough about type annotations. but I can give you an implementation of destructure() above if you want it.

sly root
astral rover
#

if you want to make it immutable just use the read only version of the class with final

vague cairn
#

it seems to me that at the module level, foo: bar = this["baz"]
compiles to:

             66 LOAD_CONST               5 ('baz')
             68 BINARY_SUBSCR
             70 STORE_NAME              10 (foo)
             72 LOAD_NAME               11 (bar)
             74 LOAD_NAME               12 (__annotations__)
             76 LOAD_CONST               6 ('foo')
             78 STORE_SUBSCR```
but inside a function it compiles to:
```           6 LOAD_FAST                0 (this)
              8 LOAD_CONST               1 ('baz')
             10 BINARY_SUBSCR
             12 STORE_FAST               1 (foo)
             14 LOAD_CONST               0 (None)
             16 RETURN_VALUE```

Which is less helpful to your purposes.
earnest wing
#
(1).bit_length
class Evil:
  def __eq__(self, other):
    other['bit_length'] = 42
int.__dict__ == Evil()
print((1).bit_length)

prints <built-in method write of _io.TextIOWrapper object at 0x10a895080> on my machine lol

wet mountain
#

Hello

#

I need help with something that I am working on a machine learning assignment in creating an algorithm that will detect brain tumors based on brain data tumor data sets. This is an assignment that is asked by my professor but I donโ€™t have experience with coding.

These are the steps I already complete which is

(1) Import the dataset into a fresh Google Collab project
(2) Split the dataset into training / testing / validation sets (thursday)

But i still need help with
(3) Defining my classification model(s). You would probably want to try a few different models here.ย ย You can either build your own convolution neural network (layer by layer) in tensorflow and train it from scratch, or you can modify an existing pre-trained network like VGG19, alter it to better suit our binary classification needs, and retrain it on the dataset.
(4) Train you model(s) and evaluate

vague cairn
rugged sparrow
night quarryBOT
#

Objects/descrobject.c lines 1186 to 1190

static PyObject *
mappingproxy_richcompare(mappingproxyobject *v, PyObject *w, int op)
{
    return PyObject_RichCompare(v->mapping, w, op);
}```
rugged sparrow
night quarryBOT
#

Objects/dictobject.c lines 2886 to 2894

static PyObject *
dict_richcompare(PyObject *v, PyObject *w, int op)
{
    int cmp;
    PyObject *res;

    if (!PyDict_Check(v) || !PyDict_Check(w)) {
        res = Py_NotImplemented;
    }```
rugged sparrow
night quarryBOT
#

Objects/object.c lines 695 to 706

if ((f = Py_TYPE(v)->tp_richcompare) != NULL) {
    res = (*f)(v, w, op);
    if (res != Py_NotImplemented)
        return res;
    Py_DECREF(res);
}
if (!checked_reverse_op && (f = Py_TYPE(w)->tp_richcompare) != NULL) {
    res = (*f)(w, v, _Py_SwappedOp[op]);
    if (res != Py_NotImplemented)
        return res;
    Py_DECREF(res);
}```
rugged sparrow
#

funny thing is that this relies on the first check failing so ```py

class Evil:
... def eq(self, other):
... other['bit_length'] = 42
...
Evil() == int.dict
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in eq
TypeError: 'mappingproxy' object does not support item assignment

marsh void
#

in PyPy you can't even modify the wrapped mutable dictionary afaik

prisma coral
#

@rugged sparrow @earnest wing iirc this was raised as a bug on bpo a while back

#

BPO issue 43838

sick hound
#

!e ```py
from typing import Any, Callable, Generator, Iterator
from types import ModuleType
import types

a: int = 5
b: float = 5.0
c: complex = 5j
d: bool = True
e: str = "lol"
f: list[int] = [5, 6]
g: tuple[str, str] = ("hello", "world")
h: dict[str, int] = {"hi": 5}
i: set[int] = {1, 2, 3}

j: range = range(5)
k: Iterator = iter([i for i in range(5)])
l: Generator = (i for i in range(5))
m: Callable = lambda: None
n: ModuleType = types

v: type = type

x: list[Any] = [a, b, c, d, e, f, g, h, i, j, k, l, m, n, v]
y: list[tuple[Any, Any]] = [(type(i).name, i) for i in x]
z: list[str]= [f"type: {i[0].ljust(13)} -> {i[1]}" for i in y]

print("\n".join(z))

night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

001 | type: int           -> 5
002 | type: float         -> 5.0
003 | type: complex       -> 5j
004 | type: bool          -> True
005 | type: str           -> lol
006 | type: list          -> [5, 6]
007 | type: tuple         -> ('hello', 'world')
008 | type: dict          -> {'hi': 5}
009 | type: set           -> {1, 2, 3}
010 | type: range         -> range(0, 5)
011 | type: list_iterator -> <list_iterator object at 0x7fe45727fdc0>
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/salijihata.txt?noredirect

tranquil yarrow
#

hi! could we say that a is b is equivalent to id(a) == id(b)?
taking into consideration that a is b compares place in memory that are occupied by objects referenced by a and b, isn't it the same as comparing their id()?

#

so, in other words, my question would be: can I be sure that id() always returns an object's place in memory... hm.

#

stretching it hard, I could say that id() provides a pointer :D

#

but without the whole pointer API that would make it a real pointer

tranquil yarrow
sly root
#

!e ```py
from typing import (
Any,
TypeVar,
Generic,
Optional,
Callable,
Mapping,
get_args,
)

class TypeMismatch(Exception):
def init(self, message):
super().init(message)

class Fn(Callable):
def init(self, func: Callable):
self.__func = func

def call(self, *args: tuple, **kwargs: dict):
self.__orig = self.orig_class
self.__type = self.__orig.args
self.__rtype = self.__type[-1]

self.__args, self.__kwargs = args, kwargs

for arg in self.__args:
  if not type(arg) == (type_hint := self.__type[(arg_index := self.__args.index(arg))]):
    raise TypeError("Parameter of function %s, at index %s and of type %s cannot be converted to specified type %s" % (
      self.__func.__name__,
      arg_index,
      (param_type := type(arg)),
      (required_type := type_hint),
    )) \
    from TypeMismatch("Cannot convert %s to %s" % (param_type, required_type))
for kwarg in self.__kwargs:
  if not type(self.__kwargs[kwarg]) == (type_hint := self.__type[(kwarg_index := get_index(self.__kwargs, kwarg))]):
    raise TypeError("Parameter of function %s, at index %s and of type %s cannot be converted to specified type %s" % (
      self.__func.__name__,
      kwarg_index,
      (param_type := type(kwarg)),
      (required_type := type_hint),
    )) \
    from TypeMismatch("Cannot convert %s to %s" % (required_type, param_type))
fout = self.__func(*args, **kwargs)
match type(fout):
  case self.__rtype:
    return fout
  case _:
    raise TypeError("Returned value of type %s cannot be converted to specified return type %s" %(
      (returned_type:= type(fout)),
      (return_type := self.__type[-1]),
    ))\
    from TypeMismatch("Cannot convert %s to %s" % (returned_type, return_type))

(func := Fn[[int, int], bool](lambda a,b:not not a+b))
print(func(8, 8))```

night quarryBOT
#

@sly root :white_check_mark: Your eval job has completed with return code 0.

True
sly root
#

!e ```py
from typing import (
Any,
TypeVar,
Generic,
Optional,
Callable,
Mapping,
get_args,
)

T = TypeVar("T")

class TypeMismatch(Exception):
def init(self, message):
super().init(message)

class Var(Generic[T]):
def init(self, value: Any):
self.__orig = self.orig_class
self.__type = self.__orig.args[0]

match type(value):
  case self.__type:
    self.__val = self.__type(value)
  case _:
    raise TypeError("Value of type %s cannot be assigned to variable of type %s" % (
      (value_type := type(value)), 
      (variable_type := self.__type)
    )) \
    from TypeMismatch("Cannot convert %s to %s" % (value_type, variable_type))

@property
def type(self): return self.__type
def type(self): return self.__type

@property
def value(self): return self.__val
def repr(self): return str(self.__val)

(a := Varint)
print(type(a), a.type, a, a.value)```

night quarryBOT
#

@sly root :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 40, in <module>
003 |   File "/usr/local/lib/python3.10/typing.py", line 943, in __call__
004 |     result = self.__origin__(*args, **kwargs)
005 |   File "<string>", line 19, in __init__
006 | AttributeError: 'Var' object has no attribute '__orig_class__'. Did you mean: '__orig_bases__'?
prisma coral
#

@tranquil yarrow A is B is equivalent to id(A) == id(B) by definition. id returns the "identity" of an object (a unique number for the object) and is compares identities, hence they are the equivalent.

However, the fact that CPython uses memory addresses for the identities of object is just an implementation detailโ€”PyPy (another Python implementation) does not, for example.

tranquil yarrow
#

@prisma coral thanks a lot! i dream of becoming such an expert one day...

prisma coral
tranquil yarrow
#

yeaah

#

i even did it

#

look :D

#

(ok, wait a moment, i will rewrite it from my memory)

#

but it worked as a pointer

#

ctypes is genuine btw

#

@prisma coral yeah, i got it

#
from ctypes import cast, py_object, pointer

class Pointer(int):    
    def __new__(cls, pointed_obj):
        return int.__new__(cls, id(pointed_obj))
    def __call__(self):
        return cast(self, py_object).value

my_object = object()
my_pointer = Pointer(my_object)
assert my_pointer() is my_object
assert my_pointer == id(my_object)
prisma coral
#

nice

tranquil yarrow
#

using ctypes.cast is also a funny thing when you invent the number xD

#

iirc ctypes.cast(0, ctypes.py_object) crashes the program

#

naah

#

it was ctypes.cast(1, ctypes.py_object)

#

ctypes.cast(0, ctypes.py_object) returns an elegant py_object(<NULL>)

#

so interesting, isn't it

#

:D

#

yeah, unicode

#

but it handles it correctly i think

#

those are just weak warnings

hard spoke
#

which are false - it runs perfectly fine.

tranquil yarrow
#

looks again

#

and where is eft_copy declared?

#

because, as PyCharm, I also can't see eft_copy around

#

but I can see left_copy :P

#

i'm talking about this:

#

the first character, in the assignment expression of left_copy at the top

#

became the last character there

#

am I right?

#

actually everywhere you are referring eft_copy, this name error appears

#

eft_copyl, in fact.

tranquil yarrow
hard spoke
tranquil yarrow
#

it's the first line

#

but it's left_copy, not eft_copyl

#

and in the following lines you are referring to eft_copyl instead of left_copy

hard spoke
#

my guess is that there's a right-to-left segment in that word or something like that

#

since:

  1. it runs, I checked that
  2. my program only replaces individual chars and doesn't change the order
tranquil yarrow
#

and in real it turns out to be the same

#

but PyCharm doesn't accept it as Python does

hard spoke
#

@tranquil yarrowHere's the file (when I try pasting it as a message, it gets corrupted I think)

tranquil yarrow
#

yeah, it got corrupted

#

anyway, this script is beautiful

hard spoke
#

the file should be okay if you download it

tranquil yarrow
#

keep up the calligraphy <3

prisma coral
hard spoke
#

hmm, hold on

#

a bit complicated, since currently it doesn't quite produce working code on every run

tranquil yarrow
#

heh

carmine sun
#

!e
print((lambda: ([]==[]+[]==[])+lambda: []==[])())

night quarryBOT
#

@carmine sun :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     print((lambda: ([]==[]+[]==[])+lambda: []==[])())
003 |                                    ^^^^^^
004 | SyntaxError: invalid syntax
carmine sun
#

!e
print([]==[])

night quarryBOT
#

@carmine sun :white_check_mark: Your eval job has completed with return code 0.

True
carmine sun
#

!e
print([]==[]+[]==[])

night quarryBOT
#

@carmine sun :white_check_mark: Your eval job has completed with return code 0.

True
tough ruin
#

how would i reverse a string?
for example, hello turning into llohe
like reversing 2 digits at a time

sick hound
#

idk and probably not the best place to ask.

prisma coral
soft void
#
def ii(j):
    print(j*2,__name__)

print(__name__)
ii(2)```

in this both __name__ give __main__ but i saw in my book that only top lvl statements give __main__ not inside function
tranquil yarrow
#

if-else inline statements that may be heavier for memory
!e ```py
yes = 'YES'
no = 'NO'
condition = True
result = (no, yes)[condition]

#

ok, i'm a noob of !e

#

anyway, using tuple (might also be frozenset) of alternatives is essential

tranquil yarrow
#

and it might be heavier, because if-else statement does not "eval" both endpoints expressions

#

but only one, depending on the condition

tranquil yarrow
tranquil yarrow
#

yes() if condition else no()

#

then it would be replaced with
(no, yes)[condition]()

#

what.

#

uhm, okay

tranquil yarrow
#

then it would be replaced with

#

(yes, lambda: NO)[condition]()

#

and so on

prisma coral
steep mural
#

is there a way to represent 1 << 0 if x else 0 using only bitwise operators?

rugged sparrow
#

i dont think so unless x is an int

steep mural
#

x is a boolean

rugged sparrow
#

so you want to convert the bool to an int?

steep mural
#
a = 1 << 0

if x:
    a |= 1 << 1
#

I just want a shorter form of this

rugged sparrow
#
a = 1 | (2)*x
``` if x is a bool or an int (1 or 0) that should work
astral rover
#

<@&831776746206265384> ^^^

fleet bridge
#

~~x

night quarryBOT
#

@vague cairn :white_check_mark: Your eval job has completed with return code 0.

4321
vague cairn
#

!e

#this is a more standard idiom for reversing strings.
print(''.join(reversed('1234')))```
night quarryBOT
#

@vague cairn :white_check_mark: Your eval job has completed with return code 0.

4321
past plank
fleet bridge
#

is it intended behaviour?

#

why i can import some folders as namespace packages?

#
>>> bin.__spec__
ModuleSpec(name='bin', loader=<_frozen_importlib_external._NamespaceLoader object at 0x000002778D0E47F0>, submodule_search_locations=_NamespacePath(['D:\\Programs\\Python\\310\\bin', 'D:\\Programs\\Python\\310\\bin']))
night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

001 | <string>:16: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | <string>:19: SyntaxWarning: "is" with a literal. Did you mean "=="?
003 | <string>:27: SyntaxWarning: "is" with a literal. Did you mean "=="?
004 | <string>:27: SyntaxWarning: "is" with a literal. Did you mean "=="?
005 | <string>:27: SyntaxWarning: "is" with a literal. Did you mean "=="?
006 | <string>:27: SyntaxWarning: "is" with a literal. Did you mean "=="?
007 | <string>:27: SyntaxWarning: "is" with a literal. Did you mean "=="?
008 | <string>:27: SyntaxWarning: "is" with a literal. Did you mean "=="?
009 | [3, -1, 4] 7 9
#

@sick hound :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 7, in <module>
003 |   File "<string>", line 6, in a
004 |   File "<string>", line 6, in <listcomp>
005 | ValueError: too many values to unpack (expected 3)
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

[3, -1, 4] 7 9
maiden river
#

or we can try make a Transpiler for our all new PyF##k

#

can you share the general idea how this is working : )

is *10% important and how do we go about writing the starting brackets, does it depend on the length of our "code" ?
like print(chr(67)) has 14 chars

and i guess different nums are comma separated

maiden river
#

!e

#print( *b"print('hi')" )

code = """print('hi')"""

X = len(code)

exec( '%c'*X%(112,114,105,110,116,40,39,104,105,39,41))

night quarryBOT
#

@maiden river :white_check_mark: Your eval job has completed with return code 0.

hi
maiden river
#

now just gotta make a char to ()==() converter

fleet bridge
#

here

maiden river
#

for x = 10
your : ((([]==[])*(([]==[])+([]==[]))**(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[]))**([]==[])

mine: ((()==())+(()==()))*((()==())+(()==()))*((()==())+(()==()))*+(()==())+(()==())+(()==())

night quarryBOT
maiden river
#

!e

exec('%c'*13%(((([]==[])*(([]==[])+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[])),((((([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[]))**(([]==[])*(([]==[])+([]==[]))*(([]==[])+([]==[]))),((((((([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[]))**((([]==[])+([]==[]))+([]==[])))+([]==[]))*(([]==[])+([]==[])),(((((([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[]))**((([]==[])+([]==[]))+([]==[])))+([]==[]),((((((((([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[])),((((((([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[]))*(([]==[])+([]==[])),((([]==[])*(([]==[])+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[]))**((([]==[])+([]==[]))+([]==[])),((((([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[]))**((([]==[])+([]==[]))+([]==[])))+([]==[]))*(([]==[])+([]==[])),((((([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[]))**((([]==[])+([]==[]))+([]==[])))+([]==[]))*(([]==[])+([]==[])),(((((((([]==[])*(([]==[])+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[])))+([]==[]),(((((((([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[])))+([]==[]),(((([]==[])*(([]==[])+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[]))**((([]==[])+([]==[]))+([]==[])))+([]==[]),((([]==[])*(([]==[])+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[]))))
night quarryBOT
#

@maiden river :white_check_mark: Your eval job has completed with return code 0.

3.142857142857143
maiden river
#

Here's the Transpiler, you can now convert your normal code into PyF### ; )

#

Read & write functionality can be added to convert other files (thx @fleet bridge for the int2eso converter)
or you can write code in the code variable

grave rover
#

oh I made one of those for my obfuscator

#

here's tic tac toe but obfuscated :)

night quarryBOT
#

Hey @maiden river!

It looks like you tried to attach file type(s) that we do not allow (.zip). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.

Feel free to ask in #community-meta if you think this is a mistake.

maiden river
#

converted into
เฅ‘

grave rover
#

now do fibonacci

#

here's mine: ```py

Generated by Mart Obfuscator

a=lambda b:b<(()<=())<<([]==[])and()==()or a(b-(()==()))+a(b-((()==())<<([]==[])))
based onpy
def fibonacci(n):
if n < 2:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)

maiden river
grave rover
#

yeah but exec means imports are wacky

#

it also means that if you just do a regex replace with 1s it becomes pretty easy to figure out with some in-place calculation resolver tools

maiden river
#

yea this ain't really about hiding code
it's sort of a JSf..k equivalent for python

grave rover
#

It's more fun if not everything is ()==() btw

rapid sparrow
#

where can I see the files at?

night quarryBOT
#

@sick hound :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 7, in <module>
003 |   File "<string>", line 6, in a
004 |   File "<string>", line 6, in <listcomp>
005 | ValueError: too many values to unpack (expected 3)
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

[3, -1, 4] 7 9
grave rover
#

old code and really messy but it more or less works

#

loads of stuff not implemented and you need to kinda whack your code around

#

but it sort of works

maiden vine
#

Hey all!

#

I thought y'all might like to see this singleton class I wrote (using cython)

#

New instances can't be created by calling either Singleton.__new__() or object.__new__(Singleton)

#

The class itself must be called

#

Also, singleton classes inheriting from it can be configured to either throw an error upon subsequent calls beyond the first, or not

#

And, can be configured to throw an error upon subclassing, or not

#
NoSubclassSingleton(Singleton, fossilized=True):
  """cannot be subclassed"""
#
ErrorOnSubsequent(Singleton, thunderous=True):
  """no instances beyond the first"""
#

???

#

How do you mean?

maiden vine
#

@sick hound ???

maiden river
prisma coral
#

But what you made is really cool!

maiden vine
#

Thanks!

#

It was actually a bit challenging, trying to account for all the edge cases

#

But I think its well and truly impossible to make secondary instances without the use of ctypes, or using the object model directly otherwise

#

I wish I didn't have to use a metaclass, but I don't think there is any other way of controlling instance creation of cdef classes

#

Not without factory function at least

prisma coral
#

Ok I've got a challenge for y'allโ€”how many oneliners which create a working console.log (the JavaScript equivalent of print) can you find? Here's some examples to start you off:

console = type("console", (object,), {"log": print})
console = __import__("collections").namedtuple("console", ["log"])(print)
(console := __builtins__).log = print

All of these will result in being able to use console.log as an alias for print. There's only two rules: a) it has to be runnable through !eval and b) you have to use a different method for each oneliner. Obfuscating a previous oneliner doesn't count ๐Ÿ™‚

trail quest
#

i did a thing

>>> def square(x):
...     return x * x
...
>>> Iter(3) @ square @ range @ foreach(str) @ ', '.join @ print
0, 1, 2, 3, 4, 5, 6, 7, 8
#

let's pipe in python

finite blaze
#

i see @ for the first time

earnest wing
#

we need more combinators

rapid sparrow
earnest wing
#

usually I see function composition being right associative

trail quest
#

Sort of like piping in bash, it makes it clearer to see in what order stuff is actually happening IMO

earnest wing
#

maybe | then :>

shut trail
#

!e
setattr(type("console", (object,), {}), "log", print)

night quarryBOT
#

@shut trail :warning: Your eval job has completed with return code 0.

[No output]
shut trail
#

!e

setattr((console := type("console", (object,), {})), "log", print)
console.log("hi")
night quarryBOT
#

@shut trail :white_check_mark: Your eval job has completed with return code 0.

hi
shut trail
#

@prisma coral one way ^

viscid nymph
#

You can use an empty tuple instead of (object,) for the second arg of type

#

!e

console=type("",(),{"log":print})

console.log("hi")
night quarryBOT
#

@viscid nymph :white_check_mark: Your eval job has completed with return code 0.

hi
shut trail
#

hmmm, what else

#

!e

console=[(new_type := type("", (), {})), new_type.__dict__["__getattr__"] = lambda attr: print if attr == "log" else None][0]

console.log("hi.")
night quarryBOT
#

@shut trail :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 | AttributeError: type object 'console' has no attribute 'log'
shut trail
#

!e

console=[(new_type := type("", (), {})), (new_type.__dict__["__getattr__"] := lambda attr: print if attr == "log" else None)][0]

console.log("hi.")
night quarryBOT
#

@shut trail :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     console=[(new_type := type("", (), {})), (new_type.__dict__["__getattr__"] := lambda attr: print if attr == "log" else None)][0]
003 |                                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
004 | SyntaxError: cannot use assignment expressions with subscript
shut trail
#

hm

shut trail
#

oh yeah, but can you not create dunder methods by the type way alone?

#

!e

console = type("", (), {"__init__": lambda: print("hi.")})

console()
night quarryBOT
#

@shut trail :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 | TypeError: <lambda>() takes 0 positional arguments but 1 was given
shut trail
#

type(...)

#

brainfart, sorry

golden finch
#

!e

try:
    raise
except Exception as e:
    print(e.__traceback__.tb_frame.f_code.co_consts)
    e.__traceback__.tb_frame.f_code=e.__traceback__.tb_frame.f_code.replace(co_consts=(None,3))

print(2)
night quarryBOT
#

@golden finch :x: Your eval job has completed with return code 1.

001 | ((None, 3), ('co_consts',), None, 2)
002 | Traceback (most recent call last):
003 |   File "<string>", line 2, in <module>
004 | RuntimeError: No active exception to reraise
005 | 
006 | During handling of the above exception, another exception occurred:
007 | 
008 | Traceback (most recent call last):
009 |   File "<string>", line 5, in <module>
010 | AttributeError: readonly attribute
golden finch
#

Obviously, this code does not work for two reasons. Firstly the method is flawed (but this can be fixed trivially). Secondly, and the question I'm asking - how can one modify the co_consts?

maiden river
night quarryBOT
#

@maiden river :white_check_mark: Your eval job has completed with return code 0.

hmm
golden finch
#

I mean I'm familiar with small snippets

rugged sparrow
#

you can modify the co_consts tuple in place

golden finch
#

Okay, how would I do that?

#

(what's the structure of tuples in cpython?)

#

@rugged sparrow you there?

#

memset?

rugged sparrow
#

!e ```py
from ctypes import *

def getTStruct(t):
class T(Structure):
fields = [
('ob_refcnt', c_ssize_t),
('ob_base', py_object),
('ob_size', c_ssize_t),
('ob_items', py_object * len(t))
]
return T.from_address(id(t))

x = (1,2,3)
getTStruct(x).ob_items[0] = 4
print(x)```

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

(4, 2, 3)
golden finch
#

I see

#

so how does that work, and can I do it more simply?

rugged sparrow
#

you could just use raw offsets but that makes the code harder to understand

golden finch
#

I am utterly down to use raw offsets

rugged sparrow
#

ok then

#

!e ```py
from ctypes import *
def setitem(tup, idx, obj):
py_object.from_address(id(tup) + tuple.basicsize + (sizeof(py_object) * idx)).value = obj

x = (0,1,2)
setitem(x, 0, 4)
print(x)```

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

(4, 1, 2)
rugged sparrow
#

@golden finch that works by getting the PyObject at the address (addressof tup + size of tuple header + (index of item * sizeof an item)) and then changing its value

golden finch
#

so uh

#

thinking through that

#

yeah that makes sense

golden finch
#

it appears not to work in this case @rugged sparrow

import dis,ctypes
x,y=0,1
def setitem(tup, idx, obj):
    ctypes.py_object.from_address(id(tup) + tuple.__basicsize__ + (ctypes.sizeof(ctypes.py_object) * idx)).value = obj
try:
    raise
except Exception as e:
    #modify co_consts (how?) to change the 2nd element to y and the 3rd to x+y
    setitem(e.__traceback__.tb_frame.f_code.co_consts,2,(y,x+y))
    #change the LOAD_CONST in the 2nd-last position to JUMP_ABSOLUTE
    mutable_bytes=lambda i:memoryview((ctypes.c_uint8*len(i)).from_address(id(i)+bytes.__basicsize__-1)).cast('B')
    code=mutable_bytes(e.__traceback__.tb_frame.f_code.co_code)
    print(e.__traceback__.tb_frame.f_code.co_consts)
    code[-4]=dis.opmap['JUMP_ABSOLUTE']
print(y)
#

full code includes because I'm not sure where the issue is

rugged sparrow
#

!e py import dis,ctypes x,y=0,1 def setitem(tup, idx, obj): ctypes.py_object.from_address(id(tup) + tuple.__basicsize__ + (ctypes.sizeof(ctypes.py_object) * idx)).value = obj try: raise except Exception as e: #modify co_consts (how?) to change the 2nd element to y and the 3rd to x+y setitem(e.__traceback__.tb_frame.f_code.co_consts,2,(y,x+y)) #change the LOAD_CONST in the 2nd-last position to JUMP_ABSOLUTE mutable_bytes=lambda i:memoryview((ctypes.c_uint8*len(i)).from_address(id(i)+bytes.__basicsize__-1)).cast('B') code=mutable_bytes(e.__traceback__.tb_frame.f_code.co_code) print(e.__traceback__.tb_frame.f_code.co_consts) code[-4]=dis.opmap['JUMP_ABSOLUTE'] print(y)

night quarryBOT
#

@rugged sparrow :x: Your eval job has completed with return code 139 (SIGSEGV).

001 | (0, None, (<class 'ctypes.c_ubyte'>, 166), <code object setitem at 0x7ff4594f1dc0, file "<string>", line 3>, 'setitem', 2, <code object <lambda> at 0x7ff4594f1e70, file "<string>", line 11>, '<lambda>', 'JUMP_ABSOLUTE', -4)
002 | 1
rugged sparrow
#

what is your goal for that code @golden finch

golden finch
#

It should print the fibbonaci numbers

rugged sparrow
#

then it is very wrong

golden finch
#

why?

rugged sparrow
#

changing co_consts will not affect y or x

golden finch
#

but that's the thing

#

it doesn't need to

#

right?

rugged sparrow
#

you would need to write into the frames globals

golden finch
#

look at line 2

#

x,y=(0,1).

rugged sparrow
#

i dont think youre jumping to the right place then

golden finch
#

jumping to 0

#

the jumping works with the setitem call removed

#

the last 4 bytes of a program are basically always LOAD_CONST 0 (None) POP_TOP 0

#

so changing the -4th byte turns that LOAD_CONST into a JUMP_ABSOLUTE

#

in this case I think it is

rugged sparrow
#

setitem(e.__traceback__.tb_frame.f_code.co_consts,2,(y,x+y)) this line sets the third item in co_consts to (y, x + y)

golden finch
#

scratch that there's some other stuff - it's returning a value

rugged sparrow
#

i dont think thats what you want

golden finch
#

that's exactly what I want

#

the third item is that tuple used on line 2

rugged sparrow
#

ok but setitem does not handle refcounts

golden finch
#

the problem is apparently that it's setting it to (<class 'ctypes.c_ubyte'>, 166) instead of (1,1)

rugged sparrow
#

so that new tuple is dealloced

golden finch
#

why do refcounts affect it?

rugged sparrow
#

the tuple (y, x+ y) is dealloced

golden finch
#

ah

#

so how can I fix that?

#

also it does appear to be jumping to 1 not 0

rugged sparrow
#
from ctypes import *
from _ctypes import Py_DECREF, Py_INCREF
def setitem(tup, idx, obj):
  p = py_object.from_address(id(tup) + tuple.__basicsize__ + (sizeof(py_object) * idx))
  Py_DECREF(p.value)
  p.value = obj
  Py_INCREF(p.value)
golden finch
#
import dis,ctypes
x,y=0,1
def setitem(tup, idx, obj):
    ctypes.py_object.from_address(id(tup) + tuple.__basicsize__ + (ctypes.sizeof(ctypes.py_object) * idx)).value = obj
try:
    raise
except Exception as e:
    codeobj=e.__traceback__.tb_frame.f_code
    #modify co_consts (how?) to change the 2nd element to y and the 3rd to x+y
    setitem(codeobj.co_consts,2,(y,x+y))
    #change the LOAD_CONST in the 2nd-last position to JUMP_ABSOLUTE
    mutable_bytes=lambda i:memoryview((ctypes.c_uint8*len(i)).from_address(id(i)+bytes.__basicsize__-1)).cast('B')
    code=mutable_bytes(codeobj.co_code)
    print(e.__traceback__.tb_frame.f_code.co_consts)
    code[-4]=dis.opmap['JUMP_ABSOLUTE']
    code[-3]=0
print(y)

fixed the jump

rugged sparrow
#

try the new setitem

golden finch
rugged sparrow
#

decrease the refcount of the object being repaced and increase the refcount of the object being inserted

golden finch
#

works

#

Ah, thank you

#

:)

rugged sparrow
#

!e ```py
def gadget(magic):
def hack():
def get():
return magic
def set(*value):
nonlocal magic
if value:
magic = value[0]
else:
del magic
return get, set
return hack()

C = gadget.code
gadget.code = C.replace(
co_code=b'\x88' + C.co_code[1:]
)

def setitem(t, i, o):
g, s = gadget(list.setitem)
s(tuple)
i += tuple.basicsize // tuple.itemsize
list.setitem((t,) * (i + 1), i, o)
s(list)

x = (0,1,2)
setitem(x, 0, 3)
print(x)

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

(3, 1, 2)
rugged sparrow
#

@golden finch this setitem is more fun

golden finch
#

those variable names confuse me to no end

gritty saffron
#

!e

night quarryBOT
#
Command Help

!eval [code]
Can also use: e

*Run Python code and get the results.

This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.

We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*

gritty saffron
#

!e myfunc = lambda x, myf: x*(myf(x-1, myf)) if x > 1 else 1
myfunc(10, myfunc)

night quarryBOT
#

@gritty saffron :warning: Your eval job has completed with return code 0.

[No output]
gritty saffron
#

e!
myfunc = lambda x, myf: x*(myf(x-1, myf)) if x > 1 else 1
myfunc(10, myfunc)

night quarryBOT
alpine peak
#
type(cls).__len__ = lambda self: len(self._instances)

I feel really weird about that...

prisma coral
gritty saffron
#

!eval

myfunc = lambda x, myf: x*(myf(x-1, myf)) if x > 1 else 1
myfunc(10, myfunc)
night quarryBOT
#

@gritty saffron :warning: Your eval job has completed with return code 0.

[No output]
gritty saffron
#

Hi, does anybody know why this code does not run?

#

no output?

prisma coral
gritty saffron
#

oh! Thanks!

#

๐Ÿ™‚

#

!eval
!e

myfunc = lambda x, myf: x*(myf(x-1, myf)) if x > 1 else 1
print(myfunc(10, myfunc))
night quarryBOT
#

@gritty saffron :white_check_mark: Your eval job has completed with return code 0.

3628800
gritty saffron
#

Ah! got it! Thanks! ๐Ÿ˜‰

sick hound
#

how past code to this channel?

prisma coral
#

!code

night quarryBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

sick hound
#

thank

alpine peak
#

Honnestly I dont feel very comfortable with this solution .-.

sick hound
#

!e ```py
import random

def wjh():
items = ('map',
'flashlight',
'stick',
'sunglasses',
'sausage',
'Coca-cola')

character = ('John',
             'Sussy')

ok = random.sample(items, 1)
characters = random.sample(character, 1)

print(f'{characters} have a {ok}')

wjh()
wjh()

night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

001 | ['Sussy'] have a ['Coca-cola']
002 | ['Sussy'] have a ['stick']
prisma coral
prisma coral
gritty saffron
#

I am new to python. Had no clue what 'esoteric Python' stands for!

prisma coral
#

The channel description normally has good info

#

Or you can just ask ๐Ÿ

gritty saffron
#

Sorry again! How to view channel description for a channel? ๐Ÿ™‚

#

@prisma coral

prisma coral
#

It should be at the top of the channel, near the channel name iirc (Iโ€™m on mobile atm). On mobile you can click on the channel name at the top

indigo echo
#
def find_delimiter(filename):
    sniffer = csv.Sniffer()
    with open(filename) as fp:
        delimiter = sniffer.sniff(fp.read()).delimiter

    return delimiter```
returns 1space when the delimiter is 8 spaces. Anyone knows why?
rapid sparrow
sleek sphinx
#

!e

print((lambda: (lambda: (lambda: (lambda: (lambda: (lambda: (lambda: 'h')))))))()()()()()()())
#

!e

print((lambda: (lambda: (lambda: (lambda: (lambda: (lambda: (lambda: 'h')))))))()()()()()()())
night quarryBOT
#

@sleek sphinx :white_check_mark: Your eval job has completed with return code 0.

h
sleek sphinx
#

hmm

#

!e

print((lambda _: _())(lambda: 'h'))
night quarryBOT
#

@sleek sphinx :white_check_mark: Your eval job has completed with return code 0.

h
sleek sphinx
#

you can name a function _?

#

!e

def _(_):
    return _()

print(_((lambda: 'h')))
night quarryBOT
#

@sleek sphinx :white_check_mark: Your eval job has completed with return code 0.

h
sleek sphinx
#

ah yes

dire stump
#

here is the code:

night quarryBOT
rapid sparrow
#

cursed? or not cursed?

#

!e

from string import ascii_letters as a
print(
  [a[i*(len(a)>>1)+i:(i+1)*(len(a)>>1)] for i in (0,1)]
)โ€Š
night quarryBOT
#

@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.

['abcdefghijklmnopqrstuvwxyz', 'BCDEFGHIJKLMNOPQRSTUVWXYZ']
rapid sparrow
#

for dividing a list in half

#

oh , no, there's an A missing

#

it's definitely cursed -_-

gritty saffron
grave rover
#
partition = lambda c,n:[*map(lambda i,l=len(c)//n:c[i*l:i*l+l],range(n))]
```if you want it shorter
#

actually wait that doesn't include all letters

#

hmm

#
partition = lambda c,n:[*map(lambda i,l=len(c)/n:c[int(i*l):int((i*l+l))],range(n))]
#

that one works

#

but sadly it has to be wrapped in int() now :(

tranquil yarrow
#

!e ```python
somefloat = .5
print((maybesomeint := somefloat // 1), type(maybesomeint))

night quarryBOT
#

@tranquil yarrow :white_check_mark: Your eval job has completed with return code 0.

0.0 <class 'float'>
tranquil yarrow
#

ok, so it wont be int

#

but hm

#

!e ```py
somefloat = .5
print((maybesomeint := import('math').floor(somefloat // 1)), type(maybesomeint))

#

:)

#

!e ```py
somefloat = .5
print((maybesomeint := (somefloat // 1).floor()), type(maybesomeint))

night quarryBOT
#

@tranquil yarrow :white_check_mark: Your eval job has completed with return code 0.

0 <class 'int'>
grave rover
#

ideally float//int should be converted to int

tranquil yarrow
#

yeah

grave rover
#

I wonder what the rationale behind that is

cloud fossil
#

Since it was an operation between a first and an int

grave rover
#

Well yeah but like

#

It's not like a floor div will ever return a non-integer value

cloud fossil
#

ยฏ\_(ใƒ„)_/ยฏ

astral radish
#

whereas if it returned an int

#

it'd return something

#

or ig it could error too

dense nova
#
print(' '.join(map(str,sorted(list(set(map(int,input("Enter numbers seperated by commas: ").split(','))))))))
data=[(int(input("Enter roll number: ")),input("Enter name: "),int(input("Enter marks: ")))for _ in range(int(input("How many students?")))]
print(f"Roll no: {roll_no}\nName: {(names:=[value[1]for value in data])[roll_nos.index(roll_no)]}\nMarks: {(marks:=[value[2]for value in data])[roll_nos.index(roll_no)]}" if (roll_no:=int(input("Enter a roll number to find: "))) in (roll_nos:=[value[0]for value in data]) else "Not found")
print("The numbers in the list, the largest number and the smallest number are:  (" + " ".join(list(map(str,(numbers:=[int(input("Enter a number: "))for i in range(int(input("Enter number of numbers: ")))]))))+f"), {max(numbers)}, {min(numbers)}")
ASCII_String = lambda strings: {string: sum([ord(letter) for index, letter in enumerate(string) if index % 2 == 1]) for string in strings}
get_duplicates = lambda string: "".join(sorted(["".join(map(str,[k, v])) for k, v in {character: string.count(character) for character in list(set(string))}.items()], key=lambda item: item[0]))
coder = lambda string, offset, encode=True: "".join([chr(ord(letter)+offset) for letter in string]) if encode else "".join([chr(ord(letter)-offset) for letter in string])
``` A few one liners~~~ (and a two liner but we dont talk about that)
dense nova
#

really

#

i love blocks of code

#

just blocks of it

full arch
#

I mean i could understand bits of it, but its cool esoteric

dense nova
#

ok, now i have to go study

#

even though its 12:40 am

#

byee

night quarryBOT
#

:incoming_envelope: :ok_hand: applied mute to @remote niche until <t:1640298859:f> (9 minutes and 59 seconds) (reason: discord_emojis rule: sent 150 emojis in 10s).

sharp kestrel
#

!unmute 768660928257982505 be careful with the emotes

night quarryBOT
#

:incoming_envelope: :ok_hand: pardoned infraction mute for @remote niche.

errant crescent
# dense nova ```py print(' '.join(map(str,sorted(list(set(map(int,input("Enter numbers sepera...

So if I understood correctly, sorry if i am mistaken in some parts the code is squished on the phone, you first print a sorted number list given from the user -

>>> 1,4,5,2,3,10
1, 2, 3, 4, 5, 10

Then you go about doing a whole other thing - making a list of "students" data, getting the amount of students first(N) then asking N times for the students name, marks and roll(?).

Afterwards, you assign the variables name & marks (using walrus operator :=), while in the same time printing the given roll number from the user (using .index() ) IF it does exist in the list/data (else you just say it isn't there)

>>> 1  # 1 students
>>> 0  # roll num
>>> R  # name
>>> A+  # marks

>>> 1  # roll number
Not found

Then, you do another different thing - you print the max & min number from the list, given by the user (again, asking for the length of the list beforehand, and then asking the user N times to input a number) ; then print the numbers, using the max/min methods on the list after assigning it to the variable numbers (and again, by using :=).

>>> 3  # length/"number of numbers"
>>> 1
>>> 2
>>> 4
... are: 4, 1 

Seems like the walrus operation is your friend for making an esoteric code pithink

pallid dawn
#
print(
    " ".join([
        str(inplist := [(float(k) if i % 2 == 0 else k) for i, k in
                        enumerate(input("Expression (format (spaces matter): num op num): ").split(' '))]),
        "evaluates to:",
        str(inplist[0] + inplist[2]) if inplist[1] == "+" else (
            str(inplist[0] - inplist[2]) if inplist[1] == "-" else (
                str(inplist[0] * inplist[2]) if inplist[1] == "*" else (
                    str(inplist[0] / inplist[2]) if inplist[1] == "/" else (
                        str(inplist[0] ** inplist[2]) if inplist[1] == "**" else (
                            str(inplist[0] ** (1/inplist[2])) if inplist[1] == "nrt" else (
                                str(inplist[0] % inplist[2])
                            )
                        )
                    )
                )
            )
        )
    ]).replace('[', '').replace(']', '').replace("'", '').replace(",", '')
)

One line basic calculator does this count as esoteric ๐Ÿ’€

dense nova
sick hound
#
python3 -c "import random as r;a='';exec('a+=chr(r.randint(33,126));'*$1);print(a)"``` I cheated and used bash with it
dense nova
#

it did not occur to me to do that

severe canyon
# dense nova ```py print(' '.join(map(str,sorted(list(set(map(int,input("Enter numbers sepera...

two small golfs:

print(' '.join(map(str,sorted(list(set(map(int,input("Enter numbers seperated by commas: ").split(','))))))))

print(' '.join(map(str,sorted([*set(eval(input("Enter numbers seperated by commas: ")))]))))
coder = lambda string, offset, encode=True: "".join([chr(ord(letter)+offset) for letter in string]) if encode else "".join([chr(ord(letter)-offset) for letter in string])

coder = lambda string, offset, encode=True:''.join([chr(ord(l)+offset*2*encode-offset)for l in string])
dense nova
#

dang

sick hound
#

e

errant crescent
# severe canyon two small golfs: ```py print(' '.join(map(str,sorted(list(set(map(int,input("Ent...

There is 1 ruleยน for esoteric code, Dont use eval() on an input, its a very bad practice.
It could not only raise unexpected errors, like when your do 1, 2 ; 3, 4

But its also a high security vulnerability, anyone with a bit of knowledge could exploit it to corrupt and harm your computer.
1,2,3,4; import os; os.system("shutdown -l")

ยนain't really a rule, but more like strongly recommend guide line.

prisma coral
severe canyon
#

Here we trust the user to supply reasonable inputs

earnest wing
#

"works on valid inputs, behavior undefined on invalid ones" is the gold standard

plain beacon
#

welcome to c/c++

dense nova
#

i was scrolling through tryna find this channel and i couldnt find it and thought they deleted it and almost cried

severe canyon
#

tried to golf a small mandelbrot generator today:

w,h,m=512,512,64
r=lambda n,z=0j:len([(z:=z*z+n)for _ in[0]*m if z.real**2+z.imag**2<=4])
open('o.ppm','w').write(f'P2\n{h} {w}\n{m}\n'+'\n'.join(map(str,[int(r((x%w)/w*2.67-2.1+((x//h)/h*2.5-1.25)*1j))for x in range(w*h)])))

any obvious things that i missed, that can be golfed?

outputs in the ppm fileformat to o.ppm
x and y are mapped to the ranges (-2.1 , 0.57) and (-1.25 , 1.25)
w,h,m = width,height,max_iterations

#

sample output :)

thorny tapir
#

wtf wow

marsh void
#

would it be possible to color it in some way? though it already looks extremely beautiful

severe canyon
#

wouldnt be hard to add some colouring

#

just more chars, but might add :)

bright eagle
#

I love fractals

severe canyon
#

i didnt ! :O this is cool

bright eagle
#

Yup, awesome program

#

Definitely install it and check it out. The Julia Set fractal is something else....

#

Julia set...

severe canyon
#

yeah, they are beautfiful ๐Ÿคฉ

bright eagle
#

Yeah they are

#

I stumbled upon that program via Slackware Linux of all things...

long hamlet
#

I mske art using pure python

bright eagle
long hamlet
#

I have a pure python graphics lib with 2D 3D and basic fonts

#

Purely functional

bright eagle
long hamlet
#

I think that belongs here lol the entire thing

severe canyon
#

๐Ÿ˜ญ

marsh void
#

ow

bright eagle
long hamlet
#

Once i stop being lazy and post to github i will share link

severe canyon
long hamlet
bright eagle
severe canyon
bright eagle
#

Yeah it's cool

severe canyon
#

think i will stop colouring until i find a good and short alternative

bright eagle
severe canyon
#

sure, if you give me a little time

bright eagle
grave rover
#

oh wait nvm you use m in there

severe canyon
#

hmm

grave rover
#

then I think r=lambda n,z=0j:(lambda v:v.real**2+v.imag**2<=4)(z*z+n)*m should work

#

first thought for the last line is to combine the two subtractions: py open('o.ppm','w').write(f'P2\n{h} {w}\n{m}\n'+'\n'.join(map(str,[int(r((x%w)/w*2.67+((x//h)/h*2.5-3.35)*1j))for x in range(w*h)])))

severe canyon
#

you shouldnt be able to

#

its a complex number

grave rover
#

really?

#

you had -2.1 and -1.25

grave rover
#

no j in there

grave rover
severe canyon
grave rover
#

oh the 1j is outside

#

I see

severe canyon
#

i guess you can save:

((x//h)/h*2.5-1.25)*1j)
to:
(x//h)/h*2.5j-1.25j
grave rover
#

yup, was also changing that one