#esoteric-python
1 messages · Page 118 of 1
Oh wow
now, I'll show you what I do when i need the number 256
Sorry to bother, but does anyone know?
!e ```py
for annotations in [globals()]:
n: 1<<(n+1)//2 = (0x00for x in 100% yo_mamma is fat. B)
Main:print (Main) = n
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
256
My brain is confused but not confused at the same time.
I got a idea
for x in 100% yo_mamma is fat. B)
is definitely not python
So where I got the number == 1
SyntaxError is my only weakness
Can that become more advance?
Seems like it.
I made a whole switch case default suite here a while ago
before 3.10 that was unpythonic
and looks like what you're trying to emulate
Goddam
It is?
I just don't want the basic ==
ah, search for switch
in this channel
you'll find it quicker that way
probably also filter for by me
This?
yeah that also abuses annotations
but that annotations abuse only works in globals
that's a switch suite in all of it's implementation and glory.
You could probably deimplement whatever you don't use if you want it shorter.
There's also golfing it, obfuscating it to look less pythonic, etc.
sure there's three ways i'd go about the variable names,
_00
_01
_02
_03
_04
lambda _0,_1,_2,_3,_4:...
and so on, or
lambda _____,______:(
lambda _,__,___,____:...,
lambda _,__,________:...
)
or
_
a
b
c
d
e
f
g
lambda w,x,y,z:...
EDIT: i can't count XD
EDIT 2: im lazy XD
ah that's half a lambda expression in the first block im lazy
so that's variablesing
next, statements make python readable, so put all your code in one expression in one line
no
Oh
the first line would name error as it's not being assigned to, annotated, or previously defined
Oi
the second line will make a function with one argument of input and returns 5
I see
!e one line number variables obfuscated brainfuck ```py
(lambda _00,_01='',_02=import('collections').defaultdict(int):(lambda _03,_04,_05='+-<>.,[]':(lambda _06,_07:({([lambda _0,_1,_2,_3:[lambda:(lambda _4,_5:[_0(0,_4),_0(2,5)]and None)(_07_00[_2]),lambda:((lambda _6,_7:_0(2,_7))if _00[_2]==_05[7]else(lambda _6,_7:_0(2,_6)if _00[_2]==_05[6]else lambda _6,_7:print(end='|')))(_3+1,_3-1)][bool(_3)],lambda _0,:lambda*__:None]_00[_06[1]]not in _05(),(_06.setitem(1,1+_06[1]-(_06[2]<0)*2)))for _ in iter(lambda:len(_00)>_06[1]>=0,1==0)}and _06[2]and (()for()in()).throw(Exception('INVALID HALTING STATE'))))([0]3,{a:b for a,b in zip(_05,(lambda _00,_01:[lambda _0:[_00(_02,_0,(_02[_0]+1)%_04),(_0,0)][-1],lambda _0:[_00(_02,_0,(_02[_0]-1)%_04),(_0,0)][-1],lambda _0:(_0-1,0),lambda _0:(_0+1,0),lambda _0:[_03(_02[_0]),(_0,0)][-1],lambda _0:(lambda _1:[_00(_02,_0,_01.pop(_1)if len(_01)>_1 else 0),(_0,0)][-1])(_02[_0]),lambda _0:(_0,+(not (_02[_0]))),lambda _0:(_0,-(bool(_02[_0])))])(import('collections').defaultdict.setitem,[_01]))}))(lambda _0:print (end=chr(_0)if _0>=32 else '['+str(_0)+']'),1<<((0x00for x in utf-8)//2+1)))("++++++++++[>+++>+++++++>++++++++>++++++++++>+++++++++++<<<<<-]>>++.-->>+.+++++++..-------->+This is a comment.-<<<<++.-->>+++++++.------->>+.+++.----<++++++++.--------.<<<+++.")
I'm a dumb dumb
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
Lmao
it's so obfuscated that syntax colouring broke
my esoteric skills are beyond the interpretation of discord syntax colouring
My python scripts are esoteric in functionality as well as readability
I can see that..
I've made a Blue Screen Protocol that crashes the OS if its Windows.
runs fine on linux
but on windows it blue screens
Lmao
it's not even the function call itself.
the function call itself is harmless. until you try to delete what it returns XD
What does it return?
🙃
hence when it's time to stop the program, and it gets deleted, python has then gotta delete those 4 new instances as well
which results in 16 new instances
then 64
then 256
then 1024
then 4096
...

"hang on while we report this problem to Microsoft"
secretly uploads personal files
!e I make my own atexit protocol by doing this ```py
class atexit:
init=lambda s,f,*a:setattr(s,'f',f)or setattr(s,'a',a)
del =lambda s:s.f(s.a)
cancel =lambda s:not setattr(s,'f',lambdaa:None)
@atexit
def when_exiting():
print('World!')
print('Hello',end=' ')
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
Oh
!e ```py
a = 4
b = 4
c = 5
print(a in[b], a in[c])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
True False
Thanks
if you want even further...
Yes?
!e ```py
a = 4
b = 4
c = 5
print({b:True}.get(a,False), {c:True}.get(a,False))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
True False
in that case you could make it return binary integers instead of booleans if you wanted
i.e. logical 0, or logical 1
like in matlab
!e ```py
a = 4
b = 4
c = 5
print(
a<=b<=a,
c<=a<=c
)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
True False
number:True.get(1, False) say I wanted to use multiple values, like 1 and 5, how could I without using or?
{number:True}.get(1, False) remember my only weakness is SyntaxError
Oh yeah
yeah just swap them, equality is commutative
!e ```py
number = 5
result = {1:True, 5:True}.get(number, False)
print(result)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
True
Oh thanks!
that's essentially the python version of switch
except if you want lazy evaluation you gotta use lambdas
!e
__annotations__ = globals();
x: 5 = int;
stdout: open(1, 'w');
number: __import__('random').randint(1, 5) = int;
class Main:
def __init__(self) -> dict:{
(x == 5) & stdout.write(str(x)),
(x <= 10) & stdout.write(__import__('codecs').decode(b'\x48\x65\x6c\x6c\x6f\x20\x77\x6f\x72\x6c\x64\x21')),
({1:True, 2:True}.get(number, False)) & stdout.write(__import__('codecs').decode(b"\x4e\x69\x63\x65\x21"))
}
Start = (self) = (True, False);
y = int;
if (y := 12): {(lambda SubMain: stdout.write(str(SubMain)))(Main().Start)};
@short crag :white_check_mark: Your eval job has completed with return code 0.
5Hello world!Nice!(True, False)
My Start = (self) = (True, False) is there a way of making this more complex but still keeping it the same "style" it is?
!e ```py
annotations = globals();
x: 5 = int;
stdout: open(1, 'w');
number: import('random').randint(1, 5) = int;
class Main:
def init(self) -> dict:{
(x == 5) & stdout.write(str(x)),
(x <= 10) & stdout.write(import('codecs').decode(b'\x48\x65\x6c\x6c\x6f\x20\x77\x6f\x72\x6c\x64\x21')),
({1:True, 2:True}.get(number, False)) & stdout.write(import('codecs').decode(b"\x4e\x69\x63\x65\x21"))
}
Start = (*self,) = (True, False);
y = int;
if (y := 12): {(lambda SubMain: stdout.write(str(SubMain)))(Main().Start)};
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
5Hello world!Nice!(True, False)
!e ```py
annotations = globals();
x: 5 = int;
stdout: open(1, 'w');
number: import('random').randint(1, 5) = int;
class Main:
def init(self) -> dict:{
(x == 5) & stdout.write(str(x)),
(x <= 10) & stdout.write(import('codecs').decode(b'\x48\x65\x6c\x6c\x6f\x20\x77\x6f\x72\x6c\x64\x21')),
({1:True, 2:True}.get(number, False)) & stdout.write(import('codecs').decode(b"\x4e\x69\x63\x65\x21"))
}
Start = (*self,) = ([]==[], []is[]);
y = int;
if (y := 12): {(lambda SubMain: stdout.write(str(SubMain)))(Main().Start)};
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
5Hello world!Nice!(True, False)
Now.. is there still a way of writing __init__ as more complex, but still keeping it intact/work the same way?
!e ```py
annotations = globals();
x: 5 = int;
stdout: open(1, 'w');
number: import('random').randint(1, 5) = int;
class Main:
init:() = lambda self:{
(x == 5) and stdout.write(str(x)),
(x <= 10) and stdout.write(import('codecs').decode(b'\x48\x65\x6c\x6c\x6f\x20\x77\x6f\x72\x6c\x64\x21')),
({1:True, 2:True}.get(number, False)) and stdout.write(import('codecs').decode(b"\x4e\x69\x63\x65\x21"))
} or None;
Start = (*self,) = ([]==[], []is[]);
_:0=0
y = int;
if (y := 12): {(lambda SubMain: stdout.write(str(SubMain)))(Main().Start)};
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 15, in <module>
003 | TypeError: __init__() should return None, not 'set'
004 | 5Hello world!Nice!
I like how the traceback is before the print
Lmao
i think it's confused
reminds me of when i somehow got a terminal develop multiple personality disorder
BRUH
there was two cmd instances sharing the same terminal stream
so the input would alternate between the two, but one prompt would mean input to the other so that made it confusing
Damn
XD
ofc that session blue screened
I see
it took a while for windows to figure out there's something wrong and it should probably blue screen
Really? I think your breaking windows and python
You could say I'm a circuit breaker ;)
Also, is there a way to fix the error that it throws?
this nickname follows a submodule of cursedutils
Ohh alright.
!e ```py
annotations = globals();
x: 5 = int;
stdout: open(1, 'w');
number: import('random').randint(1, 5) = int;
class Main:
init:() = lambda self:{
(x == 5) and stdout.write(str(x)),
(x <= 10) and stdout.write(import('codecs').decode(b'\x48\x65\x6c\x6c\x6f\x20\x77\x6f\x72\x6c\x64\x21')),
({1:True, 2:True}.get(number, False)) and stdout.write(import('codecs').decode(b"\x4e\x69\x63\x65\x21"))
} and None;
Start = (*self,) = ([]==[], []is[]);
_:0=0
y = int;
if (y := 12): {(lambda SubMain: stdout.write(str(SubMain)))(Main().Start)};
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
5Hello world!(True, False)
What did you change?
i appended and None to the set
E:\__py__\__modules__\cursedutils>py -i -m cursedutils
E:\Users\[redacted]\AppData\Local\Programs\Python\Python39\lib\runpy.py:127: RuntimeWarning: 'cursedutils.__main__' found in sys.modules after import of package 'cursedutils', but prior to execution of 'cursedutils.__main__'; this may result in unpredictable behaviour
warn(RuntimeWarning(msg))
>>> from .death import*
>>> dir()
['RecreationalMcNuke', '__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'abort', 'blue_screen_induction_protocol', 'kill_all', 'kill_python', 'nuke_pc', 'raise_error']
>>>
that's a sneak peak at the death.py my nickname mentions
Oh, wow...
calling abort cancels the atexit effect of RecreationalMcNuke instances
Hmm

Is there anyway of transforming the Main class to be more complex, but function the same?
Syntax error 
Wholy shit-
Whoops
Yeet that goes
!e ```py
annotations = globals();
x: (0x00for x in yo_mamma is fat and yo_mamma > a_truck(big_macs*a_lot))//3 = int;
stdout: open(1, 'w');
number: import('random').randint(1, 5) = int;
for function in [type]:
Main = function("Main",(),{
'init':lambda self:{
(x == 5) and stdout.write(str(x)),
(x <= 10) and stdout.write(import('codecs').decode(
b'\x48\x65\x6c\x6c\x6f\x20\x77\x6f\x72\x6c\x64\x21',
)),
({1:True, 2:True}.get(number, False)) and stdout.write(import('codecs').decode(
b"\x4e\x69\x63\x65\x21",
))
} and None,
'Start' :(lambda*self,: (()in((),),((),)in()))(),
'_':0==0
})
y = int;
if (y := 12): {(lambda SubMain: stdout.write(str(SubMain)))(Main().Start)};
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
5Hello world!(True, False)
anything that doesn't raise a syntax error can theoretically do whatever you want it to
but overwriting builtin literals takes a bit of work, however
!e ```py
print (1+2j)
print("that is complex")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | (1+2j)
002 | that is complex
Wtf
!e ```py
echo=print
echo (1+2j)
print("lol")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | (1+2j)
002 | lol
.-.
!e ```py
assert "False"
assert "yo mamma" > "a truck full of big macs"
assert "that was a pretty epic burn"
assert "P" != "NP"
assert False**False
assert AssertionError
print("XD")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
XD
Wtf is that
!e ```py
assert()
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | AssertionError
!e ```py
assert "I have a life" == True
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | AssertionError
7.3. The assert statement
Assert statements are a convenient way to insert debugging assertions into a program:
assert_stmt ::= "assert" expression ["," expression]
``` The simple form, `assert expression`, is equivalent to
```py
if __debug__:
if not expression: raise AssertionError
```...
!e ```py
class annotations(metaclass=lambda*a:type(*a)()):
def setitem(self, item, value):
globals()[item] = globals()item
_: ('X'+'D' *(0x00for x in 110% yo-mamma is fat),) = print
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
XDDDDDDDDDDDDDDD

alright someone gave me this:
+[----->+++<]>+.++++++++++++..----.+++.+[-->+<]>.-----------..++[--->++<]>+...---[++>---<]>.--[----->++<]>+.----------.++++++.-.+.+[->+++<]>.+++.[->+++<]>-.--[--->+<]>-.++++++++++++.--.+++[->+++++<]>-.++[--->++<]>+.-[->+++<]>-.--[--->+<]>-.++[->+++<]>+.+++++.++[->+++<]>+.----[->++<]>.[-->+<]>++.[----->++++<]>.-[->++++++<]>-.-[-->+++<]>-.+[++>---<]>.[--->++<]>-.-[-->+<]>--.+[-->+++<]>.+++[->++++<]>-.>+[--->++<]>++.+++++++++++.[->++++++<]>-.
hang on while i golf this interpreter a little
How it started:
x: int = 5;
class Main:
def __init__(self) -> dict:{
(x == 5): print(x),
(x <= 10): print("Yee yee"),
}
Start = (self) = (True, False);
y: int;
if (__name__ == '__main__') and (y := 12): {(lambda SubMain: print(SubMain))(Main().Start)}
```
How it ended:
```py
__annotations__ = globals();
x: 5 = int;
stdout: open(1, 'w');
number: __import__('random').randint(1, 5) = int;
for function in [type]:
Main = function("Main", (), {
'__init__':lambda self:{
(x == 5) & stdout.write(str(x)),
(x <= 10) & stdout.write(__import__('codecs').decode(b'\x48\x65\x6c\x6c\x6f\x20\x77\x6f\x72\x6c\x64\x21')),
({1:True, 2:True}.get(number, False)) & stdout.write(__import__('codecs').decode(b"\x4e\x69\x63\x65\x21"))
} and None,
'Start' :(lambda*self,: (()in((),),((),)in()))(),
'_':0==0})
y = int;
if (y := 12): {(lambda SubMain: stdout.write(str(SubMain)))(Main().Start);
that link looks suspiciously familiar
hang on
!e ```py
for input in[lambda prompt:builtins.print(end=prompt)or(lambda c:builtins.print(c)or c)("+[----->+++<]>+.++++++++++++..----.+++.+[-->+<]>.-----------..++[--->++<]>+...---[++>---<]>.--[----->++<]>+.----------.++++++.-.+.+[->+++<]>.+++.[->+++<]>-.--[--->+<]>-.++++++++++++.--.+++[->+++++<]>-.++[--->++<]>+.-[->+++<]>-.--[--->+<]>-.++[->+++<]>+.+++++.++[->+++<]>+.----[->++<]>.[-->+<]>++.[----->++++<]>.-[->++++++<]>-.-[-->+++<]>-.+[++>---<]>.[--->++<]>-.-[-->+<]>--.+[-->+++<]>.+++[->++++<]>-.>+[--->++<]>++.+++++++++++.[->++++++<]>-.!"+' ')]:
print=lambda o:builtins.print(end=chr(o))
class type_hints:
def setitem(self, item, value):
if hasattr(value,'args'):
globals()[item] = value([value.args0for e in globals()[item]])
else:globals()[item]=value(globals()[item])
for annotations in[type_hints()]:
i:int="0";
a:list[eval]="i"32;
p:eval="i";
t:int=0.0;
c:input="brainfuck code: ";
c:lambda a: a[0]=c.split('!')
while len(c)>p>=0:
if not t:
if c[p]=='+':a[i]+=1;a[i]%=256;
if c[p]=='-':a[i]-=1;a[i]%=256;
if c[p]=='<':i:int=i-1;
if c[p]=='>': i:int =1+i;
if c[p]=='.':std:print=a[i];
if c[p]==','::ord=c[c.find('!')][a[i]];a[i]=;
if c[p]=='['and(not a[i]or t):t:int=t+1;
if c[p]==']'and(a[i]or t):t:int=t-1;
p:int=p+1-2(t<0);
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | brainfuck code: +[----->+++<]>+.++++++++++++..----.+++.+[-->+<]>.-----------..++[--->++<]>+...---[++>---<]>.--[----->++<]>+.----------.++++++.-.+.+[->+++<]>.+++.[->+++<]>-.--[--->+<]>-.++++++++++++.--.+++[->+++++<]>-.++[--->++<]>+.-[->+++<]>-.--[--->+<]>-.++[->+++<]>+.+++++.++[->+++<]>+.----[->++<]>.[-->+<]>++.[----->++++<]>.-[->++++++<]>-.-[-->+++<]>-.+[++>---<]>.[--->++<]>-.-[-->+<]>--.+[-->+++<]>.+++[->++++<]>-.>+[--->++<]>++.+++++++++++.[->++++++<]>-.!
002 | https://www.youtube.com/watch?v=dQw4w9WgXcQ
I recognise that link without even clicking it lol
let's see if my generator can think of a better code for that
!e ```py
annotations=globals()
: +'+-<>'=",.[]";
://2 +1=(0x00for x in 100% yo_mamma is fat)
def code(
0:(str,"The code, preferably UTF-8")="",
1:(int,'architecture of target machine')=__
):
if not(_0):return''
if ord(max(_0))>1<<_1:raise RuntimeError(
"Cannot encode "+max(_0)+" into character size "+str(_1)
) ;-D
for _00 in['']:01: (list, "mem::code")=[ord()for _ in str(_0)]
_02:(list, "bf::mul-values")=[
_ for _ in range((max(01)+2)//10)if any([__//10== for __ in _01])
];_02+=(max(_01)//10 not in _02)[max(_01)//10]
00+='+'*10+'[>'+'>'.join(['+'for _ in _02])+'<'*len(_02)+'-]>'
_03:(int,"sys::pointer-shift state")=int()
_04:(list,'mem::turing-machine')=[0]*len(_02)
for _10 in _01:
_11:(tuple, ("chop off last digit","last digit"))=_10.divmod(10)
while _11[0]>_02[_03]:_03+=1;_00+='>';
while _11[0]<_02[_03]:_03-=1;_00+='<';
_12:(int,'cell_increment')= _11[1]-_04[_03]
_00+={1<0:'+',0<1:'-'}[12<0]*abs(12)+'.'
04[03]+=12
05:(str, 'conflict')=[:2],[2:4]
for _2 in range(2):
while _05[_2]in _00:_00=_00 .replace(_05[_2],'')
while _05[_2][::-1]in _00:_00=_00.replace(_05[_2][::-1],'')
return _00
script:print (script)=code("https://www.youtube.com/watch?v=dQw4w9WgXcQ")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
++++++++++[>++++>+++++>++++++>++++++++>+++++++++>++++++++++>+++++++++++>++++++++++++<<<<<<<<-]>>>>>>++++.>++++++..----.+++.<<<<<++++++++.<+++++++..>>>>>>++++...<<<<<<-.>>>>>>>+.<--------.++++++.-.+.<<++++++++.>---.<<<<<.>>>>+.>>------.<++++++++.<<<<<+.>>>>>>++++++++.<<--.>>---.<<++.>-----.<<<+++.>>>>++.<<<<--.>>>----.<<+.>>>+.<<<<<------.>>>>>.<<<<<+++++.>>++++++.>>+++.<<+.>.<-------.
I think it might be a little bit shorter
!e ```py
def bf(p):
s,a='',[0]*32;j=t=0
for i in p:s+=' 't+'j-=1 a[j]+=1 j+=1 a[j]-=1 print(end=chr(a[j])) while+a[j]: # # # #'.split()[ord(i)%18-6]+chr(10);t+=(i>'Z')-2(i>'[')
exec(s,locals(),locals())
bf("++++++++++[>++++>+++++>++++++>++++++++>+++++++++>++++++++++>+++++++++++>++++++++++++<<<<<<<<-]>>>>>>++++.>++++++..----.+++.<<<<<++++++++.<+++++++..>>>>>>++++...<<<<<<-.>>>>>>>+.<--------.++++++.-.+.<<++++++++.>---.<<<<<.>>>>+.>>------.<++++++++.<<<<<+.>>>>>>++++++++.<<--.>>---.<<++.>-----.<<<+++.>>>>++.<<<<--.>>>----.<<+.>>>+.<<<<<------.>>>>>.<<<<<+++++.>>++++++.>>+++.<<+.>.<-------.")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
https://www.youtube.com/watch?v=dQw4w9WgXcQ
Lol
guys
wat
i find this repo https://github.com/pablogsal/python-horror-show
>>> a = 300
>>> b = 300
>>> a is b
False
>>> a = 300; b = 300
>>> a is b
True```
SEMICOLONS HAVE A USE
the repo says "assignations occur in the same line both variables will refer to the same object to avoid wasting space.", is that true? why this really occurs?
cpython internals for the most part
wdym? 
Yes.
to make assignments slightly faster, I guess
@floral meteor can I give you a challenge?
Convert this:
__annotations__ = globals();
x: 5 = int;
stdout: open(1, 'w');
number: __import__('random').randint(1, 5) = int;
for function in [type]:
Main = function("Main", (), {
'__init__':lambda self:{
(x == 5) & stdout.write(str(x)),
(x <= 10) & stdout.write(__import__('codecs').decode(b'\x48\x65\x6c\x6c\x6f\x20\x77\x6f\x72\x6c\x64\x21')),
({1:True, 2:True}.get(number, False)) & stdout.write(__import__('codecs').decode(b"\x4e\x69\x63\x65\x21"))
} and None,
'Start' :(lambda*self,: (()in((),),((),)in()))(),
'_':0==0})
y = int;
if (y := 12): {(lambda SubMain: stdout.write(str(SubMain)))(Main().Start);
``` to a one liner
@floral meteor do you think you could?
people here have onelinerizors
Bruh
I would, but i have papercut on my thumb
!e ```py
(lambda x=5,stdout=open(1,'w'),number=import('random').randint(1,5):[(lambda function:globals().update({'Main':function('',(),{'init':lambda self:{x==5 and stdout.write(str(x)),x<=10 and stdout.write(import('codecs').decode(b'\x48\x65\x6c\x6c\x6f\x20\x77\x6f\x72\x6c\x64\x21')),({1:True, 2:True}.get(number, False))and stdout.write(import('codecs').decode(b"\x4e\x69\x63\x65\x21"))}and None,'Start':(lambda*self,: (()in((),),((),)in()))(),'_':0==0})}))(type),(y:=int),(y:=12)and(lambda SubMain: stdout.write(str(SubMain)))(Main().Start)])()
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
5Hello world!Nice!(True, False)
there you go
i get rid of the line breaks
Oh alright.
and then change the code until it works again
So it's pretty simple then?
:/
()[]{}
want some clues?
just as i previously showed you how to assign without equals, it's possible to call functions without brackets
!e for example
a = 4
print(a.__add__(5))
print(a + 5)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 9
002 | 9
a+5 calls a.add with 5 as the argument
Ohh
so
2 + 2 == 5
calls
(2).__add__(2).__eq__(5)
well, technically...
!e ```py
print(int.eq(int.add(2,2),5))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
False
now while you're figuring that out im gonna make that line give True instead of False
Alright
oh, and in case you haven't learnt it before, search google or open a help channel and ask about "decorators"
!e ```py
@(2).lt
@lambda _:5
def yay():pass
print(yay)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
True
I know a little about them
Idk how to make them
But ik what they do
you don't really need to make them. in the current version of python anything that's callable is valid
Oh ok
Can I use brackets in other parts of my code but not in print or no brackets at all?
no brackets at all

i've overcompensated it's giving me 2+2==6 smh
Lmao
!e ```py
from ctypes import py_object as p;
hack = lambda victim:p.from_address(id(victim)+8);
class protect:
gulag = {2:hack(2).value}
def del(self):
for prisoner in gulag:
hack(prisoner).value = gulag[prisoner]
@lambda c:setattr(hack(2),'value',c)
class Int(int):
def add(self, other):
return super().add(int.add(other,1))
result = 2 + 2 == 5
print((2).add(2))
assert result
print("Big Brother is watching you")or protect
@floral meteor :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
lmfao
Tf
@floral meteor can I continue tomorrow? I'm tired rn
k
Thanks and goodnight
olivia?
forbiddenfruit
yeah i woulda used fishhook on int
small problem with forbiddenfruit
>>> import forbiddenfruit
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "E:\Users\[redacted]\AppData\Local\Programs\Python\Python39\lib\site-packages\forbiddenfruit\__init__.py", line 47, in <module>
import inspect
File "E:\Users\[redacted]\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 35, in <module>
import ast
File "E:\Users\[redacted]\AppData\Local\Programs\Python\Python39\lib\ast.py", line 636, in <module>
class _Precedence(IntEnum):
File "E:\Users\[redacted]\AppData\Local\Programs\Python\Python39\lib\enum.py", line 174, in __prepare__
enum_dict['_generate_next_value_'] = getattr(
File "E:\Users\[redacted]\AppData\Local\Programs\Python\Python39\lib\enum.py", line 105, in __setitem__
if _is_sunder(key):
File "E:\Users\[redacted]\AppData\Local\Programs\Python\Python39\lib\enum.py", line 38, in _is_sunder
len(name) > 2 and
TypeError: '>' not supported between instances of 'int' and 'NodeVisitor'
>>>
2 is now an instance of NodeVisitor
bruh
>>> del protect
E:\__py__\__modules__\cursedutils>
the function that was meant to prevent segfault, segfaulted
lol🤣 👍
haha yes, it works
original image
python3 -m metascii --width 20 --out hello.py img.png
It goes both directions? How divinely fiendish.
Does anyone her know subleq or more specifically the SIC-Game(https://jaredkrinke.itch.io/sic-1)
Pls ping
I've heard of it; why, do you have some Python-related take on it?
One time I made a compiler to subleq from a language pretty similar to subleq, in Python.
Not very esoteric Python though...
Yes I want to make a compile of the language using python
Esoteric Python?
I don't know? I thought subleq is an esoteric programming language and that's why it fits here
But don't know the server structure well enough to know what's esoteric python, sorry if this is the wrong chanel
I reckon the topic is well suited for the general Python help channels. (I don't know of any language design channels unfortunately.) This one is mostly for golfing, bad practice and that one weird trick that Python programmers don't want you to know.
Myself, I like esolangs, and I know a fair few others in this channel do too, but there are other servers for esolangs.
What is meant by golfing?🏑⛳?
Oh ok. Is golfing an acronym?
Oh. Makes sense
yes
least amount of code
trye
but
you learn a lot about language
best code golfing for me is in JavaScript and C
or some specialised languages
didn't use python for it ;))
will try
there is a great esolanf wiki
esolang wiki
u could also make one language by yourself
but like in python/c or something
real compilers take time to make ;))
wdym
there is no tutorial for it
There are some very short Python brainfuck compilers, further up in this channel.
u gonna figure it out yourself
make brainfuck compilers in c kek
brainfuck compiler takes 5m to make
I first learnt what they were on the code golf stack exchange, then took to browsing the wiki, which has links to various servers.
brainfuck jit compiler tho 
^^
there is literally code golf site
the point is
to solve problems with least amount of code
well read few books
and learn CS
I am currently working on my jit compiler and I can tell you its fun af
I'm learning so much
There's a well-recommended guide called 'Crafting Interpreters'.
no llvm backend, everything from scratch
that one is also cool
wdym
lmao
wdym
I expect so. I've not actually searched for it (not enough time to make things) but I hear it's valuable.
its not syntax dependant
I dont think u know what you're talking about but ok
you can't make interpreter tUtOrIaL
u have to know CS
read a lot of books
The channel topic gremlins are probably getting restless, so I'll offer them this piece of esoteric Python: there's a neat language called Pyth (https://esolangs.org/wiki/Pyth) which compiles to Python, but is designed to be much less verbose.
and then make one yourself
asking people for help w specific things is totally ok tho
but dont make them spoonfeed u
I would hazard that reading a tutorial could teach you exactly the computer science you need in order to make one.
do u know what c++ creator said?
u can't learn much by a tutorial kek
That's not what I've heard.
2-3k pages of theory at least
and then know x86
and C
and how computers work
*or arm if you aren't targeting x86 cpus
That all sounds highly unnecessary.
🤔 if you want to make shitty compiler then yes
how u gonna make abstract syntax trees
parsing?
scanning
analyzing
backend?
how u gonna make that
There are libraries.
without knowing theory
🤦♂️
I was being facetious, I admit. But you don't need to know asymptotic runtime complexities, page tables or Dijkstra's Algorithm in order to make one. That's why I thought a tutorial can teach you enough.
Indeed.
why did you mentioned it then
There's a lot of computer science that doesn't go into compilers. That's why it's a little pointless to merely recommend learning computer science.
Fair, fair.
but even when u know compiler theory
u gotta know how CPUs works
would recommended
nand2tetris
then learning C preferably or C++
how they work how they compile etc...
then after 5-6months or few years depending on how much work you put in
you can start making some cool stuff
there is no easy way in life for anything
I think we might have different projects in mind. If you want to work in industry, then sure, that might all be helpful. But it's no substitute for getting your hands dirty and creating things — and failing to create things, then figuring out what you did wrong.
Maybe we should take this to DMs.
u and I?
If you'd like to discuss further.
discuss what exactly?
I just don't get the sense anyone else is participating.
What sort of experience is needed to make an interpreter or compiler.
Okay. I guess we should agree to disagree.
If you don't compile to machine code and instead transpile to e.g. C or some compiler IR, then you don't need to deal with mov semantics
Of course, a good compiler is grounded in theory.
!e
(datetime:=__import__("datetime"));(datetime:=datetime.datetime);(time:=__import__("time"));(sleep:=time.sleep);(dt_now:=lambda:print(datetime.now()));(sleeper:=lambda:sleep(1));(lambda f,g,n:[(f() or g()) for _ in range(n)])(dt_now, sleeper, 5)
@ornate spire :white_check_mark: Your eval job has completed with return code 0.
001 | 2021-06-16 13:24:10.097207
002 | 2021-06-16 13:24:11.102700
003 | 2021-06-16 13:24:12.108128
004 | 2021-06-16 13:24:13.112478
005 | 2021-06-16 13:24:14.114486
How often do you guys obfuscate yoru python code. And why did you do it?
is there a way to access a global by passing it to a function? for example;
def foo(bar):
# use bar to access and modify the global baz
baz = ""
foo(baz)
obviously theres return and baz = foo(baz) but i wanna do it without that
do you know that global keyword?
yeah, im currently using a hacky search by value with it
def foo(n):
i = [x for x in globals().items() if x[1] == n]
return i[0][0] if i else ""
globals()[i] ...
nb the variable i wanna change wont be the same each time so global baz wouldnt work
you can do this for small ints ```py
from ctypes import *
def foo(bar):
c_int.from_address(id(baz)+24).value = 2
baz = 1
foo(baz)
print(baz)```
oh interesting, does the implementation for strings (or i guess char arrays) work similarly?
wait, youve used baz inside the function
ah okay i get why that works, small ints have predefined memory addresses during runtime, unfortunately i need to do this for any type of variable where i assigned it to str
anyway heres cin in all its space = eol glory
class cinClass:
def __init__(cls): globals()["0"],globals()["1"] = False, False
def __add__(cls, n):
i = [x for x in globals().items() if x[1] == n]
return i[0][0] if i else ""
def __rshift__(cls, in_):
if globals()["0"]:
globals()["0"], globals()[cls + in_] = False, input(globals()["1"]).split()[0]
else:
globals()["0"], globals()["1"] = True, in_
return cls
cin = cinClass()
var = "";
cin >> "prompt" >> var;
demo
Does that just print hello world?
in the image i use cin to take hello from the input hello world, given the prompt prompt. having assigned that to var i use cout to print var which results in hello/command/prompt/here $ because i forgot to use endl
you can have ```py
from ctypes import *
import sys
def foo(bar):
c_ssize_t.from_address(id(bar)+16).value = 4
(c_char*len(bar)).from_address(id(bar)+48).value = b'defg'
baz = 'abc'
foo(baz)
print(baz)```
but it breaks if you set the length too high
Rather than overwriting the heap, you could just allocate a new cstring and reassign the pointer in 48
what sort of function is so sensitive that it could crash python?
!e ```py
a = (1<<64)+1
borderline_truthiness = lambda n:[a-(a+(1<<10)+eval("2048.000000000000227373675443232059478759765625")),a-(a+(1<<10)+eval("2048.000000000000227373675443232059478759765625"+'0'*2048+'1'))][bool(n)]<0
print(borderline_truthiness(0))
print(borderline_truthiness(1))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | False
002 | True
!e this magic number i now name Slightly More Than 2048 which i rather crudely generated (it was satisfying to watch it generate) ```py
a = (1<<64) + 1
result_left = a - (a+(1<<10)+ 2048.0000000000002273736754432320594787597656249999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999 + 1.0)
result_center = a - (a+(1<<10)+ 2048.000000000000227373675443232059478759765625 + 1.0)
result_right = a - (a+(1<<10)+ 2048.0000000000002273736754432320594787597656250000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 + 1.0)
print(result_left, result_center, result_right) # 0.0 0.0 -4096.0
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
0.0 0.0 -4096.0
slightly less than Slightly More Than 2048, Slightly More Than 2048 and slightly more than Slightly More Than 2048, respectively
!e ```py
a = (1<<64) + 1
print(a + 1.0 < a)
print(a - a + 1.0)
print(a - (a+1.0))
print(a - int(a+1.0))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | True
002 | 1.0
003 | 0.0
004 | 1
!e ```py
print(0.0 / -1, '/ 0')
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
-0.0 / 0
!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.
cursed python: macro expansion
#!/usr/bin/env python3
import re
import inspect
def macro_string_transform(source):
source = re.sub("(?m)(^|\s+)@macro_expand(\s+|$)", "", source) #drop "@macro_expand"
source = re.sub("^def (\w+)_\(", "def \\1(", source) #remove trailing underscore
# actual macro replacements:
source = re.sub("REPLACEME", "replaced value", source)
return source
def macro_expand(f):
s = macro_string_transform(inspect.getsource(f))
exec(s, globals(), globals())
@macro_expand
def test_(): #note the trailing underscore
print("REPLACEME")
test()```
(doesn't work with pythonbot because inspect seemingly only works when code is loaded from a file)
but it prints replaced value
thoughts?
how cursed is this?
you could do it differently though
actually I forgot you changed the actual code of the function
I could probably write a better one using the ast module actually...
I know it's not python, but it's esoteric.
I randomly print 1s, 0s and all sorts of interesting escape sequences!
hey it just jumped to the top O_O
it didn't even finish the line smh
inchresting

or you can use inspect to find the module itself, replace the macro text with regex in the module, exec the module, then exit before the unedited module is run
...which I have done in a project >_>
alright i just did an exam my brain is fried so i can't do the usual big brain, how do i find the "nearest" element e in an array a to a given quantitative variable x?
i thought of a project, but i'm gonna need an elegant version of that for it to go at any decent speed
otherwise i gotta use the crude solution...
!e ```py
from random import randint
def nearest(x, a):
i = j = x
while all([e not in a for e in[i,j]]):i-=1;j+=1
return i if i in a else j
for i in range(8):
a, x = [8e-randint(1,8)for e in range(20)], randint(1,820)
e = nearest(x, a); print (x,e); print (*a)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 138 142
002 | -6 1 13 23 29 34 44 50 62 68 74 85 92 98 109 118 121 131 142 149
003 | 65 65
004 | -6 5 11 18 26 39 41 48 63 65 77 80 88 103 106 113 126 134 142 147
005 | 144 146
006 | -8 4 13 22 31 32 47 52 59 66 78 85 88 98 106 113 123 131 139 146
007 | 37 38
008 | -2 1 9 18 27 38 40 53 57 67 73 84 88 99 108 113 120 132 136 145
009 | 42 40
010 | -6 1 8 20 24 35 40 52 59 65 78 82 95 100 107 113 124 133 143 144
011 | 134 135
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ekiketugiv.txt?noredirect
I mean that sort of works i guess, now i just need to make a hashable rgb object
@viscid nymph @dire galleon changed it to work a little better with ast:```py
#!/usr/bin/env python3
import re
import ast
import inspect
def macro_string_transform(source):
module = ast.parse(source)
assert type(module) is ast.Module and len(module.body) == 1
f = module.body[0]
assert type(f) is ast.FunctionDef
f.decorator_list = [d for d in f.decorator_list if type(d) != ast.Name or d.id != 'macro_expand' ]
for node in ast.walk(f):
if (type(node) is ast.Call and
type(node.func) is ast.Name and
node.func.id == 'bad_print'):
node.func.id = 'print'
elif (type(node) is ast.Constant and
type(node.value) is str):
node.value = node.value.replace("textreplaceme", "replaced value")
return ast.unparse(f), f.name
def macro_expand(f):
s, name = macro_string_transform(inspect.getsource(f))
exec(s, globals(), globals())
return globals()[name]
@macro_expand
def test():
bad_print("bad_print, textreplaceme")
test()
makes it easier to replace methods without accidentally replacing strings
named tuple
ew i'll make my own one, that way I can customise it
Since I have the bad habit of placing metadata in custom classed variables
!e ```py
class RGB(tuple):
def init(self, iterable=(), , r=0, g=0, b=0):
if len(iterable)!=3:iterable = (r, g, b)
self.r, self.g, self.b = iterable = (((e//1)%256 for e in iterable),)
super().init()
def hash(self):
rgb = self.r, self.g, self.b
r,g,b = [bin(channel).removeprefix('0b').zfill(8)for channel in rgb]
value = int('0b'+''.join([r,g,b]).lstrip('0'),2)
return value
def list(self):return[*self]
def index(self):return hash(self)
print(hex(RGB((255, 136, 255))))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
0xff88ff
!e ```py
class RGB(tuple):
def init(self, iterable=(), , r=0, g=0, b=0):
if len(iterable)!=3:iterable = (r, g, b)
self.r, self.g, self.b = iterable = (((e//1)%256 for e in iterable),)
super().init()
def hash(self):
rgb = self.r, self.g, self.b
r,g,b = [bin(channel).removeprefix('0b').zfill(8)for channel in rgb]
value = int('0b'+''.join([r,g,b]).lstrip('0'),2)
return value
def list(self):return[*self]
def index(self):return hash(self)
rgb = RGB(r=255,g=128,b=255)
print(hex(rgb))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
0xff80ff
tell me a named tuple can do that
!e or this ```py
class RGB(tuple):
def init(self, iterable=(), ,hex=None, r=0, g=0, b=0):
if len(iterable)!=3:iterable=(r,g,b)if hex is None else((
int(e,16)for e in[''.join(_)for _ in zip(hex[::2],hex[1::2])]
),)
self.r,self.g,self.b=iterable=(*((e//1)%256 for e in iterable),)
super().init()
def hash(self):
rgb=self.r,self.g,self.b
r,g,b=[bin(channel).removeprefix('0b').zfill(8)for channel in rgb]
value=int('0b'+''.join([r,g,b]).lstrip('0'),2)
return value
def list(self):return[*self]
def index(self):return hash(self)
def str(self):return hex(self).removeprefix('0x')
@property
def rgba(self):return(*self, 255)
print(RGB(hex='CE0CE0'))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
ce0ce0
@floral meteor dude, please add some whitespace
it does not make your code look cooler, regardless of what you may think
!e ```py
#coding:unicode-escape
class\x20RGB(tuple):\n\tdef init(self,iterable=(),,hex=None,r=0,g=0,b=0):\n\t\tif\x20len(iterable)!=3:iterable=(r,g,b)if\x20hex\x20is\x20None\x20else((int(e,16)for\x20e\x20in[''.join()for\x20\x20in\x20zip(hex[::2],hex[1::2])]),)\n\t\tself.r,self.g,self.b=iterable=(*((e//1)%256\x20for\x20e\x20in iterable),);super().init()\n\tdef hash(self):rgb=self.r,self.g,self.b;r,g,b=[bin(channel).removeprefix('0b').zfill(8)for\x20channel\x20in\x20rgb];value=int('0b'+''.join([r,g,b]).lstrip('0'),2);return\x20value\n\tdef\x20__list__(self):return[*self]\n\tdef\x20__index__(self):return\x20hash(self)\n\tdef\x20__str__(self):return\x20hex(self).removeprefix('0x')\n\t@property\n\tdef\x20rgba(self):return(*self,255)\nprint(RGB(hex='CE0CE0'))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
ce0ce0
fite me
this is #esoteric-python I can do what I want
!e @rare yarrow ```py
exec("捬慳猠則䈨瑵灬攩㨊।敦 彩湩瑟弨獥汦Ⱪ瑥牡扬攽⠩Ⱚⱨ數㵎潮攬爽〬朽〬戽〩㨊उ楦敮⡩瑥牡扬攩ℽ㌺楴敲慢汥㴨爬本戩楦數猠乯湥汳攨⨨楮琨攬ㄶ⥦潲湛✧潩渨弩景爠张楮⁺楰⡨數嬺㨲崬桥硛ㄺ㨲崩崩Ⱙਉॳ敬昮爬獥汦ⱳ敬昮戽楴敲慢汥㴨⨨⡥⼯ㄩ┲㔶潲渠楴敲慢汥⤬⤻獵灥爨⤮ 彟楮楴彟⠩ਉ摥映彟桡獨彟⡳敬昩㩲杢㵳敬昮爬獥汦ⱳ敬昮戻爬本戽孢楮⡣桡湮敬⤮牥浯癥灲敦楸⠧ぢ✩晩汬⠸⥦潲桡湮敬渠牧扝㭶慬略㵩湴⠧ ぢ✫✧潩渨孲ⱧⱢ崩獴物瀨✰✩ⰲ⤻牥瑵牮⁶慬略ਉ摥映彟汩獴彟⡳敬昩㩲整畲湛⩳敬晝ਉ摥映彟楮摥硟弨獥汦⤺牥瑵牮慳栨獥汦⤊।敦 彳瑲彟⡳敬昩 㩲整畲渠桥砨獥汦⤮牥浯癥灲敦楸⠧へ✩ਉ䁰牯灥牴礊।敦杢愨獥汦⤺牥瑵牮⠪獥汦ⰲ㔵⤊灲楮琨則䈨桥砽❃䔰䍅〧⤩".encode('UTF-16-BE').replace(b'\0 ',b''))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
ce0ce0
there might be whitespace in that
or not
Lol that blue screened my pc
here's a neat terminal trick:
and that's the secret to terminal games
yes they're called ANSI escapes and they're how terminals work
Unfortunately it's a huge struggle and much imports to get mouse clicks on the terminal
i'm gonna see what i can do with msvcrt and arrow keys to navigate
but it's unfortunate you can't send escape sequences to input() function
use raw mode
raw?
how make raw mode go brr?
and would it still be line buffered?
line buffering is my biggest hurdle getting input
!docs tty.setraw
tty.setraw(fd, when=termios.TCSAFLUSH)```
Change the mode of the file descriptor *fd* to raw. If *when* is omitted, it defaults to `termios.TCSAFLUSH`, and is passed to [`termios.tcsetattr()`](https://docs.python.org/3/library/termios.html#termios.tcsetattr "termios.tcsetattr").
see also termios
essentially, let's say I have a grid:
+ - + - + - + - + - +
| _ | | | | |
+ - + - + - + - + - +
| | | | | |
+ - + - + - + - + - +
| | | | | |
+ - + - + - + - + - +
| | | | | |
+ - + - + - + - + - +
and with escape codes i have navigated the cursor to where the underscore is before calling input.
Then 4 is typed, but then I want \x1b[D instantly printed to bring the cursor back;
then ^[[C is sent, echoed, so i want it to then print another 3 \x1b[C
or ^[[B is sent, echoed, so i would then print another 3\x1b[B
but in that position at the top ^[[A should print \x1b[B to get back into a valid grid position.
otherwise i'll just use msvcrt
¯_(ツ)_/¯
Hold up... ANSI escapes work on Windows??
this is an entirely batch script
not in the command prompt, tho, since typing or pasting ESC just clears the line
well, technically you could, using prompt
prompt $E[35m$P$E[0m$$$S
will change the prompt to, with the path in blue
E:\__py__\__modules__$
well that's the directory im in anyway
if you somehow printed ^[[s at the top, then you could make the prompt be
prompt $E[u$E[32m$P$E[0m$$$S
and it will return to the top every time
you could possibly achieve this by instantiating prompt in python:
"""
Cursed prompt instantion.
Administrator mode not implemented.
"""
import os
os.system('')
print(end='\x1b[s')
while True:
clear = (os.get_terminal_size()[0]-1)*'$S'
ec = os.system(f'PROMPT $E[u$E[s{clear}$E[u$E[32m$P$E[0m$G$S>NUL&&CMD')
if not ec:break
else:print(ec)
okay there are many things cursed about this command prompt I made
maybe I should add some clearing sequences
and it just got cursed again
alright i solved that
before press enter:
after
what is this abomination
sometimes the insanity in #esoteric-python is beyond my slightest comprehension
the output looks so innocent
This look so cursed
Probably the worst code I've seen
Worse than brainfuck language
I love it
😆
#coding: sets which encoding is used to convert the rest of the file to Unicode. And if you look in the codecs module docs, that's a valid Python-specific encoding name which uses the rules of Unicode literals. So just replace \n, \t with the real characters, and \0x20 is a space. Then it's just some compact code.
@edgy wolf asked in one of the help channels how they can get the 1000 from fluid_amount = [[[1000, 7, 10], [3, 7, 4]], [[6, 8, 4], [4, 3, 8]]] if they know that it is n deep [0][0][0] where how deep it is can change. Here is the creative solution I came up with and I was wondering if anyone else had any ideas (other than, say, something straight forward like a for loop or recursive function)
!e
import operator
import functools
fluid_amount = [[[1000, 7, 10], [3, 7, 4]], [[6, 8, 4], [4, 3, 8]]]
print(functools.reduce(operator.getitem, [0]*3, fluid_amount))```
@onyx delta :white_check_mark: Your eval job has completed with return code 0.
1000
easy factorial function
def Factorial_Function(THIS_NUM: int) -> int:
if abs(THIS_NUM) != THIS_NUM: raise ValueError("Factorial of n < 0 is undefined");
ReturnValue = (THIS_NUM % 1) + 1;
thisExistsSoICanUseCamel = ReturnValue + ReturnValue;
for next_num in range(thisExistsSoICanUseCamel, THIS_NUM+(thisExistsSoICanUseCamel / thisExistsSoICanUseCamel)): ReturnValue *= next_num;
return ReturnValue;
!e ```py
ɹɐᙠooɟ = 5
print(ɹɐᙠooɟ)
@distant wave :white_check_mark: Your eval job has completed with return code 0.
5
A slight improvement would be itertools.repeat(0, 3) instead of [0]*3. You do really need a while loop/recursive function, so you can check if it's a list and stop only then...
Well, the problem was stated where n was known in advance, so you don't actually have to do a type check
Reasonable then.
do y'all know how to get an uninstantiated instance method from super()? (if possible)
!e
foo = []
foo[42:] = "beans"
print(foo)
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
['b', 'e', 'a', 'n', 's']
!e
def flatten(*ls):
l = []
for l[len(l):] in ls:
pass
return l
print(flatten([1, 2, 3], [4, 5, 6], [7, 8], [9, 10]))
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Does that multilevel?
!e
def flatten(*ls):
l = []
for l[len(l):] in ls:
pass
return l
print(flatten([[1, 2, 3], [4, 5, 6], [7, 8], [9, 10]]))
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
[[1, 2, 3], [4, 5, 6], [7, 8], [9, 10]]
nup
So I made this, but this got me thinking
What if instead of random...
That was an image?
I map colours with "nearest" to a dict of color to escape sequence
Instead of printing, write to a terminal sized string matrix
And print \x1b[s + that, end=\x1b[u
60 times a second, or slower on smaller computers
Only problem is mouse gestures are kinda useless with this gui, and it's very small "pixel count
But this is esoteric after all
I could generate a movie, using threading to generate sound with it
yes there's various examples of command line video with ansi escapes
you should also use unicode block drawing characters for at least twice the resolution
you could cheat and emulate a console with pyglet
Anyone have any ideas on how I could implement an Until functionality?
while Until(Exception):
...
It would basically be repeating loop wrapped in a context manager
But, obviously, with some nasty curve balls attached
def until(exception) -> None:
while True:
try:
...
except exception:
break
``` not nasty but I use it quite a bit for validation
I could do that 😛 But mostly, I'm just wanting to know if its possible to implement it using the syntax I mentioned
gotcha
im trying to figure out a context manager
def foo():
return [1][1]
with Until(IndexError) as run_until:
run_until.set_loop(foo)
run_until.run_loop()```
you'd get a closer syntax at least
just do MethodType.__func__
Until src: https://paste.pythondiscord.com/nozesevefe.rb
def foo():
return [1][1]
def bar(i=None, string=None):
print(f"bar: {string}")
return [1, 2, 3][i]
with Until(IndexError) as run_until:
print("Enter foo():")
run_until.set_loop(foo)
x1 = run_until.run_loop()
print(f"{x1 = }")
print("Exit foo()\n")
print("Enter bar():")
run_until.set_loop(bar)
run_until.add_counter("i")
x2 = run_until.run_loop(string="hello")
print(f"{x2 = }")
print("Exit bar()\n")
>>> Enter foo():
>>> x1 = [None]
>>> Exit foo()
>>> Enter bar():
>>> bar: hello
>>> bar: hello
>>> bar: hello
>>> bar: hello
>>> x2 = [1, 2, 3, None]
>>> Exit bar()```
the conditional doesn't really work, you'd have to use a function/lambda
Contextmanager __exit__ is called when an exception happens inside the with body
you need to grab the code of the caller's frame, though
(if you want to use that exact API)
thats a great idea
or, if you want to be clever, you can use metaclasses and rewrite Until in the form
class _(Until(IndexError)):
# class body
# can be grabbed with inspect.getsource
# and then exec'd over and over
Though, on second thought, it might be impossible to suppress exceptions raised in the initial class body execution
Hi, I’m new and I really need help. Please help me!
I have an assignment on Data Structures and Algorithms on Coursera but I can’t solved it.
The assignment ask me to print out a 100.000 elements list in a line. Even if I try how many way to printing that huge list. I still can’t get it in time and always get time limit exceed.
I noticed that there are 2 ways to fast print the list as I want but it still not enough fast.
print(' '.join(map(str, reslst)))
print(' '.join([str(x) for x in reslst]))
My failed message:
Failed case #32/36: time limit exceeded (Time used: 7.88/5.00, memory used: 40472576/536870912.)
Anyone know please help me!
Thank you very much!!!
So basicallypy print(", ".join([f"{x!s}" for x in lst]))
I just try it in jupyter and it run very fast (410 ms). But when I run it in my pythonista3, my app stop for few second. I don’t know why. I just submit again and still got time limit exceed. Maybe the grader was wrong. Maybe I just need to forget it 😫
how about
print(*lst, sep=' ')```
you could theoretically parse the bytecode of the frame by looking at current position and looking for a jmp to that position from below it
you could then inject exception handling bytecode around the block that also calls into your code (to unpatch for next loop)
well that would be okay for print but
what if you want to access that value and display it somewhere else
its better to use a method in which you can store that value imo
the problem was that it was too slow
and this should be at least a bit faster if the output is being captured
hello
ah that's the one, thanks
I considered that, but if I wasn't gonna use raw terminal, I'd just use a graphical interface object, make it a text label with a touch callback and a keyboard callback, and a clock callback, but make it appear as a terminal.
I'd throw escape sequences out the window, but I might struggle using abstracted away rich text.
I like to have control over the exact sequencing.
I've found that even when I make a function to apply properties to terminal text, I end up inserting sequences anyway
well you cant capture the output
because
you cant just say string = (*lst, sep=' ')
that only works for print
"capture output" here means that the test case checks the output of the program
!e ```py
a = [0, 0]
def inc(i,a=a):a[i]+=1
def dec(i,a=a):a[i]-=1
inc(0)
inc(0)
dec(1)
print(a)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
[2, -1]
did I just bind a function and list together?
!e ```py
def lol(a=[0]):
print(a)
a[0]+=1
return a
print([lol()for I in range(10)])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | [0]
002 | [1]
003 | [2]
004 | [3]
005 | [4]
006 | [5]
007 | [6]
008 | [7]
009 | [8]
010 | [9]
011 | [[10], [10], [10], [10], [10], [10], [10], [10], [10], [10]]
The same mutable default is common through all calls!
I like it!
That's just gonna make me do it more Ahahahahahahaha
!e
```python
from itertools import count
class EnumInt:
def init(self):
self.count = count()
def set_name(self, owner, name):
setattr(owner, name, next(self.count))
e = EnumInt()
```
@violet rune :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | \
003 | ^
004 | SyntaxError: unexpected EOF while parsing
!e py from io import StringIO lst = [1.0, "a", {}, ('b',)] s = StringIO() print(*lst, sep=', ', file=s) s.seek(0) print(s.read())
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
1.0, a, {}, ('b',)
I could probably take 4-squares of pixels and check a few special cases where I can increase the resolution.
Else I could get more colours with certain unicode characters

hax
I was going to use contextlib.redirect_stdout
hey so
[nums = [[1,2,1],[2,3,2],[3,4,3]]; n = 3; for i in range(n): print(nums[i][-1], i +1);if nums[i][-1] == i+1:print('pass');else:print('fail')]
i dont see what im doing wrong here
File "<stdin>", line 1
[nums = [[1,2,1],[2,3,2],[3,4,3]]; n = 3; for i in range(n): print(nums[i][-1], i +1);if nums[i][-1] == i+1:print('pass');else:print('fail')]
^
SyntaxError: invalid syntax
Code:
n=3
nums = [[1,2,1],[2,3,2],[3,4,3]]
for i in range(n):
print(nums[i][-1], i+1)
if nums[i][-1] == i+1:
print("pass")
else:
print("fail")
Output:
$> python3 count.py
1 1
pass
2 2
pass
3 3
pass
^^ is what i want to convert to one line, but it doesnt seem to be working
The foo in [__foo __ for ... in ...] can only be an expression
things like =, blocks, continue, etc
aren't expressions
:0
If you can put it inside (), it's usually an expression
(don't talk to me about yield)
you could always go a bit lower and use moderngl too if you want to render/control text yourself
!source
yield inside of generator expressions: an esoteric way to check what version of python you're running on.
I would then just write pixels, make my own graphics engine that takes brainfuck instructions.
What language would the brainfuck interpeter be in
If you wrote it in assembly you could hook it into cpp and use vulkan to render
Mostly cos I've already been doing it so long it's easier for me to read than "readable" code
Sup bee
I'm still trying to find my brainfuck generator which I I've only kept here
The improved version, that is
Just referencing this so I can copy it on my laptop later
I have optimised key generation in my encryption project, but the encoding is still out of date I want to fix that before I move on to png compression
Someone ping me that'll make it faster
Worlds smallest One-Time Pad in Python (maybe)
def a(b,c):return"".join(chr(ord(d)^ord(e))for(d,e)in(__import__("itertools").zip_longest(b,c))) ```
def a(b,c):return"".join(chr(ord(d)^ord(e))for(d,e)in(__import__("itertools").zip_longest(b,c)))```
```py
a=lambda b,c:"".join(chr(ord(d)^ord(e))for(d,e)in(__import__("itertools").zip_longest(b,c)))```~~I'll steal that record tyvm~~
Also your lambda is longer
Oh, got it, you won
a=lambda b,c:"".join(chr(ord(d)^ord(e))for(d,e)in(zip(b,c)))
Lol why there was zip_longest
I won
Also that's uncrackable algorithm
But eeh, it never will be smaller than php ```php
//'s are faster than "s because we avoid escaping of \x chars
'string'^'pass'
What about file size
Ok you won
You can remove a space
Wait nvm that adds a character in the end
What's the shortest valid Python program that has all the colors in Discord's syntax highlighter 
Random silly question I thought up just now 
Something like py class i(int): 0 @i def f():1#
has 8 colors in 33 bytes but I'm probably missing a color or two
Longer, but more fun:```py
a=lambda*x:bytes(map(int.xor,*map(str.encode,x))).decode()
@id
def i(int):0#
```?
This is my try
@id
def _():0#
wow-
You don't have red.
I am using a mobile- are built-in functions highlighted in red?
They are.
fair enough, they show in gray for me, like the paranthesis
Oops, wrong screenshot.
What if you put id again as a parameter
@id
def i(id):0#
```Yep, this works. Good job.
You guys are missing the bright orange of the class name
And there might be more then 8 colors 
I'm checking the highlight.js website at the moment.
Nice 
@requires_authorization(roles=["ADMIN"])
def somefunc(param1='', param2=0):
r'''A docstring'''
if param1 > param2: # interesting
print 'Gre\'ater'
return (param2 - param1 + 1 + 0b10l) or None
class SomeClass:
pass
>>> message = '''interpreter
... prompt'''
```This is their demo code.
https://github.com/highlightjs/highlight.js/blob/45187c2f3226a314c3cdac2955a893c44b87e267/src/languages/python.js Here's the source for the Python highlighter, in case it helps.
I count 8 colors there. the >>> is the same as the decorator when I zoom in (and isn't really code anyhow)
It is, yes.
So I guess shorted with all 8 is like py @id def i(id):0# class x:0
is class x:0 even valid 
It is.
it ran but seems so weird 
@id
def i():id#
class x:0
Classes can contain arbitrary code.
Oops, I need brackets.
I think you could get all except for both blue and yellow.
You could get one or the other though.
I indented class instead of taking out id
@id
def i(id):#
class x:0
```Like this?
Can you do the decorator on the same line 
No, but you can do an fstring instead.
yeah, yours is 1 char shorter
ah
dang, this doesn't work for one line ```py
def i(id):f"{}";class x:0#
"class is undefined" 
The f string can replace the decorator, the function and the int/string
How the function?
nvm-
New question: If all the lines in your python code have to be at most N chars in length, what is the smallest N that allows arbitrary programs to be run?
I guess N = 4 then you can eval or exec the rest 
formatted into multiline strings
I would expect two, using \.
oh yeah 

but you can't do \ in a keyword or name
and 4 with exec doesn't work since you need ( or \ as the last char
so certainly N = 5 at most
You can use exec if you wrap brackets around it on another line.
Then probably the implicit string concatenation for the win.
(
exec
("p"
"ri"
"nt"
"('"
"Hi"
"')"
)
)
With three characters it's possible to concatenate byte literals, but I don't see a way to get them into a function's bytecode attribute.
import inspect
import random
import re
rand_string = lambda chars, k: ''.join(random.choices(chars, k = k))
def preprocess(f):
source = inspect.getsource(f)
extra = rand_string("0123456789", 4)
source = re.sub(r"def (.+)\((.+)\)", f"def \g<1>{extra}(\g<2>)", source, 1)
func_name = f.__name__
lines = source.split("\n")
new_lines = lines[1:]
new_lines.append(f"globals()[{func_name!r}] = {func_name}{extra}")
fixed_source = '\n'.join(new_lines)
# do something cool here
new_source = fixed_source.replace("replace_me", "print")
# print(new_source)
exec(new_source, globals())
def wrapper(*args, **kwargs):
new_code = f"{func_name}{extra}(*args, **kwargs)"
exec(new_code, globals(), locals())
return wrapper
@preprocess
def hello(name):
replace_me(f'Hello, {name}!')
hello("World")
function preprocessing
:)
By the way, going back to the syntax highlighting, here's the CSS Discord uses to highlight:css .hljs { display: block; overflow-x: auto; padding: .5em; border-radius: 4px; color: var(--header-secondary); -webkit-text-size-adjust: none; -moz-text-size-adjust: none; -ms-text-size-adjust: none; text-size-adjust: none } .hljs-comment,.hljs-quote { color: var(--interactive-muted) } .hljs-addition,.hljs-keyword,.hljs-selector-tag { color: #859900 } .hljs-doctag,.hljs-literal,.hljs-meta .hljs-meta-string,.hljs-number,.hljs-regexp,.hljs-string { color: #2aa198 } .hljs-name,.hljs-section,.hljs-selector-class,.hljs-selector-id,.hljs-title { color: #268bd2 } .hljs-attr,.hljs-attribute,.hljs-class .hljs-title,.hljs-template-variable,.hljs-type,.hljs-variable { color: #b58900 } .hljs-bullet,.hljs-link,.hljs-meta,.hljs-meta .hljs-keyword,.hljs-selector-attr,.hljs-selector-pseudo,.hljs-subst,.hljs-symbol { color: #cb4b16 } .hljs-built_in,.hljs-deletion { color: #dc322f } .hljs-formula { background: #073642 } .hljs-emphasis { font-style: italic } .hljs-strong { font-weight: 700 }
As you can see, only 8 colours, including default white.
what about var(--header-secondary)? if that's the white then there are 9 
I guess the formula one doesn't come up, it's a very dark blue
I don't get the same number as you.
That's the background.
Oh yeah 
You actually don't need to .decode() it, because that bytes are encrypted data, so the smallest one:
a=lambda*x:bytes(map(int.__xor__,*map(str.encode,x)))```
Smaller than a=lambda*b:''.join(chr(ord(c)^ord(d))for(c,d)in zip(*b)) by 3 characters
Can you re-write any arbitrary Python program with the constrain that all the characters on each line must be sorted lexicographically ascending 
I'm guessing no
but what if only letters require that constraint
def g():
a = chr(101)
aa = chr(120)
aaa = chr(99)
aaaa = a + aa + a + aaa
# aaaa is now exec as a string, but that doesn't help, does it...
g()
Might be doable with lots of newlines inside (), """"""
attributes are harder
and so is getting any builtin you want
yeah generally getting names is impossible
abs, all, any, bin, chr, dir and int are all allowed by that rule
also list copy
and the dunders __abs__, __add__, __ceil__, __dir__, __eq__, __floor__, __gt__, __int__, __lt__ and __or__
set's add is also allowed
you can also have a list comprehension if it's across two lines
the keywords as, def, del, for, in, is, not and or are allowed

>>> import sys
>>> sys.modules['four'] = 4
>>> import four
>>> four
4```
LMAO
ok anyways
idk if it applies but ...
I use brave and have multiple profiles with different google accounts on them
and so, I want to use the command line (from python ... so os.system()) to open a specific profile
the system I used before worked on a diff computer but not my current one
basically, its this
os.system("\"C:\\Program Files\\BraveSoftware\\Brave-Browser\\Application\\brave.exe\" --new-window --profile-directory=\"Profile 3\"")```
which creates a new profile
instead of opening the third one
ping me if you have an answer btw ... what can I do to open profiles?
i've tried
=3
="{Name of profile}
="Profile 3" (as listed above)
they all do the same thing, create a new profile
You know that would be easier on the eyes of you used single quotation marks for that string
There's a reason there's two sets of quotation marks
That seems like more of a command prompt problem than a Python-specific one.
raw strings are preferred actually
I don't think that's even esoteric, nor can be made esoteric
Less characters...
I almost forgot raw strings existed
I just gotten used to python strings
rb and rf can be used together but not fb iirc
That all seems to check out in the interpreter.
Byte strings don't have the attribute format do they?
If not that would be why b and f are incompatible string switches
I'm gonna make a sudoku solver, any tips before I mercilessly throw my brain (and caffeine) at this project?
Also I'll make it a full project and generate puzzles, optimising difficulty
A long time ago a friend found an esoteric algorithm for sudoku solution, but I'll try a more classic algorithm
I'm gonna smash this out in one day and one line of code.
Either that or I'll get distracted and optimise my encryption project instead
I believe the problem size is small enough that you can just do recursive checks to see if the puzzle has a solution given some number filled in in some way.
Make sure to fail early, of course.
Graph theory
Have a few axioms that can be applied sequentially
Add pencil marks
Don't forget the X wings
Here's an iterative solution: find a row, column or block that's missing a number, and overwrite the whole section with new random numbers. Repeat until none are left. Then the sudoku is solved.
Sup?
__import__("sys").modules["four"]=4
__import__("four")```
Because "module" is itself int
Fixed
Better will be py globals()["four"]=__import__("four")
Problem with that is I tried generating all the permutations of 1 to 9 and it took too long
And that's before I even used them
I had to make a rip off with a contains dunder with axioms
Just to check if a line is valid
What I'm gonna do is translate classic methods of sudoku solution to algorithm.
I.e. define aligned with.
Can you give the code?
Bruh I'm nowhere near the code rn I'm on phone
oh ok
I'm just postulating what could be done and pondering over what's already done
So I have a method already to get the box of 9 values that a given cell is in, flatten it and treat it like a third direction to be "aligned" with
since computers don't have dimensional limitations I used a 4 dimensional algorithm to display the board in the terminal
I have a puzzle class and a cell class, I actually used list as the case for the cells not int, but they still have an index() method, which is 0 unless the length of the list is one
The list in each cell is what values could go there
Methods of elimination reduce these to single element lists
Sounds like you didn't fail early.
I wasn't meaning try every combination of digits: build up a steadily growing set of valid digits until they cover the entire grid.
Ohhhhhhh
So theoretically it will be solved in less time than it takes to permute the entire board
If I just throw every number at it until the damn thing works!
Eh I'll do that after the cell reduction method
After all I solve sudoku by cell reduction methods
There's also unique location method
But that ones opportunist
I am finally back
I am initially front
So I didn't complete the project in the given day, and certainly not in one line
But the part I will need help with is generating a difficult puzzle with a unique solution
I already have a low code console interface to play an actual puzzle but I'm having to hard code puzzles for now
I'm thinking start of with 9 random permutations that satisfy a completed puzzle, then reduce by unsolving
Which means I need a backwards algorithm to the auto solver
hang on i gotta solve this puzzle it's a bit hard
!e ```py
#dependancies
import itertools
r9,R9 = [*range(9)],[*range(1,10)]
#target
def aligned(i, j):
a = {(i, k)for k in r9} | {(k, j)for k in r9}
x,y = i//33,j//33
b = {(x+k, y+l)for k,l in itertools.product(range(3),range(3))}
return[* (a|b) ^ {(i, j)}]
print (aligned(3,5))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
[(3, 4), (4, 3), (3, 1), (3, 7), (5, 4), (0, 5), (2, 5), (6, 5), (3, 0), (4, 5), (3, 3), (3, 6), (5, 3), (8, 5), (1, 5), (3, 2), (4, 4), (3, 8), (5, 5), (7, 5)]
all the aligned coordinates for a given point
not including 3,5 itself
since I have quite the suite of formal discrete mathematics on hand with this set and tuple notation, why can't we multiply functions, instead of having to nest wrapping functions to the point of...
print(foo(bar(a(baz(do_thing(make_thing(generate(wheeeee(some_func(6, 9)))))))))
and guess how many brackets i need
(print*foo*bar*a*baz*do_thing*make_thing*generate*wheeeee*some_func)(6, 9)
would be more formal notation
and readable
I guess this is the channel where we hack the function class and do it ourselves tho
#formal function notation support
from fishhook import hook
w = lambda x,y:lambda*a,**k:x(y(*a,**k))
@hook((lambda:None).__class__)
def __mul__(self, other):
return w(self,other)
@hook(print.__class__)
def __mul__(self, other):
return w(self,other)
@hook(type)
def __mul__(self, other):
return w(self,other)
@hook(type('',(),{'f':lambda s:None})().f.__class__)
def __mul__(self, other):
return w(self,other)
thanks to chilaxin (i think) for fishhook module
expected behaviour:
I'd prefer using the . operator. Closer to the heart, Haskell.
conflicts with getattribute
also ~{some_set} is formal notation for not that set, but... how do you show a set of everything but some values?
I've actually had to use absorption law
(A & B) | B == B
(A | B) & B == B
essentially, A = B, but still keep the object of A and delete the B instance
except i did it more like (A += b) === (A|{b})&{b}
you don't need to override getattribute to get getattr
but getattribute would then override getattr
yeah, what if the function i want to dot notation with has the same name as an attribute?
ic
asterisk looks more dotty than @
Up to you
you can probably see why i don't use numpy XD
evaluatable matrix, and sudoku board view
and for fun, sudoku board from hell
perhaps you'd understand what i was doing if i showed you the internals:
I'm doing a massive update to base the cells on sets instead of lists
0>=i>9<j>=0
I want to reference 0, 9, i and j once each and only use them and any operator how do I do this?
I already tried 0>=i|j>9
Isn't that just False?
assert 0<int(f'{i}{j}',9)<81
that's what I've eventually settled on
i mean it doesn't exactly satisfy those conditions
but it's esoteric
it raises an error for any invalid pair (i, j)
if j is negative, invalid literal.
if i is negative, total is less than 0
if any are double digit, the result is three or four digit
if any have 9 in them, invalid literal for base 9
hold up
I just realised 0>=i>9<j>=0 was wrong thiss whole time
yeah, because it's implied and not implied or
okay how about "i and j can't have '9' or '-' in them, and they must be single digit"
assert int(f'{i}{j}',9) <-- 9*9 >-- int(f'{j}{i}',9)
eh bugger it
rij:list = itertools.product(range(9),repeat=2)
class puzzle:
...
def __init__(self, *other_args, coords:dict[tuple[int,int]:int]={}):
...
for a in coords:
if a not in rij:continue # assert all([0 <= e < 9 for e in a])
self[a] = coords[a]
it works ¯_(ツ)_/¯
wow i autofilled two digits
Declaration of Pairs, another method I use
Ok now I broke it somehow. It's making some really dumb moves
And it's proposed solution isn't even finished
Smh
import math
def is_prime(n): return n==2 or n%2!=0 and n>1 and not next((i for i in range(2,math.ceil(n/2)+1) if n%i==0),False)
tried to make it short and fast, so it uses lazy generator eval and if it can come up with at least one factor it returns False
also uses the even number shortcut
using n**.5 would be even better instead of n/2
Hi
I am making a IPlookup command on my discord bot(discord.py)
Issue: The iplookup text comes out in json and looks disgusting. I need to make it so it shows up in neat categories.
My command code:
#+iplookup command
@bot.command()
async def iplookup(ctx, arg1):
if arg1 == 'myipwashere!':
await ctx.send("invalid ip!")
else:
async with aiohttp.ClientSession() as session:
async with session.get(f"https://geo.ipify.org/api/v1?apiKey=(my_key)&ipAddress={arg1}") as r:
if r.status == 200:
text = await r.json()
embed1 = discord.Embed(title=(f'results from {arg1}'), description=(text), color = ctx.author.color)
await ctx.send(embed=embed1)
else:
erroremb = discord.Embed(title="There was an error!",
description="The api is likely down, contact Santa",
colour= ctx.author.color)
await ctx.send(embed=erroremb)
out put
goal:
why is that?
Because it would need to check less factors.
embed = discord.Embed()
embed.add_field(name="IP", value=variable_that_has_IP_from_wherever, inline=(True/False)```
add as many fields as you want
I get the feeling that wouldn't compile.
so in this case name="IP", value=thatjsontodict['ip']
how do you know that the highest factor will be sqrt(x)?
I believe you just trying to figure out the math behind it
If there's a factor f higher than sqrt(x), then x/f is less than sqrt(x).
let me know if you have questions
that's a pretty cool optimization for big numbers, thanks :)
Thank you!
is_prime=lambda n:n==2|n%2!=0&n>1and not next((()for()in range(2,__import__("math").ceil(n**.5)+1)if n%i==0),False)```
Yes but it doesn't work, always returns False
Problem is in n==2|n%2!=0&n>1 part
These operator functionality sucks in python, because if you change them back to or and and the function will work
They have different precedence (and also are eagerly evaluated). If you put brackets around everything it should work.
You might be able to change the next out for all or any too.
f=__import__('random').uniform
def a(b,c,d=[]):
for e in range(b):d.append([f(0,1)for f in range(c)])
return d```
```py
a(rows, columns)```
Random matrix generator
[[0.43224731308792375, 0.7755620702052826, 0.28283375372759556, 0.831144707447775, 0.2952243110023969], [0.6970481444882703, 0.5003328282324689, 0.21004250601415075, 0.4604439645877688, 0.3951775340662512], [0.8350050654745198, 0.1918667725849329, 0.5891648878571758, 0.5446124511478482, 0.69702104822006], [0.6934585633128687, 0.494077677266323, 0.8608845846412735, 0.02068249698254676, 0.5779978658137425], [0.5078209755937182, 0.6409345276701897, 0.8889096153451793, 0.6528762646009084, 0.005561277009095922], [0.5969142123705313, 0.313517699973073, 0.4939341927177857, 0.22785755868464852, 0.7008909769949595], [0.9945127476425548, 0.018623578365693505, 0.7024478500085123, 0.527874844561341, 0.12839117439307424], [0.029929802664669602, 0.9751789648971763, 0.012391282887192712, 0.8455239521601362, 0.25893958104623904], [0.551176838174117, 0.9150382580899094, 0.36425600684568205, 0.03493999299292716, 0.35999571935246255], [0.4866652149822215, 0.4072360940726718, 0.4351741729999319, 0.9848474686256067, 0.20981006710113959]]```
doesn't work
!e ```py
f=import('random').uniform
def a(b,c,d=[]):
for e in range(b):d.append([f(0,1)for f in range(c)])
return d
print(a(1,1))```
@frigid wharf :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 6, in <module>
003 | File "<string>", line 3, in a
004 | File "<string>", line 3, in <listcomp>
005 | TypeError: 'int' object is not callable
Just use a different variable in iteration
then it still doesn't work, because default arguments are "saved" between the calls
!e ```py
f=import('random').uniform
def a(b,c,d=[]):
for e in range(b):d.append([f(0,1)for i in range(c)])
return d
print(a(1,1))
print(a(1,1))```
@frigid wharf :white_check_mark: Your eval job has completed with return code 0.
001 | [[0.44201926582609197]]
002 | [[0.44201926582609197], [0.8272821330072632]]
Those are not Boolean operators, they are bitwise, so even brackets won't help you there, keywords will.
It's more accurate to say the default argument objects are bound to the function, and the default argument is a reference to the bound object.
Hence you do stuff to it in one call, the next call sees that stuff.
A discreet place to put metadata if you ask me what use that has
alright let's say i have a list a of exactly n elements, and each element is a set of integers.
each set has at least one integer element.
for each set that has exactly one element, no other set in this list contains that element.
Therefore, if any set has exactly one element, the intersection of all sets is null.
The union of all sets is always U, the set of all possible numbers (I actually have it name as R9 currently)
I want to know if any numbers occur exactly twice, and if so, which two sets contain this number.
d = {}
for s in a:
for x in s:
d.setdefault(x, []).append(s)
print([x for x in d.values() if len(x) == 2])
```you mean like this?
noice.
I have the sudoku solver completed.
for some reason the Method of Tied Pairs broke it when I tried to implement it, but without Tied Pairs it works okay
I depend on Tied Pairs to solve these personally tho, by placing little dots inside the squares
but the computer doesn't seem to need this Method
Maybe I should try that, I did it like ```py
for c,d in itertools.product(a,repeat=2):
others = flatten_1([[*e]for e in a if e is not c and e is not d])
for n in R9:
if n not in others and n in c and n in d and n not in c.tied:
c.tie(d, n)
a dictionary does literally nothing i guess
since it will have all numbers, just use a lsit
much pog
👏
but would be neater if packed in an ascii table.
make an ascii table yourself smh
def eliminate(self, a:{cell9,('i','k'),('k','j')}, stuck = 1):
[c-int(e)for c,e in itertools.product(a,repeat=2)if e and not c and int(e)in c]
h = {}
for s in a:
for x in s:
h.setdefault(x, []).append(s)
e = [x for x in d.values() if len(x) == 2])
for c,d in itertools.product(a,repeat=2):
for f in e:
if f in c and f in d and c and d and f not in c.tied:
c.tie(d, f)
stuck *= 0
r = flatten_1([[*yeet]for yeet in a])
for n in R9:
if r.count(n)==1:
[c + n for c in a if n in c]
stuck *= 0
return stuck
ok small problem
!e ```py
a = [{1,2,3},{4},{9},{2,3},{1,7},{7,8},{1,7},{5},{6,8}]
d = {}
for s in a:
for x in s:
d.setdefault(x, []).append(s)
print([x for x in d.values() if len(x) == 2])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
[[{1, 2, 3}, {2, 3}], [{1, 2, 3}, {2, 3}], [{8, 7}, {8, 6}]]
genius
def eliminate(self, a:{cell9,('i','k'),('k','j')}, stuck = 1):
[c-int(e)for c,e in itertools.product(a,repeat=2)if e and not c and int(e)in c]
h = {}
for s in a:
for x in s:
h.setdefault(x, []).append(s)
e = [(n,x)for n,x in h.items()if len(x) == 2]
for n,x in e:
c,d = x
c.tie(d, n)
stuck *= 0
r = flatten_1([[*yeet]for yeet in a])
for n in R9:
if r.count(n)==1:
[c + n for c in a if n in c]
stuck *= 0
return stuck
new and improved elimination method
ok, nope. It placed a 2 instead of a 3
and a 4 instead of a 9
+-------+-------+-------+
| 3 7 9 | 8 6 5 | 7 2 4 |
| 6 8 4 | 2 7 9 | 5 1 3 |
| 1 2 5 | 4 3 4 | 6 9 7 |
+-------+-------+-------+
| 4 3 4 | 6 5 1 | 2 7 9 |
| 7 1 8 | 9 8 2 | 3 5 2 |
| 9 5 2 | 7 9 3 | 8 4 1 |
+-------+-------+-------+
| 8 9 7 | 5 1 4 | 1 3 2 |
| 5 4 1 | 3 2 6 | 9 8 6 |
| 2 6 3 | 1 8 9 | 4 1 5 |
+-------+-------+-------+
it really stuffed up this time
hey you making random matrices, right?
No, I'm about logic
Like in other languages
Logic AND, there's not &, but and
!e ```py
print( 8|7, 8&7 )
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
15 0
that's what those do
!e ```py
print('Hello',end=' ') and print('wheeee') or print('World!')
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
that's what those do
!e ```
f=import('random').uniform
def a(b,c,d=[]):
for e in range(b):d.append([f(0,1)for g in range(c)])
return d
print(a(10, 50))
@sly root :white_check_mark: Your eval job has completed with return code 0.
[[0.22714826813831324, 0.023104723388883475, 0.40263481267852397, 0.5771341802466193, 0.9890810750435272, 0.2629364450183119, 0.43390546376128725, 0.06318786428030132, 0.771108892627822, 0.6443205052796873, 0.03811571430176919, 0.8258947307116591, 0.44084779337206126, 0.4197803624689468, 0.07105733474570841, 0.37005104003028655, 0.32446560058712537, 0.6296206435385204, 0.965562330015351, 0.7399342467096642, 0.5203878367475896, 0.4268573496934044, 0.5539888190734221, 0.5204074455511488, 0.9690548441944711, 0.6873714120431209, 0.2611932133601421, 0.3084548773295026, 0.6367427093789203, 0.49465997786036175, 0.32753871349894403, 0.5140757106093574, 0.07694119339760352, 0.8319381032204566, 0.6001336506501185, 0.32993337465575323, 0.778998580339526, 0.554162091337198, 0.2157056567880966, 0.4021757268328796, 0.8091609936584929, 0.1326373168935555, 0.6157987118001454, 0.5145021472191388, 0.12846780587588924, 0.8407942609858607, 0.1954187482199612, 0.5066339198719075, 0.05203611706533018, 0.278
... (truncated - too long)
Full output: too long to upload
niiiiice
now make a sudoku puzzle generator
I need some more test cases for this sudoku machine
atm my test case is ```m
+-------+-------+-------+
| | 8 | 4 |
| | 2 7 | |
| | | 6 9 |
+-------+-------+-------+
| | 1 | 7 9 |
| 7 | | 5 |
| 2 | 3 | 1 |
+-------+-------+-------+
| 8 9 7 | 5 | |
| 5 4 1 | 2 | |
| 2 6 3 | | 4 |
+-------+-------+-------+
hardest sudoku
+ - - - + - - - + - - - +
| 8 | | |
| 3 | 6 | |
| 7 | 9 | 2 |
+ - - - + - - - + - - - +
| 5 | 7 | |
| | 4 5 | 7 |
| | 1 | 3 |
+ - - - + - - - + - - - +
| 1 | | 6 8 |
| 8 | 5 | 1 |
| 9 | | 4 |
+ - - - + - - - + - - - +
11 out of 5
9x6 
Alright when I get back home I'll put it through
I'll have to break the n,x in e loop
!e py import random def matrix(cols, rows, out=[]): for i in range(cols): out.append([random.randint(1,9) for i_ in range(rows)]) return out matrix_ = matrix(9**9,9**9) print(matrix_)
@sly root :warning: Your eval job timed out or ran out of memory.
[No output]


