#esoteric-python
1 messages ยท Page 137 of 1
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 :white_check_mark: Your eval job has completed with return code 0.
P
it's still P, lol
how cannn I golf this py k=P=1 while k<1e4:P%k>0==print(k);P*=k*k;k+=1
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?"
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.
range(1e4) is not valid, since 1e4 is a float and not an int
!e
print(type(1e4))
@severe canyon :white_check_mark: Your eval job has completed with return code 0.
<class 'float'>
also, this is not really helping the golf situation
!e
k = 1
print(1e4 > k)
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.
still, using numpy would make it way larger than the original 45 bytes
Indeed.
Indeed.
Thats why I only imported the important stuff from math. [.prod() and .ceil()]
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
Yeah, just wanted a go at it.
Its missing the caching of the last operation, and it's re-computing p every time. While i got rid of another variable; this just made it do more calculations >.< (and potentially slow the program)
golfing isnt about being fast, if the program takes 9000 years.. it will take 9000 years hehe ๐
but you do you :)
hey guys how work python obfuscators? and what i need to do one?
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 :)
cant ask for everything haha
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
code.golf
i took a look at the numbers, is this just getting all primes under 10000?
yeah
damn
what?
im just impressed this calculates primes
It uses Wilson's theorem
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
:)
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
do I look like I have this much time? my guess is you're using zero width spaces and zero width nonjoiners
people sometimes do who go to #esoteric-python
you can spend lots of time and have nothing to show for it except for horrified looks
I mean I'm making something esoteric rn
lmao
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
lol #pythonic-python is not welcome here
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
โฐ๏ธ
!e
type('',(),{'__getattr__':lambda s,a:exec(__import__('base64').b64decode(a+'='))})().cHJpbnQoIkhlbGxvIHdvcmxkISIp
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
Hello world!
!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
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
Hello world!
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___
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
False
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
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
!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]][i2 <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(Xa+2( h+
s) [c
](n-2[0,a][a>=1]-2b)+X[::-1]*b)
@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
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)]))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Star
kewl
!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
@sick hound :warning: Your eval job has completed with return code 0.
[No output]
!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))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Java SucksJava
Does this function have a purpose? Will I ever use it? Why did I even create it? All these questions have unknowable answers
doesnt this evaluate decimals incorrectly? ๐ค .2 of "java sucks" should be "ja" ?
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))```
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Java SucksJa
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))
!e
f=lambda s,n:s*int(n)+s[:int(round(n%1,2)*len(s))]
print(f("Java Sucks",1.2))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Java SucksJa
You forgot to place the code with the !e in its own message
yeah yeah whatever xD
But nice that that absolutely useless piece of code got golfed
I just created that to spite a Rust programmer I know who hates that Python allows string multiplication
smoll eldritch code โฅ๏ธ
:D
This entire channel is basically a big "f you" to the readibility of Python lmao
yessir
We are an affront to god themself with our code!
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: "))
x1,y1,x2,y2 = [int(input(f'{t}: ')) for t in ('x1','y1','x2','y2')]
x1 = int(i("x1: "))
could shorten the list but ah well
Thanks, that works
this was my first idea too
I prefer readability over efficiency
i am trying to golf my code
just get rid of prompts to save chars
yeah, will do that later on
i = lambda x='':int(input(x))
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
x1,y1,x2,y2=[int(input())for i in[0]*4]
ยฏ_(ใ)_/ยฏ
well call them abcd
just for the lols, use emojis for the variable names while golfing ๐, ๐, ๐, and ๐ instead of x1, y1, ...
Massive iq moment
Okay, thats actually pretty great idea
will do will do
Hieroglyphics make code 10% faster, add RGB lighting and you get 200% speed boost to your code
Proven fact
dont forget the gamer chair
Depending on the type of the glyph you pray to a different god and you get different code buffs
And wear your coding socks
all my homies code in Anubis for resurrected variables
Wouldn't want brainpower to leak out so you wear sealed socks
i need things to golf 
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
Just golf FizzBuzz
what is this doing?
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
hmm
uh what's the blue line then
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
oh you are right
from 1031 chars to 755
slowly getting smaller
yep
tight and warm socks
@severe canyon golf this
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
(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
if anyone has any ideas for how could i golf it more, let me know
(i know that i can use spaces instead of tabs)
down to 674 by replacing tabs
back at keyboard, gonna go golf it now
๐
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
Wow, how many chars?
277 i think
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
SHEESH
Why are you mapping to "eval"?
What
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
yeah didnt even think of using another formula xD, this is much better
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
10+1.75(x-5)\{1<x<5\}
10+3.0(x-5)\{3<x<5\}
Tyty
also use stdin!
for l in open(0):
$ python3 line.py < input.txt
82 bytes with ^
this @next flame guy knows his math 
I was like, "maybe they can go down to 500 somehow..."
xd
welp, thats that
next problem!
Tomorrow I will have to add more features to it
Cuz rn it is only able to draw straight line
Which is not enough
Yea
for l in open(0):print('(1-t)({},{})+({},{})t'.format(*eval(l)))
64 now :)
@finite blaze
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
how is input formatted?
aight
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])))
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
how the hell
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
does input need to be from arguments?
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
yeah ok you need to use arguments
cant you remove the ~~ ?
its not doing anything?
also it doesnt need an f string
in the exec
98 :D
what does f=j* do
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
It's mostly a pure math thing
sure!
I moved the discussion to #algos-and-data-structs
return list(map(lambda x: list(map(lambda a: a.split(","), x)), lines))
Honestly atm I have no idea whats going on :p
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.
which makes multiprocessing.pool easier.
You could define __setstate__() too, and build the function in there, then the state doesn't have to relate to your attributes at all.
*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
Good shit
I need to learn these eval() tricks
I only know that eval() can run code from string.
eval("print("X")")
I have 2 more questions
what does the * before eval do?
It unpacks the tuple we get out of the eval, to the 4 arguments
๐
๐
@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:
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)
(you need space between 2 and else)
nope
numbers and else/if dont clash
ยฏ_(ใ)_/ยฏ
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
i see
the wiki page for a spline gives us an algorithm for computing cubic splines
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.
the else(v:=0) seems to be redundant
else 0 works just fine from brief observation
thanks
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
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}
"{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)
@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
904 -> 662
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
!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")
@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
!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:]))
@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
502
that doesnt work unfortunately

its really weird
gives wrong output in the end
im getting a different output than this
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:]))```
!e
import base64,zlib;exec(zlib.decompress(base64.b64decode('eNrlll1OwzAQhN9zilGfQGq5A/SPhxQqkgtY9bZe4diV7Tb09qxTDlALEAWe8jfj+WaTKNkHdulmNBo9OyRDWHCICVqd4LeYmsAxdSpWqxNSOBCsPxIiuYTk0VF1j7UKKbDeEdhBYU0qoA1Ed1X1sWRDG+/05Wu2vUd7CMkSZnIpjqGcviipNRxKgoy4sQjkNgaP5OL4E9kLLzZzeXjWY6qsZbfDg3Dn9C8F4m0RD8vx0luNFyGS5G8HbPitBFDkWBJFmqhJrU5CNf4JaDoKUgl2NqDplYsC3vTcdQP6ddSZ886UtBn0WCnWuc2K7eu5zFWXfOKiOyZyQq00U8RMuc1A/SuLt2WPqshR+zA0rEntB+q/M425LX13zw6seU8h5s1A/sfH1PZki74c2SBnZuHQdXlOw865/z+an/xC3b4DgIohXw==')))
@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
498
no imports :)
can i use __import__?
i think fire got his challenge from here: https://code.golf/12-days-of-christmas#python
:)
yep
only builtins allowed it seems
True, I wonder which way is faster. there's something to be said for lazy loading, and something to be said for not wasting time on more lookups than are needed.
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.
!e
!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!*
#! /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
Can't you do something like
import random
And then just use randint instead or r
Same thing with the from sys
import sys, random
Is shorter
or actually maybe import sys, random as r
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
wait why the use of lambda here in the first place
just clocked, pretty sure we don't need it
you do need sys.argv and r.randint tho
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
Actually you can print *[thing],sep=''
It's like 2 chars shorter
calling r() will fail since you're trying to invoke a module
Then just use
from sys,random import*
And then you can call randint
syntaxerror
Okay, don't remember how it worked
$ 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
import sys, random as r
print(*[chr(r.randint(33,127))for _ in range(int(sys.argv[1]))],sep='')
Can you do something like
import sys, random as s,r?
Can u check the length of this one pls cos I'm on mobile :/
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))))
@dark wharf :white_check_mark: Your eval job has completed with return code 0.
TwUL>**(Lwi
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))
@dark wharf :white_check_mark: Your eval job has completed with return code 0.
|1&0/;H...+b
This looks promising
Alright ima call this one a day
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"
another fun one:
!e ```py
import sys,random as r
n=int(sys.argv[1])
print('%c'*n%(*r.sample(range(33,127),n),))
@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
oh right
errors are fun
!e ```py
import sys,random as r
n=12
print('%c'*n%(*r.sample(range(33,127),n),))
@grave rover :white_check_mark: Your eval job has completed with return code 0.
hr,Zf"WH3.b&
sadly slightly longer since I have to use sys.argv twice
cool solution
especially syntax wack a mole
now this is the channel i came for
@silver olive It's a good feeling right haha.
I look forward to getting confused and making incorrect statements and assumptions, then feverishly editing my hasty comments
spit your wisdom
sadly no
what is this rubbish error
(lambda: _:="".join("wis dom".split()), print(_))[0])()```
sounds arbitrary
why would you need a lambda function here?
now I got it I think
!e
(lambda: ((_:="".join("wis dom".split())), print(_))[0])()
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
wisdom
just needed parens around it
just for fun
ยฏ_(ใ)_/ยฏ
!e
_ = lambda _: _ -_
print(_(_)(1))
@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'
!e
(lambda x: x() - 1)(x)
@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
!e
(lambda x: x() - 1)(1)
@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
!e
x = (lambda x: x() - 1)
x(x)
@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'
!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!*
!e While True:
print("gey")
oh i forgot shit i need to stop smoking
!e While(0):
print("gey")
!e ```py
open('xd.txt', 'w+')
@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'
!e ```py
while True:
print('baka')
@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
@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 ๐
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
you can get the co_code of the upper frame and look for the STORE_* op to get the index
so im looking for store name and the thing to the side of the dis.dis is the index in co_names?
it's the index yeah
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
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?
!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))))
@eager sphinx :white_check_mark: Your eval job has completed with return code 0.
never gonna give you up๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ
@gritty mesa
Excellent
what is #esoteric-python ??
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"
oh nice
there's a lot of scary things here
Lol
enter this channel and you will come out being a different man
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 ๐
you have to enter?
yeah
ddang
wanna see cool stuff ive done xd
i thought you just enter the server and kapow
yeeee
!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
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | _______________________,____,____,__
002 | _______________________,____,____,_
003 | _______________________,____,____,_______,_____________,_
004 | _______________________,____,____,_______,_____________,_
005 | _______________________,____,____,_______,_______,_
woah
wanna know the story behind this
how
sure
i'll pass
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
if you see cheeki or greyblue92 say hi
lmao
use truthy and ascii to do some funny bullshit
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
{}=={} and []==[] are truthy and return 1
i figured
pretty epic troll moment
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
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
@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}")
@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
Omg...
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.
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
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')```
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
is this so you can say things like:
a, b = destructure(d)
assert a==1234 and b is None```
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
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.
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
I don't know nearly enough about type annotations. but I can give you an implementation of destructure() above if you want it.
Final don't makes variable immutable, I can change its value like it never was annotated as Final
if you want to make it immutable just use the read only version of the class with final
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.
(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
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
I'd try in the data-science-and-ai channel. This is the golf and black magic channel, probably not where you're going to get the kind of code suggestions you really want.
that is interesting
figured out why, mappingproxy delegates straight to the wrapped mapping https://github.com/python/cpython/blob/main/Objects/descrobject.c#L1186-L1190
Objects/descrobject.c lines 1186 to 1190
static PyObject *
mappingproxy_richcompare(mappingproxyobject *v, PyObject *w, int op)
{
return PyObject_RichCompare(v->mapping, w, op);
}```
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;
}```
that means that here https://github.com/python/cpython/blob/main/Objects/object.c#L695-L706 line 697 fails, calling the tp_richcompare of w which is our Evil object with an argument of the wrapped dict v
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);
}```
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
in PyPy you can't even modify the wrapped mutable dictionary afaik
@rugged sparrow @earnest wing iirc this was raised as a bug on bpo a while back
BPO issue 43838
!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))
@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
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
the second thing is that it wouldn't be satisfied when e.g. invoking id() on a list
!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))```
@sly root :white_check_mark: Your eval job has completed with return code 0.
True
!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)```
@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__'?
@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.
For future reference, a question like that is more suited for #internals-and-peps
@prisma coral thanks a lot! i dream of becoming such an expert one day...
No problem. Your comment about using ids as pointers to memory actually can be used. It's not something you are likely to actually want to use in "proper" coding, but you can do some very fun stuff with a standard library module called ctypes
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)
nice
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
nah, the red highlights are nameerrors
which are false - it runs perfectly fine.
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.
and that's very interesting!
lemme see if I can find the code to answer that
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
my guess is that there's a right-to-left segment in that word or something like that
since:
- it runs, I checked that
- my program only replaces individual chars and doesn't change the order
i guess
and in real it turns out to be the same
but PyCharm doesn't accept it as Python does
@tranquil yarrowHere's the file (when I try pasting it as a message, it gets corrupted I think)
the file should be okay if you download it
keep up the calligraphy <3
You should apply your program to the program itself. And then only use that version from then on
hmm, hold on
a bit complicated, since currently it doesn't quite produce working code on every run
heh
!e
print((lambda: ([]==[]+[]==[])+lambda: []==[])())
@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
!e
print([]==[])
@carmine sun :white_check_mark: Your eval job has completed with return code 0.
True
!e
print([]==[]+[]==[])
@carmine sun :white_check_mark: Your eval job has completed with return code 0.
True
how would i reverse a string?
for example, hello turning into llohe
like reversing 2 digits at a time
idk and probably not the best place to ask.
This sounds like a question that would be best answered in a help channel. Have a read of #โ๏ฝhow-to-get-help . This channel is for Python obfuscation and general esoteric stuff
s[2:]+s[:2] ?
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
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
instead of: yes if condition else no
and it might be heavier, because if-else statement does not "eval" both endpoints expressions
but only one, depending on the condition
and this works because bool is a subclass of int, thus it may be used for indexing, everyone knows that
so if there was such a thing:
yes() if condition else no()
then it would be replaced with
(no, yes)[condition]()
what.
uhm, okay
and if it was to be yes() if condition else NO (NO is some constant)
then it would be replaced with
(yes, lambda: NO)[condition]()
and so on
Lol you need to print something if you want it to give output. Otherwise there's no output, just like if you ran this as a script
is there a way to represent 1 << 0 if x else 0 using only bitwise operators?
i dont think so unless x is an int
x is a boolean
so you want to convert the bool to an int?
a = 1 | (2)*x
``` if x is a bool or an int (1 or 0) that should work
<@&831776746206265384> ^^^
x|0
your expression is equivalent to x, but it is integer
so i convert x from bool to int by |0
~~x
!e
print("1234"[::-1])
@vague cairn :white_check_mark: Your eval job has completed with return code 0.
4321
!e
#this is a more standard idiom for reversing strings.
print(''.join(reversed('1234')))```
@vague cairn :white_check_mark: Your eval job has completed with return code 0.
4321
not really, [::-1] is super common
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']))
@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
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
!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))
@maiden river :white_check_mark: Your eval job has completed with return code 0.
hi
now just gotta make a char to ()==() converter
lol, i just built one : )
for x = 10
your : ((([]==[])*(([]==[])+([]==[]))**(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[]))**([]==[])
mine: ((()==())+(()==()))*((()==())+(()==()))*((()==())+(()==()))*+(()==())+(()==())+(()==())
Hey @maiden river!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
!e
exec('%c'*13%(((([]==[])*(([]==[])+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[])),((((([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[]))**(([]==[])*(([]==[])+([]==[]))*(([]==[])+([]==[]))),((((((([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[]))**((([]==[])+([]==[]))+([]==[])))+([]==[]))*(([]==[])+([]==[])),(((((([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[]))**((([]==[])+([]==[]))+([]==[])))+([]==[]),((((((((([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[])),((((((([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[]))*(([]==[])+([]==[])),((([]==[])*(([]==[])+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[]))**((([]==[])+([]==[]))+([]==[])),((((([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[]))**((([]==[])+([]==[]))+([]==[])))+([]==[]))*(([]==[])+([]==[])),((((([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[]))**((([]==[])+([]==[]))+([]==[])))+([]==[]))*(([]==[])+([]==[])),(((((((([]==[])*(([]==[])+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[])))+([]==[]),(((((((([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[])))+([]==[]),(((([]==[])*(([]==[])+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[]))**((([]==[])+([]==[]))+([]==[])))+([]==[]),((([]==[])*(([]==[])+([]==[]))*(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[]))))
@maiden river :white_check_mark: Your eval job has completed with return code 0.
3.142857142857143
Hey @maiden river!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
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
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.
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)
interesting, you still got lambda, and , or in text, this one's all brackets and operators, except the 'exec' & %c at the beginning : )
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
yea this ain't really about hiding code
it's sort of a JSf..k equivalent for python
It's more fun if not everything is ()==() btw
@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
if you want my obfuscator impl: https://pion.martmists.com/Martmists/PythonSnippets/src/branch/master/obfuscator
nice, thanks!
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
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?
@sick hound ???
@rapid sparrow here : )
I think (hope) they were joking
But what you made is really cool!
๐
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
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 ๐
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
i see @ for the first time
we need more combinators
ohhh yes
postfix functions? interesting
usually I see function composition being right associative
Sort of like piping in bash, it makes it clearer to see in what order stuff is actually happening IMO
maybe | then :>
!e
setattr(type("console", (object,), {}), "log", print)
@shut trail :warning: Your eval job has completed with return code 0.
[No output]
!e
setattr((console := type("console", (object,), {})), "log", print)
console.log("hi")
@shut trail :white_check_mark: Your eval job has completed with return code 0.
hi
@prisma coral one way ^
You can use an empty tuple instead of (object,) for the second arg of type
!e
console=type("",(),{"log":print})
console.log("hi")
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
hi
hmmm, what else
!e
console=[(new_type := type("", (), {})), new_type.__dict__["__getattr__"] = lambda attr: print if attr == "log" else None][0]
console.log("hi.")
@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'
!e
console=[(new_type := type("", (), {})), (new_type.__dict__["__getattr__"] := lambda attr: print if attr == "log" else None)][0]
console.log("hi.")
@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
hm
oh yeah, but can you not create dunder methods by the type way alone?
!e
console = type("", (), {"__init__": lambda: print("hi.")})
console()
@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
!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)
@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
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?
!e counts ?
class console:log=print
console.log('hmm')
@maiden river :white_check_mark: Your eval job has completed with return code 0.
hmm
you can use ctypes
I don't use ctypes too much - what would I use specifically?
I mean I'm familiar with small snippets
you can modify the co_consts tuple in place
Okay, how would I do that?
(what's the structure of tuples in cpython?)
@rugged sparrow you there?
memset?
!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)```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
(4, 2, 3)
you could just use raw offsets but that makes the code harder to understand
I am utterly down to use raw offsets
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)```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
(4, 1, 2)
@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
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
!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)
@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
what is your goal for that code @golden finch
It should print the fibbonaci numbers
then it is very wrong
why?
changing co_consts will not affect y or x
you would need to write into the frames globals
i dont think youre jumping to the right place then
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
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)
scratch that there's some other stuff - it's returning a value
i dont think thats what you want
ok but setitem does not handle refcounts
the problem is apparently that it's setting it to (<class 'ctypes.c_ubyte'>, 166) instead of (1,1)
so that new tuple is dealloced
why do refcounts affect it?
the tuple (y, x+ y) is dealloced
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)
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
try the new setitem
so what do DECREF and INCREF do in this case?
decrease the refcount of the object being repaced and increase the refcount of the object being inserted
!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)
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
(3, 1, 2)
@golden finch this setitem is more fun
those variable names confuse me to no end
!e
!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!*
!e myfunc = lambda x, myf: x*(myf(x-1, myf)) if x > 1 else 1
myfunc(10, myfunc)
@gritty saffron :warning: Your eval job has completed with return code 0.
[No output]
e!
myfunc = lambda x, myf: x*(myf(x-1, myf)) if x > 1 else 1
myfunc(10, myfunc)
Hey @sick hound!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
type(cls).__len__ = lambda self: len(self._instances)
I feel really weird about that...
Why do you need to dynamically set the __len__ of a metaclass?!
!eval
myfunc = lambda x, myf: x*(myf(x-1, myf)) if x > 1 else 1
myfunc(10, myfunc)
@gritty saffron :warning: Your eval job has completed with return code 0.
[No output]
You need to print if you want an output
oh! Thanks!
๐
!eval
!e
myfunc = lambda x, myf: x*(myf(x-1, myf)) if x > 1 else 1
print(myfunc(10, myfunc))
@gritty saffron :white_check_mark: Your eval job has completed with return code 0.
3628800
Ah! got it! Thanks! ๐
how past code to this channel?
!code
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.
thank
I have a custom metaclass to have a singleton with a certain quantity of instances that I don't know in advance. But I need to make it possible to check how many instances are currently available
Honnestly I dont feel very comfortable with this solution .-.
!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()
@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']
Ah I see. Yeah, itโs a bit weird. But if it fits the context then ๐คท
This channel is for discussions of esoteric Python. This includes code obfuscation, exploiting Python quirks and bugs and more. But Iโm not sure what you are posting fits in this channel?
If you have a question, read #โ๏ฝhow-to-get-help and if you want to test bot commands see #bot-commands
Hi, where to look to find out which channel is for what?
I am new to python. Had no clue what 'esoteric Python' stands for!
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
Thanks a lot! ๐
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?
See #โ๏ฝhow-to-get-help if you need help ๐
it stands for .... delightful horror
!e
print((lambda: (lambda: (lambda: (lambda: (lambda: (lambda: (lambda: 'h')))))))()()()()()()())
!e
print((lambda: (lambda: (lambda: (lambda: (lambda: (lambda: (lambda: 'h')))))))()()()()()()())
@sleek sphinx :white_check_mark: Your eval job has completed with return code 0.
h
@sleek sphinx :white_check_mark: Your eval job has completed with return code 0.
h
@sleek sphinx :white_check_mark: Your eval job has completed with return code 0.
h
ah yes
here is the code:
Hey @dire stump!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
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)]
)โ
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
['abcdefghijklmnopqrstuvwxyz', 'BCDEFGHIJKLMNOPQRSTUVWXYZ']
for dividing a list in half
oh , no, there's an A missing
it's definitely cursed -_-
Frankly, i thought 'esoteric Python' might be some version of Python like Cython! ๐ Hence the doubt.
partition = lambda c,n:(lambda l:[c[i*l:i*l+l]for i in range(n)])(len(c)//n)
```did a bit of cleaning up
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 :(
!e ```python
somefloat = .5
print((maybesomeint := somefloat // 1), type(maybesomeint))
@tranquil yarrow :white_check_mark: Your eval job has completed with return code 0.
0.0 <class 'float'>
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))
@tranquil yarrow :white_check_mark: Your eval job has completed with return code 0.
0 <class 'int'>
oh that's good
well yeah but that's longer than int()
ideally float//int should be converted to int
yeah
I wonder what the rationale behind that is
The most accurate type is float
Since it was an operation between a first and an int
ยฏ\_(ใ)_/ยฏ
idk the rationale but ig it could have to do with inf // x == nan or something
whereas if it returned an int
it'd return something
or ig it could error too
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)
its kind of understandable
I mean i could understand bits of it, but its cool esoteric
: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).
!unmute 768660928257982505 be careful with the emotes
:incoming_envelope: :ok_hand: pardoned infraction mute for @remote niche.
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 
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 ๐
yeah, all the lines are supposed to be different projects and not related to each other, except line 2 and line 3, i had to use 2 lines for that. also i believe that when it asks for marks its an int, thats why i said marks and not grade
python3 -c "import random as r;a='';exec('a+=chr(r.randint(33,126));'*$1);print(a)"``` I cheated and used bash with it
it did not occur to me to do that
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])
dang
e
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.
In #esoteric-python bad practise doesnโt exist
"works on valid inputs, behavior undefined on invalid ones" is the gold standard
welcome to c/c++
i was scrolling through tryna find this channel and i couldnt find it and thought they deleted it and almost cried
lmao
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 :)
wtf wow
would it be possible to color it in some way? though it already looks extremely beautiful
I love fractals
@severe canyon you prolly know of this but if not, here you go! https://xaos-project.github.io/
i didnt ! :O this is cool
Yup, awesome program
Definitely install it and check it out. The Julia Set fractal is something else....
Julia set...
yeah, they are beautfiful ๐คฉ
Keep at it! ๐คช
Ewww lol
I think that belongs here lol the entire thing
wanna see horror?
๐ญ
ow
Hahaha wth happened?
Once i stop being lazy and post to github i will share link
colours happened
Better...
i like this!
Yeah it's cool
think i will stop colouring until i find a good and short alternative
So this is the code that generated that black n white Mandelbrot you showed? Could you explain the code? "De-esotericize" it?
sure, if you give me a little time
ok๐
I think you can replace r=lambda n,z=0j:len([(z:=z*z+n)for _ in[0]*m if z.real**2+z.imag**2<=4]) with r=lambda n,z=0j:(lambda v:v.real**2+v.imag**2<=4)(z*z+n)
oh wait nvm you use m in there
hmm
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)])))
and this dont work
no j in there
what's the problem with it?
i guess you can save:
((x//h)/h*2.5-1.25)*1j)
to:
(x//h)/h*2.5j-1.25j
yup, was also changing that one
