#esoteric-python

1 messages · Page 144 of 1

cloud fossil
#

The eleven characters programming language: Python

lime bane
#

Now that's a good slogan

cloud fossil
#

Actually thirteen if you count space and newline

#

Wait

#

!e

print(len("while1-=[]:\n "))
night quarryBOT
#

@cloud fossil :white_check_mark: Your eval job has completed with return code 0.

13
cloud fossil
#

Yes

#

Thirteen

lime bane
#

Is lambda calculus also turning complete?

lime bane
#

Now for the ultimate obstructification:
You could use exec and input every character of the original code like this:

exec(chr(1+1+1+1+1+...)+chr(1+1+1+...)+...)
#

!e ```py
x = set(list("exec(chr(1+1))"))
print(x)
print(len(x))

night quarryBOT
#

@lime bane :white_check_mark: Your eval job has completed with return code 0.

001 | {'c', 'e', 'r', ')', '+', '1', '(', 'x', 'h'}
002 | 9
lime bane
#

This is borderline cheating but still valid python code. This way you could actually write any characters and execute them.

#

And also this is less fun

#

!e py exec(chr(1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+chr(1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+chr(1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+chr(1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+chr(1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+chr(1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+chr(1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+chr(1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+chr(1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+chr(1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+chr(1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1))

night quarryBOT
#

@lime bane :white_check_mark: Your eval job has completed with return code 0.

Hi
fleet bridge
#

yes
i can use only 1 to construct all integers
for quick scripting i used 0-9, but it can be constructed with 1s

fleet bridge
lime bane
#

But as I said, also more boring

#

It is astonishing how flexible this language is

cloud fossil
#

And it didn't mean to

lime bane
#

!e py exec(chr(111+1)+chr(111+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+11)+chr(111+1+1+1+1+1)+chr(11+11+11+1+1+1+1+1+1+1)+chr(11+11+11+1)+chr(11+11+11+11+11+11+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+chr(111)+chr(11+11+1+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1)+chr(111)+chr(111+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1)+chr(11+11+11+1)+chr(11+11+11+1+1+1+1+1+1+1+1))

night quarryBOT
#

@lime bane :white_check_mark: Your eval job has completed with return code 0.

Hello World
lime bane
#

I would say it is also quite fortunate that exec and chr together only have 5 different characters

#

!e ```py
def get_num2(n):
g_111 = n>=111
rest = n%111
whole_11s = rest//11
rest_rest = rest%11
p_111s = ['111'] * g_111
p_11s = ["11"]*whole_11s
p_1s = ["1"]*rest_rest
nums = []
nums += p_111s
nums += p_11s
nums += p_1s
#print(nums)
return "+".join(nums)

def obf(text):
numbers = [ord(x) for x in text]
chars = [f"chr({get_num2(n)})" for n in numbers]
txt = "+".join(chars)
result = f"exec({txt})"
return result

print(obf('print("Hello Discord")'))

night quarryBOT
#

@lime bane :white_check_mark: Your eval job has completed with return code 0.

exec(chr(111+1)+chr(111+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+11)+chr(111+1+1+1+1+1)+chr(11+11+11+1+1+1+1+1+1+1)+chr(11+11+11+1)+chr(11+11+11+11+11+11+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+chr(111)+chr(11+11+1+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1)+chr(111+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11)+chr(111)+chr(111+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1)+chr(11+11+11+1)+chr(11+11+11+1+1+1+1+1+1+1+1))
lime bane
#

I'd like to introduce you to exchr(+1):
Python, but worse

earnest wing
#

Have you heard of exc("%)?

lime bane
#

No

earnest wing
#

Hold on nevermind that doesn't necessarily work

#

Okay with =; it works

#

exchr(+1) and its sister language exc('%=;)

#

basically a bunch of assignments inside exec

sudden osprey
#

how do you get numbers (other than 0 or 1)? (or do you not need them?)

earnest wing
#
e=''=='%';ee=e=='';exec('eee=%c%%c%%%c'%ee%e%ee)```

`eee` is now 101
sudden osprey
#

aha

earnest wing
#

you can concat + modulo to get p much any number

#

then pass those to %c

#

then exec

#

I wonder actually

#

could you avoid having to use ;?

sudden osprey
#

I was thinking something like exec("%c"%((""=="")+(""=="")+(""=="")+...))

earnest wing
#

That works too

#

I forgot we had parens

#

so yeah you should be able to, right?

lime bane
sudden osprey
earnest wing
#

Use 1 and %?

#

To replace = and +

#

or is that not enough to reach most chars

lime bane
#

exec('%c%c'%(111, 111))

#

exec('%c'%(111+1)+'%c'%(11+11))

lime bane
earnest wing
night quarryBOT
#

@earnest wing :white_check_mark: Your eval job has completed with return code 0.

4
lime bane
earnest wing
#

!e let me test:

s = set()
for i in range(1, 1000):
    for j in range(i, 1000):
        x = int("1"*i)
        y = int("1"*j)
        z = x % y
        if z < 256:
            s |={z}
print(len(s))
night quarryBOT
#

@earnest wing :white_check_mark: Your eval job has completed with return code 0.

4
earnest wing
#

too bad

#

I wonder...

lime bane
icy frigate
#

Yeah

lime bane
#

Ok

icy frigate
#

But the hello world output

lime bane
#

!e py print(chr(111+1)+chr(111+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+11)+chr(111+1+1+1+1+1)+chr(11+11+11+1+1+1+1+1+1+1)+chr(11+11+11+1)+chr(11+11+11+11+11+11+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+chr(111)+chr(11+11+1+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1)+chr(111)+chr(111+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1)+chr(11+11+11+1)+chr(11+11+11+1+1+1+1+1+1+1+1))

night quarryBOT
#

@lime bane :white_check_mark: Your eval job has completed with return code 0.

print("Hello World")
earnest wing
#

!e let me test:

for q in range(1,10):
    s = set()
    for i in range(1, 1000):
        for j in range(i, 1000):
            x = int(str(q)*i)
            y = int(str(q)*j)
            z = x % y
            if z < 256:
                s |={z}
    print(q, len(s))
night quarryBOT
#

@earnest wing :x: Your eval job timed out or ran out of memory.

001 | 1 4
002 | 2 4
lime bane
#

!e ```py
exec('print("Hello World")')

night quarryBOT
#

@lime bane :white_check_mark: Your eval job has completed with return code 0.

Hello World
lime bane
#

So the thing in the parenthesis gets evaluated to code, that is then run

lime bane
#

@earnest wing Do you have a link to a list with all the %format characters? Whenever I google it, it just says use f-strings instead

icy frigate
#

where you can find what each alphabet is represented by?

lime bane
#

Do you know what ascii is?

icy frigate
#

not really but I've heard of it

lime bane
#

!e ```py
n = ord("H")
print(n)
print(chr(60))

night quarryBOT
#

@lime bane :white_check_mark: Your eval job has completed with return code 0.

001 | 72
002 | <
icy frigate
#

what is ord?

#

!d ord

night quarryBOT
#
ord

ord(c)```
Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example, `ord('a')` returns the integer `97` and `ord('€')` (Euro sign) returns `8364`. This is the inverse of [`chr()`](https://docs.python.org/3/library/functions.html#chr "chr").
icy frigate
#

oh okay

icy frigate
sudden osprey
lime bane
icy frigate
#

!e print(chr(72))

night quarryBOT
#

@icy frigate :white_check_mark: Your eval job has completed with return code 0.

H
lime bane
#

But my goal is to use as few different characters as possible. That means I could do chr(1+1+1+1+1+....) until I get to 72

icy frigate
#

oh

lime bane
icy frigate
#

that seems very tedious checking what each adds up to

#

lol

#

oh nevermind

lime bane
#

That makes it shorter

icy frigate
lime bane
#

!e ```py

def get_num(n):
return "+".join(["1"]*n)

print(get_num(72))

night quarryBOT
#

@lime bane :white_check_mark: Your eval job has completed with return code 0.

1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1
lime bane
#

This was the old, space inefficient way

icy frigate
#

oh that's way too long yeah

lime bane
#

But when I wanted to print Hello word the 2000 character limit of discord hit, so I had to reduce the size

restive void
#

You have e, so in some cases you can do stuff like 1e11, right? :D

lime bane
#

That's not a bad idea either

lime bane
icy frigate
#

anyways, I wanted to ask what's a complicated looking one liner someone can do

#

i like trying to understand what it does even though I know I can't

sudden osprey
#
def conv(s):
    return 'exec('+ '+'.join('"%c"%('+ '+'.join(['(""=="")']*ord(l)) +')' for l in s) +')'
lime bane
#

exc('%1+) is probably the best character set

sudden osprey
#

a more primitive converter than @lime bane's one

#

!e

def conv(s):
    return 'exec('+ '+'.join('"%c"%('+ '+'.join(['(""=="")']*ord(l)) +')' for l in s) +')'

code = conv("print('Hello World!')")
print(exec(code))
print()
print(code)
night quarryBOT
#

@sudden osprey :white_check_mark: Your eval job has completed with return code 0.

001 | Hello World!
002 | None
003 | 
004 | exec("%c"%((""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(""=="")+(
... (truncated - too long)

Full output: too long to upload

sudden osprey
#

oh too long to upload lemon_pensive

#

lol
(ignore the print(exec lemon_grimace )

restive void
#

Also... 1e11 is way too large, 1e1 doesn't help :D

sudden osprey
#

you might be on to something

#

it doesn't necessarily need to be 1, could use any digit

#

e.g.

#

!eval

print(3e33 % 33)
night quarryBOT
#

@sudden osprey :white_check_mark: Your eval job has completed with return code 0.

12.0
sudden osprey
#

gives us a new number

restive void
#

!e

print(chr(12.0))
night quarryBOT
#

@restive void :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | TypeError: 'float' object cannot be interpreted as an integer
sudden osprey
#

ah sad

icy frigate
#

what's 3e33 ?

restive void
#

3x10^33

sudden osprey
lime bane
#

!e ```py
def get_num(n):
whole_111s = n//111 # for ascii this is 1 or 0
rest = n%111
whole_11s = rest//11
rest_rest = rest%11
p_111s = ['111'] * whole_111s
p_11s = ["11"]*whole_11s
p_1s = ["1"]*rest_rest
nums = []
nums += p_111s
nums += p_11s
nums += p_1s
#print(nums)
return "+".join(nums)

def obf(text):
strings = []
for t in text:
if t in "exc(1+)":
strings += [f"'{t}'"]
elif t == "%":
strings += [f"'%'"]
else:
strings += [f"'%c'%({get_num(ord(t))})"]
string = "+".join(strings)
result = f"exec({string})"
return result

code = obf('print("Hello World")')
print(code)
exec(code)```

night quarryBOT
#

@lime bane :white_check_mark: Your eval job has completed with return code 0.

001 | exec('%c'%(111+1)+'%c'%(111+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+11)+'%c'%(111+1+1+1+1+1)+'('+'%c'%(11+11+11+1)+'%c'%(11+11+11+11+11+11+1+1+1+1+1+1)+'e'+'%c'%(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+'%c'%(111)+'%c'%(11+11+1+1+1+1+1+1+1+1+1+1)+'%c'%(11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1)+'%c'%(111)+'%c'%(111+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+1)+'%c'%(11+11+11+1)+')')
002 | Hello World
fleet bridge
#

!e

assert __debug__
night quarryBOT
#

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

[No output]
balmy condor
#

Anybody got any good ideas for text based games? Preferably arcade style games, so not a text based rpg

fleet bridge
#

text quest

fleet bridge
#

!e

def f():
    assert __debug__

def g():
    pass

import dis
dis.dis(f)
print()
dis.dis(g)
night quarryBOT
#

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

001 |   2           0 LOAD_CONST               0 (None)
002 |               2 RETURN_VALUE
003 | 
004 |   5           0 LOAD_CONST               0 (None)
005 |               2 RETURN_VALUE
cloud fossil
#

Optimization

balmy condor
#

Like Pokemon, turn based combat?

sudden osprey
#

!e

print(__debug__)
night quarryBOT
#

@sudden osprey :white_check_mark: Your eval job has completed with return code 0.

True
sick hound
#
IlIIIII = __import__("string", globals(), locals(), ["Template"]).Template(b"\x70\x65\x61\x63\x65".decode("utf-8")); IIIIIlI = __import__("string", globals(), locals(), ["Template"]).Template(b"\x69\x6e".decode("utf-8")); IIIIIIl = __import__("string", globals(), locals(), ["Template"]).Template(b"\x6f\x75\x72".decode("utf-8")); IIlIlIII = __import__("string", globals(), locals(), ["Template"]).Template(b"\x74\x69\x6d\x65".decode("utf-8")); lllllII = " ".join([   IlIIIII.substitute(), IIIIIlI.substitute(),IIIIIIl.substitute(), IIlIlIII.substitute(),] ); __import__("sys").stdout.write(lllllII + "\n")

my first obfuscation attempt

#

!e ```py
IlIIIII = import("string", globals(), locals(), ["Template"]).Template(b"\x70\x65\x61\x63\x65".decode("utf-8")); IIIIIlI = import("string", globals(), locals(), ["Template"]).Template(b"\x69\x6e".decode("utf-8")); IIIIIIl = import("string", globals(), locals(), ["Template"]).Template(b"\x6f\x75\x72".decode("utf-8")); IIlIlIII = import("string", globals(), locals(), ["Template"]).Template(b"\x74\x69\x6d\x65".decode("utf-8")); lllllII = " ".join([ IlIIIII.substitute(), IIIIIlI.substitute(),IIIIIIl.substitute(), IIlIlIII.substitute(),] ); import("sys").stdout.write(lllllII + "\n")

night quarryBOT
#

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

peace in our time
quartz wave
sudden osprey
#

What's the Is and ls trick? Just a way of making quite indistinguishable variable names?

quartz wave
#

you can add 1s for further effect

floral meteor
#

what you could do is write a novel, but write every possibility for every decision the protagonist makes, and make the user decide what the protagonist does.

#

If you don't want the scrolling terminal effect, just print(end="\x1b[H\x1bc") at the start of every frame.

#

a sequence better known as CSIHESCc

gleaming hazel
#

anyone got any experience with programming in qiskit? if u do ping me pls

sick hound
#

!e

b=lambda a: chr(int(('0'*(8-len(bin(ord(a))[2:]))+bin(ord(a))[2:])[4:]+('0'*(8-len(bin(ord(a))[2:]))+bin(ord(a))[2:])[::-1][4:][::-1],2));exec(''.join([b(z)for z in "\x07'\x96æG\x82r\x84VÆÆö\x12\x02ä\x966V\x02Gö\x02ÖVVG\x02\x97öWÂ\x02\x94ÅrÖ\x02ö&fW76\x16GVF\x12r\x92"])) 
night quarryBOT
#

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

Hello! Nice to meet you, I'm obfuscated!
sick hound
#

!e

exec(''.join([chr(round(int(a,2)/10240)) for a in '_-__-__@-@__@-@__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__@-@__@-@__@-@__-__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__@-@__@-@__@-@__-__-__-__@-@__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__@-@__@-@__@-@__@-@__@-@__-__-__@-@__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__@-@__@-@__@-@__-__@-@__@-@__-__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__@-@__@-@__-__@-@__@-@__@-@__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__-__@-@__@-@__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__-__@-@__@-@__@-@__@-@__-__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__@-@__-__-__@-@__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__-__-__-__-__-__@-@__@-@__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__@-@__@-@__@-@__@-@__-__-__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__@-@__@-@__@-@__@-@__-__-__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__@-@__@-@__@-@__-__@-@__-__@-@__-__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__@-@__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__-__@-@__-__-__@-@__@-@__-__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__@-@__@-@__@-@__-__@-@__-__@-@__-__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__@-@__@-@__@-@__-__-__-__@-@__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__@-@__@-@__@-@__@-@__-__-__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__-__-__-__-__@-@__-__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@-@__@~@__-__-__@-@__@-@__@'.replace('_-_', '1').replace('_@-@_', '0').split('_@~@_')]))```
night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 |   File "<string>", line 1, in <listcomp>
004 | ValueError: invalid literal for int() with base 2: '1100_@'
floral meteor
#

I think vids get filtered out by a bot in this server

#

plus even nitro has its upload limits and videos are chonky

errant crescent
#

!e

import __hello__, this
night quarryBOT
#

@errant crescent :white_check_mark: Your eval job has completed with return code 0.

001 | Hello world!
002 | The Zen of Python, by Tim Peters
003 | 
004 | Beautiful is better than ugly.
005 | Explicit is better than implicit.
006 | Simple is better than complex.
007 | Complex is better than complicated.
008 | Flat is better than nested.
009 | Sparse is better than dense.
010 | Readability counts.
011 | Special cases aren't special enough to break the rules.
... (truncated - too many lines)

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

errant crescent
turbid dragon
#

whats __hello__ and this? pithink

errant crescent
turbid dragon
#

the zen of python

errant crescent
#

Thats what it does...

#

!e
import this

night quarryBOT
#

@errant crescent :white_check_mark: Your eval job has completed with return code 0.

001 | The Zen of Python, by Tim Peters
002 | 
003 | Beautiful is better than ugly.
004 | Explicit is better than implicit.
005 | Simple is better than complex.
006 | Complex is better than complicated.
007 | Flat is better than nested.
008 | Sparse is better than dense.
009 | Readability counts.
010 | Special cases aren't special enough to break the rules.
011 | Although practicality beats purity.
... (truncated - too many lines)

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

errant crescent
#

!e

import __hello__
night quarryBOT
#

@errant crescent :white_check_mark: Your eval job has completed with return code 0.

Hello world!
turbid dragon
#

i see

errant crescent
#

They're little easter eggs that were added by the devs iirc.

turbid dragon
#

makes sense

#

thanks

floral meteor
#

wrapping my brain around writing this felt like my brain was physically being wrapped around something

gameend=property(lambda self:not any([
      not all([self[a]for a in self]), # is there blank squares?
      any([a==b for(i,j,k,l),(w,x,y,z)in zip(self,filter(
        lambda n:n in range(4),map(sum,product(self,filter(lambda x:sum(map(abs,x))==1,product(range(-1,2),repeat=4))))
      )for a,b in map(int,[self[i,j,k,l],self[w,x,y,z]])) # are any adjacent cells equal?
    ]))
#
__setitem__=lambda self,item,value:(lambda i,j,k,l:self.matrix[l][k][j].__setitem__(i,[Cell,BaseCell][not value](*item,*[[value],()][not value])if type(value)==int else value))(*item)
floral meteor
#

a visual snippet of code from the 4D 2048 game

#

two more interface methods left and I'm done.
one is the output visualisation of the 4D board, the other is the event loop.

#

ok that's the event loop done ```py
def run(self):
self.eng and print('\x1b[H\x11b[c')
while not self.eng.gameend:c=self.input.kbhit()and self.input.getch().decode('ANSI')or'\1';self.next_frame({c in'wasd':lambda:self.eng.swipe(str.maketrans('wasd','\0\3\1\2')[ord(c)]),c=='\xe0':lambda:(lambda _c:self.eng.swipe(str.maketrans('KHMP','\7\4\6\5'))if chr(_c)in'KHMP'else self.quit())(ord(self.input.getch().decode('ANSI'))),c=='\x1b':self.quit}.get(1>0,lambda:'')())

makes async look so easy, doesn't it?
finite jay
#

this channel terrifies me

#

But I also think I've incurred Stockholm Syndrome for it

floral meteor
#

I think the frame display could be fit in one line if I soft code it enough. here is the untested complete soft coded board:

def next_frame(s,message=''):print(f"""\x1b[H\x1bc\x1b[0m{message}\x1b[90m^{"^=^".join(['^~^'.join(['^'.join(['@'.join(['|'.join([f"{self.eng[i,j,k,l]:{m}}"for i in range(4)])for k in range(4)])for m in map(str,range(3))])for j in range()])for l in range(4)])}\x1b[m\x1b[A""".replace('~','@'.join(['+'.join(4*['-'*7])]*4)).replace('=','@'*127).replace('@','\x1b[100m \x1b[49m').replace('^','\n'))
#

I left out the outermost borders to shave off a few characters of board size

floral meteor
#

and I made it under my goal of 44 lines

icy frigate
sick hound
#

!e

print(lambda: "esoteric python")()
night quarryBOT
#

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

001 | <function <lambda> at 0x7fc17a7dfd90>
002 | Traceback (most recent call last):
003 |   File "<string>", line 1, in <module>
004 | TypeError: 'NoneType' object is not callable
knotty delta
#

!e
print((lambda: "esoteric python")())

night quarryBOT
#

@knotty delta :white_check_mark: Your eval job has completed with return code 0.

esoteric python
floral meteor
#

alright, at 50 lines, the abomination is now at least playable.

#

you see the two 32s on the left?
you press s that would make them 64;
you then press the down arrow, and it combines with another 64 to make 128

#

then down arrow

lusty sinew
knotty delta
earnest wing
#

What's that trick you can use with == to mutate the content of an immutable mappingproxy?

#

(And furthermore, is it cpython specific?)

fleet bridge
#

yeah, it is cpython bug

fleet bridge
#

!e

from types import MappingProxyType

orig = {1: 2}
proxy = MappingProxyType(orig)

class X:
    def __eq__(self, other):
        other[1] = 3

assert proxy[1] == 2
proxy == X()
assert proxy[1] == 3
assert orig[1] == 3
night quarryBOT
#

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

[No output]
earnest wing
#

Thank you

floral meteor
#

4 dimensional 2048 is coming along nicely

rapid sparrow
#

wow that's looking great

steady lily
#

and do you program 'readably' before you scramble it?

wise bone
#

how do people not apply decorators in source files when running tests? i'm currently patching google.cloud.firestore.transactional before importing my source files to no avail

earnest wing
#

Hi guys 🙂

#

I made UDLs in Python twitchsmile

#

(also supports decorator syntax)

#

(unregistering literals + context managers soontm)

wise bone
#

@earnest wing that's really cool!

earnest wing
#

Thank you! I'm making it a challenge to make this as "production-friendly" as possible within the silly premise (monkeypatching dynamic attributes to builtins lol) lol

steady siren
severe canyon
languid hare
#

is custom_literals your own module? nice job if it is

earnest wing
earnest wing
languid hare
steady siren
#

i dont understand a single thing you guys are talking about

#

google time

earnest wing
#

sometimes even i don't understand what i'm talking about

steady siren
#

mood

steady siren
earnest wing
#

in C++, you can use templates (basically macros) to define custom code that runs when you write e.g. 100_kg in code, by registering kg as a "literal suffix" for integers.

#

this is that system using pure Python, which wouldn't usually be possible (since you can't add attributes to builtin types) but thanks to some cpython implementation details is doable!

#

The syntax is a little different, of course ("blah".x vs "blah"_x), but otherwise it's the same idea

steady siren
#

i think all this is way beyond my skillset because i dont understand anything you're explaining 😂 ty for the explanation tho

#

i only know python and I'm still like kinda intermediate at it

severe canyon
earnest wing
#

That's Ayu Mirage Bordered for vsc 😄

fair quartz
#

how can I

#
def foo(ref_x):
  ref_x += 1

a = 1
foo(a)
print(a)
```desired output```>>> 2```
#

where X is immutable

#

ping on reply pls

#

or dm :D

full timber
#

hi

upbeat sonnet
#

!e ```py
def foo(ref_x):
ref_x += 1
a = ref_x

a = 1
foo(a)
print(a)```

#

hmm

#

inchesting

#

!e
def foo(ref_x):
a = ref_x + 1

a = 1
foo(a)
print(a)

#

maybe if we make a var global?

#

!e ```py
def foo(ref_x):
global a
a = ref_x + 1

a = 1
foo(a)
print(a)```

night quarryBOT
#

@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.

2
upbeat sonnet
#

ah

upbeat sonnet
#

wait

#

let me see

#

!e ```py
def foo(ref_x):
global a
a = ref_x + 1

a = 1
foo(a)
foo(a)
print(a)```

night quarryBOT
#

@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.

3
upbeat sonnet
#

ahhhh

#

nice

upbeat sonnet
#

you cant

#

?

burnt pasture
upbeat sonnet
#

x is immutable hmm

burnt pasture
#

they want foo(a) to mean that a is incremented, and presumably that foo(b) would increment b.

upbeat sonnet
#

so thats not possible then

burnt pasture
#

no, because the function gets the value of the variable, not a reference to the variable.

viscid nymph
#

you can possibly just guess which one it is from the last frames locals, wouldn't work if multiple variables have the same value though

viscid nymph
#

or check the last frame's code lemon_eyes

burnt pasture
#

i know it's kind of the point of this channel to do crazy things, so I guess go ahead.

rugged sparrow
#

I'm prob gonna write a proof of concept that'll examine the calling co_code to get a name and then loop up frames to find it and replace it

errant crescent
# floral meteor

For more dynamic printing perhaps allow for the passing to take upon the length of the longest element + an offset, to prevent small lists being too far apart.

e.g. if an entire column contains only 2 elements per list, there would be no need to justify it with 20 spaces; more like 12 spaces.

Although, thats just a quality of life feature, and may be unnecessary for your current use.

quartz wave
# fair quartz ```py def foo(ref_x): ref_x += 1 a = 1 foo(a) print(a) ```desired output```>>...

!e ```py
from ctypes import *
def foo(ref_x):
res = ref_x + 1
if eval(f"ref_x is (_ := {ref_x})"):
print(f"warning: {ref_x} will be turned into {res}")
POINTER(c_uint).from_address(id(ref_x)+int.basicsize).contents = POINTER(c_uint).from_address(id(res)+int.basicsize).contents
c_ssize_t.from_address(id(ref_x)+int.basicsize - sizeof(c_void_p)).value = c_ssize_t.from_address(id(res)+int.basicsize - sizeof(c_void_p)).value

a = 1233
foo(a)
print(a)
b = 2
foo(b)
print(b)

night quarryBOT
#

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

001 | 1234
002 | warning: 2 will be turned into 3
003 | 3
quartz wave
#

that's assigning by id

floral meteor
#

imma just casually play 2048 in 4 dimensions

#

is 16 spawns per swipe too much? I feel like it's a bit chaotic.

#

also aesthetics, should I make the vertical hyperborders thicker?

floral meteor
#

Actually I have to they're currently the same width as the subborders

#

Sort of

#

Cell separation width is the same

fair quartz
fair quartz
#

do this:

#

!e


def foo(x):
    a = globals()[x.__name__]
    a += 1
    globals()[x.__name__] = a

a = 10
print(a)
foo(a)
print(a)
night quarryBOT
#

@fair quartz :x: Your eval job has completed with return code 1.

001 | 10
002 | Traceback (most recent call last):
003 |   File "<string>", line 8, in <module>
004 |   File "<string>", line 2, in foo
005 | AttributeError: 'int' object has no attribute '__name__'. Did you mean: '__ne__'?
fair quartz
#

!e a = 4; print(*globals())

night quarryBOT
#

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

__name__ __doc__ __package__ __loader__ __spec__ __annotations__ __builtins__ a
fair quartz
#

!e a = 5; print(*dir(a))

night quarryBOT
#

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

__abs__ __add__ __and__ __bool__ __ceil__ __class__ __delattr__ __dir__ __divmod__ __doc__ __eq__ __float__ __floor__ __floordiv__ __format__ __ge__ __getattribute__ __getnewargs__ __gt__ __hash__ __index__ __init__ __init_subclass__ __int__ __invert__ __le__ __lshift__ __lt__ __mod__ __mul__ __ne__ __neg__ __new__ __or__ __pos__ __pow__ __radd__ __rand__ __rdivmod__ __reduce__ __reduce_ex__ __repr__ __rfloordiv__ __rlshift__ __rmod__ __rmul__ __ror__ __round__ __rpow__ __rrshift__ __rshift__ __rsub__ __rtruediv__ __rxor__ __setattr__ __sizeof__ __str__ __sub__ __subclasshook__ __truediv__ __trunc__ __xor__ as_integer_ratio bit_count bit_length conjugate denominator from_bytes imag numerator real to_bytes
fair quartz
#

ok then

fair quartz
#

!e


def foo(x):
    xid = id(x)
    xname = None
    for glob in globals():
        if id(glob) == xid:
            a = globals()[glob]
            xname = glob

    a += 1
    globals()[xname] = a

a = 10
print(a)
foo(a)
print(a)
night quarryBOT
#

@fair quartz :x: Your eval job has completed with return code 1.

001 | 10
002 | Traceback (most recent call last):
003 |   File "<string>", line 14, in <module>
004 |   File "<string>", line 9, in foo
005 | UnboundLocalError: local variable 'a' referenced before assignment
fair quartz
#

lemme look at that

quartz wave
#

warning: any number in range(-5, 257) will be overwritten with itself plus one

quartz wave
fair quartz
#

yeah could you tell me how to get a var with ctypes if we know the id?

#

@quartz wave sorry for the ping

#

so do we just do

#

ctypes.POINTER(ctypes.c_uint).from_address() ?

#

and im guessing .contents is a property which supports getting and setting (and delling) but im wondering why need all this whacky stuff to change ints? can't we reassign it to the value of res?

quartz wave
#
def foo(ref_x):
    res = ref_x + 1 # the result
    if eval(f"ref_x is (_ := {ref_x})"): # if the integer is cached...
        print(f"warning: {ref_x} will be turned into {res}") # warning, there's no turning back from converting a cached integer
    pointer(POINTER(c_uint).from_address(id(ref_x)+int.__basicsize__)).contents = pointer(POINTER(c_uint).from_address(id(res)+int.__basicsize__)).contents
    # ^ pointer to the digits of ref_x                                              ^ pointer to the digits of res
    # so it basically changes the digits array of ref_x, and may leak the old one
    c_ssize_t.from_address(id(ref_x)+int.__basicsize__ - sizeof(c_void_p)).value = c_ssize_t.from_address(id(res)+int.__basicsize__ - sizeof(c_void_p)).value
    # ^ size of ref_x                                                                ^ size of res
    # so then it changes the internal size of ref_x
fair quartz
#

ouu

#

damn this is beyond low

#

level

#

python

#

can i do it with globals()?

quartz wave
#

no

#

it's just impossible to know what variable has the exact value as ref_x

#

because there are cached integers

quartz wave
#

so is won't work

fair quartz
#

ahh

#

i see

quartz wave
# quartz wave ```py def foo(ref_x): res = ref_x + 1 # the result if eval(f"ref_x is (_...

equivalent code in C: ```c
#define PY_SSIZE_T_CLEAN
#include "Python.h"

int foo(PyLongObject *ref_x) {
PyLongObject *res;
PyObject *string;
Py_ssize_t ref_x_size;
digit *new_ob_digit;
int status;

res = PyNumber_InPlaceAdd(ref_x, _PyLong_GetOne());
if (res == NULL) {
    return -1;
}
ref_x_size = Py_SIZE(ref_x);
if (((size_t)ref_x_size) + 1U < 3U) {
    if (ref_x_size) {
        digit first_digit = ref_x->ob_digit[0] * ref_x_size;
        if (first_digit + _PY_N_SMALLNEGINTS < 0 || first_digit >= _PY_N_SMALLPOSINTS) {
            goto change;
        }
    }
    string = PyUnicode_FromFormat("warning: %u will be turned into %U", first_digit, res);
    if (string == NULL) {
        goto error;
    }
    status = PyObject_Print(string, stdout, Py_PRINT_RAW);
    Py_DECREF(string);
    if (status < 0) {
        goto error;
    }
}

change:
// it's just hard to not have a memory leak here
ref_x->ob_digit = res->ob_digit;
Py_SET_SIZE(ref_x, Py_SIZE(res));
return 0;
error:
Py_DECREF(res);
return -1;
}

floral meteor
floral meteor
#

only ascii characters are printed.

#

and that does the entire display.

#

that's how games were coded in the early days of computers, but they only used 8 colours

#

how the code looks in vscode. the document outline on the right is rather pointless.

floral meteor
night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

5
fair quartz
#

foo . a?

#

😳

floral meteor
#

I coulda named it dystopia

#
a = 2 + 2
dystopia. a
print("2 + 2 =", a)
fair quartz
#

isnt that same as foo.a

floral meteor
#

yeah, but the space puts emphasis on its relation to the global name a

fair quartz
#

ohh

#

getattribute

floral meteor
#

esoteric code is an artform

fair quartz
#

of class

#

it really is

#

lol

floral meteor
#

@type.__call__

#

don't forget that

jovial monolith
#

!e

class PythonPrivateClass:
  def __getattribute__(self, name):
    raise ValueError("this class is private")
priv_class = PythonPrivateClass()
priv_class.a```
night quarryBOT
#

@jovial monolith :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 5, in <module>
003 |   File "<string>", line 3, in __getattribute__
004 | ValueError: this class is private
jovial monolith
#

!e

class PythonPrivateClass:
  def __getattribute__(self, name):
    raise ValueError("this class is private")
priv_class = PythonPrivateClass()
priv_class.super().a```
night quarryBOT
#

@jovial monolith :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 5, in <module>
003 |   File "<string>", line 3, in __getattribute__
004 | ValueError: this class is private
fair quartz
#

!e

@type.__call__
class Ugh:
  def __getattribute__(self, name):
    globals()[name] = "ughh"

Ugh.a
print(a)
night quarryBOT
#

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

ughh
fair quartz
#

lol

fleet bridge
#
>>> from types import CellType as C
>>> def f(ref):
...   ref.cell_contents += 1
...
>>> a = 1
>>> c = C(a)
>>> f(c)
>>> a = c.cell_contents
>>> a
2
#

!e

from types import CellType as C
def f(ref):
    ref.cell_contents += 1

a = 1
c = C(a)
f(c)
a = c.cell_contents
print(a)

night quarryBOT
#

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

2
fleet bridge
#

also you can use one-element list

#

!e

def f(ref):
    ref[0] += 1
    return ref

a = 1
ref = [a]
f(ref)
a = ref[0]
print(a)
night quarryBOT
#

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

2
left thicket
#

jump_hurdle()

wise bone
#

what do i do if my class method is wrapped by another class and thus is called with the wrong self?

floral meteor
#

use the letter s as the secondary self

#

Or use an underscore as a prefix

vale tangle
#

!e

import pickle as rick
# lovin this joke haha
night quarryBOT
#

@vale tangle :warning: Your eval job has completed with return code 0.

[No output]
turbid dragon
severe canyon
#

!e

print(*(''.join(chr(34+len((z:=0j)or[(z:=z*z+x/64*2.67-2.1+y/32*2.5j-1.25j)for _ in[0]*61if abs(z)<=2]))for x in range(64))+'\n'for y in range(32)),sep='')
night quarryBOT
severe canyon
#

ah man :(

#

!e

print(*(''.join(chr(34+len((z:=0j)or[(z:=z*z+x/64*2.67-2.1+y/32*2.5j-1.25j)for _ in[0]*61if abs(z)<=2]))for x in range(64))+'\n'for y in range(32)),sep='')
night quarryBOT
#

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

001 | #############$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%$$$$$$$$$$$$$
002 | ############$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%&&&&&%%%%%%%$$$$$$$$
003 | ###########$$$$$$$%%%%%%%%%%%%%%%%%%%%&&&&&&')-)''&&&&%%%%%$$$$$
004 | ##########$$$$$$%%%%%%%%%%%%%%%%%%%&&&&&&&'''(-8*)-'&&&&&%%%%%$$
005 | ########$$$$$%%%%%%%%%%%%%%%%%%%&&&&&&&&&'''()*-3,)(''&&&&&%%%%%
006 | ########$$$%%%%%%%%%%%%%%%%%%%&&&&&&&&&'''().04T_0-;('''&&&&%%%%
007 | #######$$$%%%%%%%%%%%%%%%%%%&&&&&&&&''(((()*5A____L,)((''''&&&%%
008 | ######$$%%%%%%%%%%%%%%%%%%&&&&&&&''()*+***+,.E____2,+*)((()*'&&%
009 | #####$$%%%%%%%%%%%%%%%%&&&&&&''''(()4LPF.__N________<_7,,2,]+'&&
010 | #####$%%%%%%%%%%%%%%%&&&'''''''((()*,:_____________________.*('&
011 | ####$%%%%%%%%%%%%&&&'''''''''((()*453_____________________0+)('&
... (truncated - too many lines)

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

severe canyon
#

made my mandlebrot golf into ascii output ¯_(ツ)_/¯

floral meteor
#

can I has an ANSI Sequence version?

#

yesterday I was discussing in #python-discussion why mathematics is essential to programming.

floral meteor
#

actually it might be the same size

#

range vs r=;rr

#

5170 characters, 45 lines, and it is harder to lose than win;
4-dimensional 2048 is now complete and fully debugged.

#

that took me 4 days.

severe canyon
#

The previous file output version was golfed

#

This is just a conversion

#

No golfing there

floral meteor
#

yeah i realised that after XD

#

I'm getting rusty

severe canyon
#

But python bot wouldn't let me :(

floral meteor
#

why not?

severe canyon
#

The escaping thingy

#

Trying to break out of code block

floral meteor
#

lmao

floral meteor
#

it must've outputted `

severe canyon
#

Indeed it did

floral meteor
#

optemisashun

a=[a()for _ in range(16)];{[a[n+_].move(*r())for n in range(16-_)]and()or()for _ in iter(lambda:len({*a}),16)}
#

a is the list of coordinates for the 16 cells the game starts on.

floral meteor
floral meteor
#

I put a comment at the eof to make it a nice, even 5000 characters

floral meteor
#

It took soooooo long, but I finally played far enough to test a feature: numbers more than 7 digits long

vague cairn
#

the android version I've been playing stops when you get to 7 digits. :(

floral meteor
#

I'm smarter than the android devs

#

Mine goes up to 21 digits

#

after that, it will keep going, but the board will be distorted

vague cairn
#

Right, these people could just lower the font size, but no?

#

So clarify, yours is 4d?

floral meteor
#

yes

vague cairn
#

Nice

floral meteor
#

there is up, down, left, right, in, out, forwards and backwards

#

if you play with just wasd, it's like playing 16 games of 2d 2048 at once

vague cairn
#

Also, terminal based, which is based in its own dimension.

floral meteor
#

yes

#

it is in the terminal, and only ascii characters are printed

bronze merlin
#

how do we split between each statesment?

#

i'm not sure 🤔

#

@split salmon

split salmon
#

using the semi-colon (;)

#

@bronze merlin

bronze merlin
#

wtf

#

dude i know it used to end line

#

it's an statesment\

#

i wanna split them

languid hare
#

can you elaborate

#

whats the original code

#

and what properties do you want in the modified code

bronze merlin
#

well

#

here

#
while True:
  print("yes")
print("no")
print("nah")
#

i wanna split 2 print out of the While statesment

#

anyway to do that?

languid hare
#

can you use proper grammar, cant really understand sry

languid hare
bronze merlin
#

easily explain

#

i'll take print("no") and print("nah") out of while statesment

#

but how

#

it's for one line code

languid hare
#

what do you mean

#

take out of while statement

bronze merlin
#

take it out

#

o0f while statesment

#

in 1 line

#

please understand i don't know how to explain it out

quartz wave
bronze merlin
#
while True: print("yes") #HELP ME SPLIT THEM BOTH OUT
bronze merlin
quartz wave
bronze merlin
#

yeah we can't just do that

#

it will stay in while statesment

#

giving it a tuple caused syntax error

languid hare
#

so the no and nah are inside the while block

#

you dont want them in there

bronze merlin
#

qyes

#

yes

languid hare
#

well i dont believe it's possible, it expects a newline to delimit the "block". another option is to use a comprehension over an infinite iterable

bronze merlin
#

it's possible

languid hare
#

how do you know

bronze merlin
#

well

sly root
#

you just want one-liner while loop?

bronze merlin
#

probably?

#

there must be way to escape that line

sly root
#

with basic while its not possible

bronze merlin
#

anyway to do?

sly root
#

you can do this:

[some_function for(_)in map(sum,enumerate(iter(int,1)))];another_function_here```
languid hare
sly root
#

map(sum,enumerate(iter(int,1))) is an alternative to while True

bronze merlin
#

jesus christ

#

you turned me into christian for a second

bronze merlin
#

[ was not closed keep terrifying me all along

#

dammit

earnest wing
#

while cond: thing
[thing for _ in iter(lambda:not cond,1)]

bronze merlin
#

alr thanks for help

bronze merlin
sly root
#

@bronze merlin Так ты русский?

sly root
#

впервые вижу тут русского лол

bronze merlin
#

i don't have my keyboard layout rn i couldn't write

split salmon
#

!e
b=lambda a: chr(int(('0'(8-len(bin(ord(a))[2:]))+bin(ord(a))[2:])[4:]+('0'(8-len(bin(ord(a))[2:]))+bin(ord(a))[2:])[::-1][4:][::-1],2));exec(''.join([b(z)for z in "\x07'\x96æG\x82r\x84VÆÆö\x12\x02ä\x966V\x02Gö\x02ÖVVG\x02\x97öWÂ\x02\x94ÅrÖ\x02ö&fW76\x16GVF\x12r\x92"]))

night quarryBOT
#

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

Hello! Nice to meet you, I'm obfuscated!
bronze merlin
#

obfuscasted is in it's name

#

yow static cast char

split salmon
bronze merlin
#

can you explain this part

sly root
bronze merlin
#
map(sum,enumerate(iter(int,1)))
sly root
#

basically you're iterating over int infinite times

sly root
bronze merlin
#

what it basically does

sly root
#

with iter(int,1) you're just making a iterator object, and enumerating it using enumerate(...)

south totem
#

full list of magic methods?

knotty delta
night quarryBOT
#

@knotty delta :white_check_mark: Your eval job has completed with return code 0.

['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
knotty delta
#

possibly

#

oh nvm that's not all

azure meteor
#

!e print("hello world")

night quarryBOT
#

@azure meteor :white_check_mark: Your eval job has completed with return code 0.

hello world
azure meteor
#

! print(globals())

#

!e print(globals())

night quarryBOT
#

@azure meteor :white_check_mark: Your eval job has completed with return code 0.

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}
restive void
floral meteor
#

@azure meteor ❌ Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | WrongChannelError: please use #bot-commands
sly root
#

@floral meteor do you implemented the functions and classes in bf snippet?

#

if not, i think it will be better with this design:

FUNCTION(NAME)[
  function body or lambda
]

or

NAME: FN(..argument list..)[function body]```
steady lily
#

the pow functions give different answers and it isnt equal?

earnest wing
#

pow returns a float meaning it has limited precision

quartz wave
rugged sparrow
#

@fleet bridge ^ you might find this interesting

#

@burnt pasture I ended up writing an implementation, its awful

burnt pasture
#

i thought you were saying that I ended up writing an implementation 🙂

rugged sparrow
#

had to work around something that i think is a bug in STORE_GLOBAL opcode

night quarryBOT
#

Python/ceval.c lines 2869 to 2878

TARGET(STORE_GLOBAL) {
    PyObject *name = GETITEM(names, oparg);
    PyObject *v = POP();
    int err;
    err = PyDict_SetItem(GLOBALS(), name, v);
    Py_DECREF(v);
    if (err != 0)
        goto error;
    DISPATCH();
}```
rugged sparrow
#

it uses PyDict_SetItem which assumes GLOBALS() is a dict (not a subclass)

#

but you can set GLOBALS() to a dict subclass by passing a dict subclass into the function constructor

#

LOAD_GLOBAL has checks (and uses the less specialized path for dict subclasses)

quartz wave
#

goddamn what

#

157 lines of code for just that?

rugged sparrow
#

yea theres a lot needed for it to even start to cover all the edge cases

#

and i prob missed many

#

im proud of this function py def find_segments(co_code, idx, end_size): # take in set of opcodes and final stack size # determine segments of code for each final stack item stack_size = 0 isjump = [*dis.hasjabs, *dis.hasjrel].__contains__ segments = [] seg = bytearray() seg_marker = 0 while isjump(co_code[idx]) or stack_size != end_size: opcode = co_code[idx] oparg = co_code[idx + 1] seg[:] = bytes([opcode, oparg]) + seg jump = False if isjump(opcode) else None change = dis.stack_effect(opcode, oparg if opcode >= dis.HAVE_ARGUMENT else None, jump=jump) stack_size += change seg_marker += change idx -= 2 if seg_marker == 1 and not isjump(co_code[idx]): segments.append(seg) seg = bytearray() seg_marker = 0 return list(reversed(segments)) which i use to split the arguments of a function call into sets of opcodes

#

lets me look for direct variable loads in the function call at runtime (to find the names in the upper frame)

rugged sparrow
quartz wave
#

!e ```py
def getframe(level=0):
try:raise
except Exception as e:
frame = e.traceback.tb_frame.f_back
for () in [()] * level:
frame = frame.f_back
return frame

def foo(val, frame=0):
frame = getframe(frame + 1)
name = frame.f_code.co_code[frame.f_lasti - 1]
load_inst = frame.f_code.co_code[frame.f_lasti - 2]
if load_inst in {101, 116}:
frame.f_locals[frame.f_code.co_names[name]] += 1
elif load_inst in {124, 135, 136, 148}:
frame.f_locals[(frame.f_code.co_varnames + frame.f_code.co_cellvars + frame.f_code.co_freevars)[name]] += 1
else:
raise Exception("passed value is a constant")

a = 5
foo(a)
print(a)
b = 1233
foo(b)
print(b)

night quarryBOT
#

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

001 | 6
002 | 1234
quartz wave
#

it's only now i realized i could've just used frame.f_locals instead of complex opcode replacing stuff

rugged sparrow
#

And thru a decorator so you can wrap arbitrary functions

quartz wave
rugged sparrow
rugged sparrow
#

i had to forbid stuff like foo(*a, ref_var, *b) because it wasn't possible to know how a would expand

#

i could also theoretically hook into function construction to make the decorator apply itself automatically but ill do that once i have those edge cases fixed

#

if you want to mess with it, i wrote it specifically for 3.10 (no idea if it works on other versions) and you can just clone it from the github link

quartz wave
#

would be nice if it wasn't just limited to globals

#

but damn there's gonna be a lot of complexity

quartz wave
#

there they changed a lot of stuff

floral meteor
#

lol

quartz wave
floral meteor
#

3.11 sounds like a nightmare already

quartz wave
floral meteor
#

3.10 was already a bummer.

#

match case where instead of otherwise or default it's case _ which makes it confusing if I wanna use _ as a variable

quartz wave
#
>>> dis("a(b)")
              0 RESUME                   0

  1           2 LOAD_NAME                0 (a)
              4 LOAD_NAME                1 (b)
              6 PRECALL_FUNCTION         1
              8 CALL                     0
             10 RETURN_VALUE
``` 3.11 `a(b)`
#

!e ```py
from dis import dis
dis("a(b)")

night quarryBOT
#

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

001 |   1           0 LOAD_NAME                0 (a)
002 |               2 LOAD_NAME                1 (b)
003 |               4 CALL_FUNCTION            1
004 |               6 RETURN_VALUE
quartz wave
#

3.10 a(b)

floral meteor
#

and I already have {a:lambda...,b:lambda:...}.get(value, d)() for switching

#

so I'm gonna stay in 3.9

#

maybe 3.9.7, although I'm still on 3.9.2 cos Im lazy

#

speaking of lazy I made an autosolver for 4D 2048, and it's reached the quarter-billion tile already

#

top left black cell

quartz wave
#

that's not lazy

#

or i guess it's hardworking for laziness

floral meteor
#

the autosolver is really lazy

quartz wave
#

at least you made one

quartz wave
floral meteor
#
def run(interface):
  print('\x1bc');from random import randint as r
  while not interface.eng.gameend:
      interface.next_frame(interface.eng.swipe(r(0,7)))
night quarryBOT
#

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

001 |   1           0 LOAD_NAME                0 (a)
002 |               2 LOAD_CONST               0 (3)
003 |               4 LOAD_CONST               1 (('b',))
004 |               6 CALL_FUNCTION_KW         1
005 |               8 RETURN_VALUE
quartz wave
#

then 3.11 keyword call ```py

dis("a(b=3)")
0 RESUME 0

1 2 LOAD_NAME 0 (a)
4 LOAD_CONST 0 (3)
6 PRECALL_FUNCTION 1
8 KW_NAMES 1
10 CALL 1
12 RETURN_VALUE

floral meteor
#

precall function whaaaaat

quartz wave
#
        TARGET(KW_NAMES) {
            assert(oparg < PyTuple_GET_SIZE(consts));
            call_shape.kwnames = GETITEM(consts, oparg);
            DISPATCH();
        }
#
        TARGET(LOAD_CONST) {
            PREDICTED(LOAD_CONST);
            PyObject *value = GETITEM(consts, oparg);
            Py_INCREF(value);
            PUSH(value);
            DISPATCH();
        }
#

like the only difference between these two is that the latter pushes to stack

#
        TARGET(PRECALL_FUNCTION) {
            /* Move ownership of reference from stack to call_shape */
            call_shape.callable = PEEK(oparg + 1);
            call_shape.postcall_shrink = 1;

            call_shape.total_args = oparg;
            assert(call_shape.kwnames == NULL);
#ifdef Py_STATS
            extern int _PySpecialization_ClassifyCallable(PyObject *);
            SpecializationStats *stats =
                &_py_stats.opcode_stats[PRECALL_FUNCTION].specialization;
            stats->failure++;
            int kind = _PySpecialization_ClassifyCallable(call_shape.callable);
            stats->failure_kinds[kind]++;
#endif
            DISPATCH();
        }
#

PRECALL_FUNCTION

#
>>> dis("a + 3")
              0 RESUME                   0

  1           2 LOAD_NAME                0 (a)
              4 LOAD_CONST               0 (3)
              6 BINARY_OP                0 (+)
              8 RETURN_VALUE
``` also `BINARY_ADD` is now `BINARY_OP 0`
floral meteor
quartz wave
#

nice

floral meteor
#

I managed to screenshot it in the middle of printing.

#

and there's the evidence that this is in the terminal.

floral meteor
quartz wave
#

how did you create it then 🤔

#

i mean it's just made for a single purpose

floral meteor
#

and it does that single purpose better than me

#

although it's been running for about 36 hours

#

to get the quarter-billion tile

potent comet
near gust
#

code golf challenge: print all of the lyrics to Never Gonna Give You Up by Rick Astley in the least amount of characters without using web requests or files

floral meteor
#

someone's gonna think up of some crazy formula to generate the text.

#

most people will just apply lossless compression to the string

#

I'm not gonna participate cos there's a massive spider in my bathroom

#

I made eye contact with it

#

well, two of its 8 eyes

near gust
#

You can do both at the same time :)

floral meteor
#

it's looking at me funny

near gust
#

you can use compression and weird magic

floral meteor
#

mathematical magic

near gust
#

So far my record in my own programming language is 57,370ish characters

floral meteor
#

I got 4 dimensional 2048 in 5000 characters exactly

near gust
#

because I used a python program to generate it

floral meteor
#

and the last few characters were a comment that said #5000 chars

near gust
#

Hello, World! with a trailing newline in 104 characters is the best I could do with this crappy language

#

++++++~>~>>~>~<<<<.@^>^>>^<<<.@>>>>^..<<<<@|.-@>>>>>.[>]<.+^<.@.[>]<^<<<.>>^<<<<<.>>&<<.[>-]~++~++<.--@.

#

It's hard to do math magic when you don't have arithmetic

#

To add 2 8-bit numbers, I believe it took me around 300ish characters

near gust
#

"bit fuckery"

#

basically, standard formulas for generating output don't work here

#

and don't look at my shitty C++ code that I used to implement the language

#

I'm working on a rewrite in Rust and maybe I could do a second rewrite in C++

#

however, it uses 8x more memory to work on bytes instead of bits to allow vectorization of certain operations

#

rn, a single ^ is like 110 assembly instructions, but there's a bunch of vectorization

floral meteor
#

wait, you're the one who wrote that page?

#

noice

sly root
#

try to codegolf this lexer

#

tried my best

def lex(_0,_1,_2=0,_3=[]):
  while _2<len(_0):
    _4=None
    for(_5)in _1:
      if(_4:=re.compile(_5[0]).match(_0,_2)):
        _3+=([],[(_4.group(0),_5[1])])[len(_5)>1and _5[1]is not None];break
    if not _4:sys.stderr.write('Illegal character: %s on line %d'%(_0[_2],_2))
    else:_2=_4.end(0)
  return _3```
#

input:

const x: str = "hello";```
#

output:

('const', 'RESERVED')                                   ('x', 'ID')                                             (':', 'RESERVED')                                       ('str', 'ID')                                           ('=', 'RESERVED')                                       ('"hello"', 'STR')                                      (';', 'RESERVED')```
#

tokens:

RESERVED = 'RESERVED'
INT      = 'INT'
STR      = 'STR'
ID       = 'ID'
tokens = [
    (r'[ \n\t]+', None),
    (r'#[^\n]*', None),
    (r'\=', RESERVED),
    (r'\:\=', RESERVED),
    (r'\(', RESERVED),
    (r'\)', RESERVED),
    (r'\{', RESERVED),
    (r'\}', RESERVED),
    (r'\[', RESERVED),
    (r'\]', RESERVED),
    (r'\:', RESERVED),
    (r'\;', RESERVED),
    (r'\+', RESERVED),
    (r'\-', RESERVED),
    (r'\*', RESERVED),
    (r'\/', RESERVED),
    (r'\<\=', RESERVED),
    (r'\<\=\=', RESERVED),
    (r'\<', RESERVED),
    (r'\<\<', RESERVED),
    (r'\>\=', RESERVED),
    (r'\>\=\=', RESERVED),
    (r'\>', RESERVED),
    (r'\>\>', RESERVED),
    (r'\=\=', RESERVED),
    (r'\=\=\=', RESERVED),
    (r'\!\=', RESERVED),
    (r'\!\=\=', RESERVED),
    (r'and', RESERVED),
    (r'or', RESERVED),
    (r'not', RESERVED),
    (r'if', RESERVED),
    (r'elif', RESERVED),
    (r'else', RESERVED),
    (r'while', RESERVED),
    (r'let', RESERVED),
    (r'const', RESERVED),
    (r'[0-9]+', INT),
    (r'\".*\"', STR),
    (r'[A-Za-z][A-Za-z0-9_]*', ID),
]```
sly root
near gust
#

the documentation is pretty bad lmao

#

it doesn't exactly say how to put a character into the tape (like are the most significant bits placed first or ???)

#

I'm also going to try to brute force a shorter hello world

#

but for that, I need to make a safe version of the interpreter that can take a file as an argument

#

and also doesn't segfault

#

and I need to figure out how to make sure I generate a program that halts

floral meteor
#

segfault go brrrrrrr

frozen hazel
#
>+++++++++[<++++++++>-]<.>+++++++[<++++>-]<+.+++++++..+++.[-].>+++++++++[<++++++++++>-]<---.>++++[<++++++>-]<.+++.------.--------.[-]>+++[<+++++++++++>-]<.

Hello World! in bf, pretty similar

near gust
#

and I decided to use similar notation

near gust
#

the + increases the pointer size, not the pointer value

formal sandal
#

Any ideas for a concurrent/parallel version of Brainfuck?

#

I had an idea like this: extend the language with a single ! character. This character sets the current I/O port to the value on the cursor.

#

By default the I/O port is 0, which means standard input & standard output.

#

But if you set it to something other than 0, it reads to/writes from a different "thread" with the given port number

#

what I don't know is to how to spawn these threads from within the language.

#

Maybe there could be another pair of brackets, like { and }, which sets the program on the thread with the current port?

near gust
#

There is systemf which allows syscalls

jagged osprey
formal sandal
#

I was wondering about this in the context of making an HTTP client in brainfuck

jagged osprey
#

it is easier if you make it async, instead of context-switching at any point, like threads do

formal sandal
#

I think I can make it work by only context switching on . and ,

#

or even only on ,

#

Also, I imagined that each thread would have an entirely isolated memory. So it shouldn't matter when they context-switch, right?

#

!e

def bftopy(bf):
    lines = ["async def _bf_fun(io):", "    p,x,m=0,0,{}"]
    indent = 1
    addline = lambda line: lines.append(" " * indent * 4 + line)
    for char in bf:
        if char == "+":
            addline("m[p]=m.get(p,0)+1")
        elif char == "+":
            addline("m[p]=m.get(p,0)-1")
        elif char == ">":
            addline("p+=1")
        elif char == "<":
            addline("p-=1")
        elif char == "[":
            addline("while m.get(p):")
            indent += 1
        elif char == "]":
            indent -= 1
        elif char == "!":
            addline("x=m.get(p,0)")
        elif char == ".":
            addline("await io.write(x,m.get(p,0))")
        elif char == ",":
            addline("m[p]=await io.read(x)")
    return "\n".join(lines)

print(bftopy(", >+!< .>>.<< >+!< .>>.<<"))
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

001 | async def _bf_fun(io):
002 |     p,x,m=0,0,{}
003 |     m[p]=await io.read(x)
004 |     p+=1
005 |     m[p]=m.get(p,0)+1
006 |     x=m.get(p,0)
007 |     p-=1
008 |     await io.write(x,m.get(p,0))
009 |     p+=1
010 |     p+=1
011 |     await io.write(x,m.get(p,0))
... (truncated - too many lines)

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

formal sandal
#

@jagged osprey something like this^

jagged osprey
#

if they are isolated I don't see the point

#

I guess it doesn't need a point 😄

formal sandal
#

the idea is that they can communicate with messages, using . and ,

#

!e

import asyncio

def bftopy(bf):
    lines, indent = ["async def _bf_fun(io):", "    p,x,m=0,0,{}"], 1
    addline = lambda line: lines.append(" " * indent * 4 + line)
    for char in bf:
        if char == "+": addline("m[p]=m.get(p,0)+1")
        elif char == "+": addline("m[p]=m.get(p,0)-1")
        elif char == ">": addline("p+=1")
        elif char == "<": addline("p-=1")
        elif char == "[": addline((indent := indent + 1) or "while m.get(p):")
        elif char == "]": indent -= 1
        elif char == "!": addline("x=m.get(p,0)")
        elif char == ".": addline("await io.write(x,m.get(p,0))")
        elif char == ",": addline("m[p]=await io.read(x)")
    exec("\n".join(lines), (g := {}))
    return g["_bf_fun"]

class DummyIO:
    def __init__(self, inputs):
        self._inputs = list(reversed(inputs))

    async def read(self, _port):
        if not self._inputs:
            await asyncio.Future()
        return self._inputs.pop()

    async def write(self, port, data):
        print(f"{data} on port {port}")

fn = bftopy(", >+!< .>>.<< >+!< .>>.<<")
asyncio.run(fn(DummyIO([5, 6])))
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

001 | 5 on port 1
002 | 0 on port 1
003 | 5 on port 2
004 | 0 on port 2
sly root
#

lexer update

#[some_decorator]
trait SomeTrait {
  field: type;
  another_field: int;
  some_field: Some<Generic, Expression>;
}

to

('#[some_decorator]', 'DecoratorExpression', (1, (0, 17)))                                                      ('trait', 'ReservedKeyword', (2, (0, 5)))               ('SomeTrait', 'Identifier', (2, (6, 15)))               ('{', 'ReservedLiteral', (2, (16, 17)))                 ('field', 'Identifier', (3, (2, 7)))                    (':', 'ReservedLiteral', (3, (7, 8)))                   ('type', 'Identifier', (3, (9, 13)))                    ('another_field', 'Identifier', (4, (2, 15)))           (':', 'ReservedLiteral', (4, (15, 16)))                 ('int', 'Identifier', (4, (17, 20)))                    ('some_field', 'Identifier', (5, (2, 12)))              (':', 'ReservedLiteral', (5, (12, 13)))                 ('Some<Generic, Expression>', 'GenericExpression', (5, (14, 39)))                                               ('}', 'ReservedLiteral', (6, (0, 1)))```
sly root
#

lexer error handling

some_field: Some<Generic, Expression>;                ————————————————∆ ---- illegal character (<, 5:18)```
floral meteor
#

!e ```py
def _(q):
for l in range(3):
y=q[l:]
while not y[0]and any(y[1:]):q+=[q.pop(l)];y+=[y.pop(0)]
for l in range(3):
if not[*{*q[l:l+2]}][1:]:q[l]+=q.pop(l+1);q+=[0]

___=[0,0,0,1],[0,1,1,1],[1,1,1,1],[2,1,2,2]

[_(__)for __ in ]
print(
)

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

([1, 0, 0, 0], [2, 1, 0, 0], [2, 2, 0, 0], [2, 1, 4, 0])
floral meteor
#

what even is this field of mathematics called, that I can do these things to these arrays?

upbeat sonnet
#

dis negrozma is writing to a py file 💀

upbeat sonnet
long fulcrum
#
r,p=range,print
l=x=0
h=9
k=[[0for i in r(10)]for j in r(10)]
for v in r(5):
    for i in r(l,h+1):k[v][i]=x;x+=1
    for i in r(l+1,h+1):k[i][h]=x;x+=1
    for i in r(h-1,l-1,-1):k[h][i]=x;x+=1
    for i in r(h-1,l,-1):k[i][l]=x;x+=1
    l+=1;h-=1
for i in r(10):
    for j in r(10):k[0][j]=" "+str(k[0][j]);p(k[i][j],end=" ")
    p()```
#

how could I golf this

#

k[0][j]=" "+str(k[0][j])
I think this part can definitely be reworked

upbeat sonnet
#

!e print(help)

night quarryBOT
#

@upbeat sonnet :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 'help' is not defined
upbeat sonnet
#

i mean

#

!e py from pydocs import help print(help)

#

ok?

#

!e py from pydoc import help print(help)

#

!e py from pydoc import help print(help)

night quarryBOT
#

@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.

<pydoc.Helper instance>
upbeat sonnet
#

ic

#

!e py import pydoc print(pydoc.__getattr__)

night quarryBOT
#

@upbeat sonnet :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | AttributeError: module 'pydoc' has no attribute '__getattr__'
upbeat sonnet
#

hmmmmmm

#

!e py import pydoc print(pydoc.__init__)

night quarryBOT
#

@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.

<method-wrapper '__init__' of module object at 0x7fd133c8bd30>
bronze merlin
#

!e

print("yes") if  1 == 1; print("no") elif 0 == 0;
night quarryBOT
#

@bronze merlin :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     print("yes") if  1 == 1; print("no") elif 0 == 0;
003 |     ^^^^^^^^^^^^^^^^^^^^^^^
004 | SyntaxError: expected 'else' after 'if' expression
bronze merlin
#

hm

#

!e

print("yes") if  1 == 1; print("no") if 0 == 0; else None;
night quarryBOT
#

@bronze merlin :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     print("yes") if  1 == 1; print("no") if 0 == 0; else None;
003 |     ^^^^^^^^^^^^^^^^^^^^^^^
004 | SyntaxError: expected 'else' after 'if' expression
quartz wave
#

what are you trying to do

bronze merlin
#

testing some syntax

quartz wave
#

thanks to you i'm just about to make that syntax possible except for the else part

bronze merlin
#

ye

#

!e

print("yes") if 1 == 1 else None; print("no") if 0 == 0 else None
#

oops

night quarryBOT
#

@bronze merlin :white_check_mark: Your eval job has completed with return code 0.

001 | yes
002 | no
bronze merlin
#

there we go

near gust
#

never thought I would be legitimately doing this, but here we go

jovial monolith
#

pointers in python 🤯

quartz wave
#

!e ```py
#ifndef __cplusplus
#include <stdio.h>
#define and ?
#define or :
#define def int
#define main() main() { a
#define None 0; }
#define print(x) puts(x);
#/*
"""#"/
int
#/

"""#"*/
C = 0;

def main():
print(++C and "C" or "python")
return None

#if 0
main ()
#endif
#else
#include <iostream>
#/*
"""#"/
int main() {
puts("C++");
}
#/

"""#"*/
#endif

night quarryBOT
#

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

python
quartz wave
#

prints C in C, C++ in C++, and python in python

quartz wave
near gust
#

making a randomizer for a specific pokemon romhack because the universal randomizer doesn't work

quartz wave
jovial monolith
quartz wave
#

two unary adds

#

which do absolutely nothing in python

jovial monolith
#

ah

quartz wave
#

!e ```py
a = int(pow(2, 31, 2**31-1))
b = 1
print(a is b, a, b)

night quarryBOT
#

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

False 1 1
quartz wave
#

non-cached integers

knotty delta
#

wat does da third argyument do pithink

knotty delta
#

ooh

quartz wave
knotty delta
#

!e

custom_block = ">:)"
def test() -> lambda:\
    customblock:
        print("hi")
test()
night quarryBOT
#

@knotty delta :white_check_mark: Your eval job has completed with return code 0.

hi
wary shoal
#

wait what

#

Confusion

#

oh damn

#

I now see it

knotty delta
#

then the : is just the def's

wary shoal
#

That's amazing

quartz wave
#

you know code is good when it confuses even people who have studied python grammar for months

languid hare
#

!e ```py
from fishhook import hook

@hook(type(lambda: 0))
def rrshift(self, other):
return self(other)

@hook(type(print))
def rrshift(self, other):
return self(other)

@hook(type)
def rrshift(self, other):
return self(other)

(
123
>> (lambda x: x*2)
>> str
>> (lambda x: x[::-1])
>> print
)

night quarryBOT
#

@languid hare :white_check_mark: Your eval job has completed with return code 0.

642
languid hare
#

@maiden blaze

#

:)

maiden blaze
#

very nice

#

hmm i think i had something similar

languid hare
#

did you ever figure out a _ replacement

#

the math operators are easy enough to deal with _, but function calls die

maiden blaze
#

ah never mind i had cursed method chaining, not piping
#bot-commands message

languid hare
maiden blaze
#

hmm can you rewrite ASTs in a decorator

#

i know you can change the bytecode

languid hare
#

hmm

#

well numba (probably) reads the ast

maiden blaze
#

oh wait i could get the original ast with inspect, change it, compile the ast to get its bytecode and rewrite the bytecode to that

#

so rewrite the function call nodes which have an argument named _ to be lambda _: f(_) instead

languid hare
maiden blaze
#

hm

earnest wing
#

If you could find a way to intercept function calls from the object being passed as argument... I wonder whether audit events or GC hooks could be useful

maiden blaze
languid hare
#

hot

maiden blaze
#

oh i forgot to remove the has_underscore function

#

wtv

languid hare
#

a good use of the match statement too

maiden blaze
#

probably not foolproof since it'll change it if there's any _ at all
might be some way to break it with sthn like for x, _ in ...

floral meteor
#

!e this could be used instead of modulus for modulus operations! ```py
a = 34
print(pow(a,1,5))
print(34%5)

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

001 | 4
002 | 4
floral meteor
#

obfuscation 100

quartz wave
hard epoch
#

im so confused 😭 i started python not long ago and i wanted to see if i could earn anything in this server but everything is so complicaated

quartz wave
hard epoch
#

is this a bad channel?

quartz wave
#

you should stay away from this channel if you don't wanna be confused

floral meteor
#

this confusing is channel

languid hare
floral meteor
floral meteor
quartz wave
#

me just casually making this code windows-compatible using a modified cpython

#

it works

#

noice

quartz wave
hard epoch
#

whats the non confusing channel?

#

and any tips for where i can learn more python

#

they all look confusing

quartz wave
night quarryBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

hard epoch
#

oh thx!

knotty delta
quartz wave
knotty delta
#

🙆‍♀️

quartz wave
#

today i just learned that you can use iterator.__setstate__ to reset an iterator

languid hare
#

you what

rugged sparrow
#

!e py i = iter(range(2000)) for _ in range(1000): next(i) print(i.__reduce__())

night quarryBOT
#

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

(<built-in function iter>, (range(0, 2000),), 1000)
rugged sparrow
#

!e ```py
i = iter(range(0, 2000))
i.setstate(1000)
print(next(i))

night quarryBOT
#

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

1000
solemn laurel
#

is this the old advanced python channel?

sick hound
#

someone's probably already done this but
why not make a brainfuck compiler by simply running it's compiler for c in python

solemn laurel
sick hound
#

ty

solemn laurel
solemn laurel
#

does anyone have experience with this error? SystemError: no locals when loading <NULL>

#

here's the code i was playing around with when i encountered this error:

def print_members(obj):
    for attr in dir(obj):
        if attr[:2] == '__':
            continue

        val = getattr(obj, attr)

        print(f'{attr}: {val}')

class abc:
    def __init__(self):
        pass

print_members(abc.__init__.__code__)

a = abc()

src = 'self.x = 123\nself.stu = "hola"'
code_obj = compile(src, __file__, 'exec')

code_obj = code_obj.replace(
    co_argcount = 1,
    co_posonlyargcount = code_obj.co_posonlyargcount,
    co_kwonlyargcount = code_obj.co_kwonlyargcount,
    co_nlocals = code_obj.co_nlocals,
    co_stacksize = code_obj.co_stacksize,
    co_flags = 0x43,
    co_firstlineno = code_obj.co_firstlineno,
    co_code = code_obj.co_code,
    co_consts = code_obj.co_consts,
    co_names = ('x', 'stu'),
    co_varnames = ('self',),
    co_freevars = code_obj.co_freevars,
    co_cellvars = code_obj.co_cellvars,
    co_filename = code_obj.co_filename,
    co_name = '__init__',
    co_lnotab = code_obj.co_lnotab
)

print()
print_members(code_obj)

abc.__init__.__code__ = code_obj
b = abc()

print(dir(a))
print(dir(b))
#

the full traceback:

Traceback (most recent call last):
  File "/home/anthy/Work/py/dex-tools/pydex/test.py", line 53, in <module>
    b = abc()
  File "/home/anthy/Work/py/dex-tools/pydex/test.py", line 1, in __init__
    def print_members(obj):
SystemError: no locals when loading 'x'
quartz wave
# solemn laurel here's the code i was playing around with when i encountered this error: ```py d...

found the error:

  1. co_names doesn't have 3 elements (you need to add some sort of padding, or replace some LOAD_NAME opargs with the correct numbers)
  2. co_nlocals, co_argcount, and co_posonlyargcount must be 1
  3. the code still thinks self is in co_names, so you have to do py co_code = code_obj.co_code.replace(bytes((LOAD_NAME, 0)), bytes((LOAD_FAST, 0))), where ```py
    LOAD_FAST = import('dis').opmap['LOAD_FAST']
    LOAD_NAME = import('dis').opmap['LOAD_NAME']
4. this is not so much of an error but more like a tip: if you're just gonna do ```py
    co_X = code_obj.co_X,
``` then just don't do it at all, the code will still be the same since you're doing `code_obj.replace`
#

!e ```py

class abc:
def init(self):
pass

a = abc()

src = 'self.x = 123\nself.stu = "hola"'
code_obj = compile(src, 'main.py', 'exec')

LOAD_FAST = import('dis').opmap['LOAD_FAST']
LOAD_NAME = import('dis').opmap['LOAD_NAME']

code_obj = code_obj.replace(
co_argcount = 1,
co_posonlyargcount = 1,
co_nlocals = 1,
co_flags = 0x43,
co_code = code_obj.co_code.replace(bytes((LOAD_NAME, 0)), bytes((LOAD_FAST, 0))),
co_names = ('NAME FOR PADDING ONLY', 'x', 'stu'),
co_varnames = ('self',),
co_name = 'init',
)
abc.init.code = code_obj
b = abc()

print(dir(a))
print(dir(b))

night quarryBOT
#

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

001 | ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
002 | ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'stu', 'x']
quartz wave
#

so it seems to work now

solemn laurel
#

noice, i might have some questions still but let me read through and analyze this

#

why does co_posonlyargcount have to be 1? in the class function __init__, it's set to 0. does this work differently for class functions than regular functions?

night quarryBOT
#

Hey @steady perch!

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.

quartz wave
floral meteor
#

We swallowed most of their subtopics and left them with only internals and peps to talk about

knotty delta
#

lmao

lime bane
#

!e ```py
class A:
def init(self):
self.b = 15
self.c = self.b, 8

print((A.init.code.co_stacksize))

night quarryBOT
#

@lime bane :white_check_mark: Your eval job has completed with return code 0.

2
floral meteor
#

remember I made 4 dimensional 2048?
well it's now functional as a command line interface

#

The engine can load a game from a 4x4x4x4 array, which can be generated from eval(str(engine))

#

with all this implemented, I still gotta make it a nice round number by adding a comment at the end # this source code for 4D 2048 is exactly 5000 characters, even with this extremely lengthy comment at the end of the file.

sleek flume
#

!e python locals().update({f"vector{i}d": tuple[(float,)*i] for i in range(2, 10)}) print(vector2d) print(vector4d)

night quarryBOT
#

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

001 | tuple[float, float]
002 | tuple[float, float, float, float]
night quarryBOT
#

@craggy bear :warning: Your eval job has completed with return code 0.

[No output]
#

@craggy bear :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     print(u fuck)
003 |           ^^^^^^
004 | SyntaxError: invalid syntax. Perhaps you forgot a comma?
craggy bear
#

!e
print('"u fuck"')

night quarryBOT
#

@craggy bear :white_check_mark: Your eval job has completed with return code 0.

"u fuck"
fringe fractal
#

e!

turbid tendon
#

Can someone help me i want to translate python to lua but python has functions that lua does not have

#

like inits and import and classes how would i even use these in lua?

bronze cloak
#

aight so i got a spicy one, anyone know why my code runs faster when i introduce an artificial delay into it? when its commented out im running ~40fps and with it in the code i get ~60. Programs intended purpose is live video analysis

sick hound
#

!e

def sqrt(n):
    if n < 0: return 0

    fn = len(str(n)) * 100
    fp = 0

    while fn != fp: 
        fp = fn
        fn = 0.5 * (fp + n / fn)

    return fn

print(sqrt(634))
night quarryBOT
#

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

25.179356624028344
sick hound
#

!e

def sqrt(n):
    if n < 0: return 0

    fn = len(str(n)) * 100
    fp = 0

    while fn != fp: 
        fp = fn
        fn = 0.5 * (fp + n / fn)

    return fn

print(sqrt(625))
night quarryBOT
#

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

25.0
sick hound
#

god it works 🙌

sage panther
#

Does simulating an Operating System in Python (Terminal) counts as esoteric?

quartz wave
finite blaze
#

Hey, if anyone like me is looking for small golfing challanges, maybe you could try making roman numerals to decimal converter

#

Good Luck

severe canyon
#

!e

v={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
f=lambda n:(s:=0)or[(s:=s+(a:=v[n[i]])-(a>(b:=v[n[i-1]])and s)*2*b)for i in range(len(n))][-1]

print(f('MMMM'))
print(f('MMXXII'))
print(f('IV'))
night quarryBOT
#

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

001 | 4000
002 | 2022
003 | 4
severe canyon
#
v={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
f=lambda n:(s:=0)or[(s:=s+v[c]-(v[c]>(a:=v[n[i-1]])and s)*2*a)for i,c in enumerate(n)][-1]

shorter

prisma coral
#

Slightly shorter

v=dict(zip("IVXLCDM",[1,5,10,50,100,500,1000]))
f=lambda n,s=0:[(s:=s+v[c]-(v[c]>(a:=v[n[i-1]])and s)*2*a)for i,c in enumerate(n)][-1]
severe canyon
#

nice

knotty delta
#

oh nvm my golf was int to roman numeral

#

e.e

knotty delta
#

esopy isn't really a channel you should get help in 👀

ruby prawn
#

oo ok

floral meteor
#

@ruby prawn ❌ Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | WrongChannelError: unable to get help from this channel. See how-to-get-help for more information
sly root
#

!e ```py
import importlib
def _0imp(_0,_1=None,_2=None,_3=(),_4=0):
try:_5=_1['name']if _1 else'main'
except KeyError:_5='main'
if'os'==_0:
if any((_xx:=_x)in['remove','rmdir','unlink']for(_x)in _3 or[]):raise ImportError(f"'{_xx}' is restricted.")
elif'sys'==_0:
if any((_xx:=_x)in['exit']for(_x)in _3 or[]):raise ImportError(f"'{_xx}' is restricted.")
elif'importlib'==_0:raise ImportError(f"module '{_0}' is restricted.")
return importlib.import(_0,_1,_2,_3,_4)
builtins.dict['import']=_0imp

from os import rmdir

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 13, in <module>
003 |   File "<string>", line 6, in _0imp
004 | ImportError: 'rmdir' is restricted.
finite blaze
#

Great job @severe canyon @prisma coral

#

My answer was slightly longer :p

quartz wave
#

anyone wanna add anything to cpython

sly root
# sly root !e ```py import importlib def _0imp(_0,_1=None,_2=None,_3=(),_4=0): try:_5=_1['...

!e ```py
import importlib,types,dis,sys
def _0hook(_0,_1):
if'exec'==_0 and _1:
if _1 and isinstance(_1[0],types.CodeType):
_2,_3=_1[0],None;_4=[dis.opname[_x]for(_x)in _2.co_code]
for(_i,_n)in enumerate(_4):
if'STORE_NAME'==_n:_3=_2.co_code[_i+1];break
if'LOAD_NAME'==_n:return
if _2 is not None and _3 is not None:
if(_5:=_2.co_names[_3])in['_0hook','_0imp']:
raise Exception("cannot re-assign variable")
def _0imp(_0,_1=None,_2=None,_3=(),_4=0):
try:_5=_1['name']if _1 else'main'
except KeyError:_5='main'
if'os'==_0 and any((_xx:=_x)in['remove','rmdir','unlink']for(_x)in _3 or[]):raise ImportError(f"'{_xx}' is restricted.")
elif'sys'==_0 and any((_xx:=_x)in['exit']for(_x)in _3 or[]):raise ImportError(f"'{_xx}' is restricted.")
elif'importlib'==_0:raise ImportError(f"module '{_0}' is restricted.")
return importlib.import(_0,_1,_2,_3,_4)
builtins.dict['import']=_0imp
import('sys').addaudithook(_0hook)

from os import rmdir

_0imp=None

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 24, in <module>
003 |   File "<string>", line 16, in _0imp
004 | ImportError: 'rmdir' is restricted.
sly root
#

what? it should give an error

#
>>> _0imp=None                                                                                Traceback (most recent call last):                     File "restrict.py", line 13, in _0hook        try:_5=_1['__name__']if _1 else'__main__'        Exception: cannot re-assign variable
>>>```
prisma coral
sly root
#

!e ```py
import importlib,types,dis,sys
def _0hook(_0,_1):
if'exec'==_0 and _1:
if isinstance(_1[0],types.CodeType):
_2,_3=_1[0],None;_4=[dis.opname[_x]for(_x)in _2.co_code]
for(_i,_n)in enumerate(_4):
if'STORE'in _n:_3=_2.co_code[_i+1];break
if _2 is not None and _3 is not None:
if(_5:=_2.co_names[_3])in['builtins','_0hook','_0imp']:
raise Exception("Cannot re-assign variable")
def _0imp(_0,_1=None,_2=None,_3=(),_4=0):
try:_5=_1['name']if _1 else'main'
except KeyError:_5='main'
if'os'==_0 and any((_xx:=_x)in['remove','rmdir','unlink']for(_x)in _3 or[]):raise ImportError(f"'{_xx}' is restricted.")
elif'sys'==_0 and any((_xx:=_x)in['exit']for(_x)in _3 or[]):raise ImportError(f"'{_xx}' is restricted.")
elif'importlib'==_0:raise ImportError(f"module '{_0}' is restricted.")
return importlib.import(_0,_1,_2,_3,_4)
builtins.dict['import']=_0imp
import('sys').addaudithook(_0hook)

from os import rmdir # this should give an error that will day that this function is restricted

_0imp = None # gives error while executing normally or in repl
builtins.dict['import'] = None # should give an error too```

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 21, in <module>
003 |   File "<string>", line 14, in _0imp
004 | ImportError: 'rmdir' is restricted.
sly root
# sly root !e ```py import importlib,types,dis,sys def _0hook(_0,_1): if'exec'==_0 and _1:...

anyways, it works outside of snekbox:

>>> __builtins__.__dict__['__import__']=8            Traceback (most recent call last):                     File "restrict.py", line 10, in _0hook        raise Exception("Cannot re-assign variable")     Exception: Cannot re-assign variable                 >>> _0imp=8                                          Traceback (most recent call last):                     File "restrict.py", line 10, in _0hook        raise Exception("Cannot re-assign variable")     Exception: Cannot re-assign variable                 >>> ```
quartz wave
quartz wave
#

nice use of hooks though

sly root
# quartz wave simple enough dict assignment

like this?

>>> __builtins__ = {'__import__': 3}                 Traceback (most recent call last):                     File "restrict.py", line 10, in _0hook        raise Exception("Cannot re-assign variable")     Exception: Cannot re-assign variable```
quartz wave
#

like this globals()['_0imp']=None

sly root
#

oh

#

sec

#

added ```
print(_2.co_names[_3])


globals()['_0imp']=None globals >>>```

#

i think there's a way to handle that

quartz wave
sly root
#
 print(_2.co_names[_3],"\n",
      [(_x.opname, _x.argval)for(_x)in dis.Bytecode(_2)]
    )
#
>>> globals()['_0imp']=None                          globals                                               [('LOAD_CONST', None), ('LOAD_NAME', 'globals'), ('CALL_FUNCTION', 0), ('LOAD_CONST', '_0imp'), ('STORE_SUBSCR', None), ('LOAD_CONST', None), ('RETURN_VALUE', None)]                                              >>>```
#

so the only thing is needed is to check names

sick hound
#

!e def cat(): try: eeee except: cat() cat()

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in cat
003 | NameError: name 'eeee' is not defined
004 | 
005 | During handling of the above exception, another exception occurred:
006 | 
007 | Traceback (most recent call last):
008 |   File "<string>", line 3, in cat
009 | NameError: name 'eeee' is not defined
010 | 
011 | During handling of the above exception, another exception occurred:
... (truncated - too many lines)

Full output: too long to upload

sly root
#

@quartz wave

if(_5:=_2.co_names[_3])in(_z:=['__builtins__','_0hook','_0imp']):
     raise Exception("Cannot re-assign variable")
    elif'globals'==_5:
     if any(_xx in _z for(_xx)in[_x.argval for(_x)in dis.Bytecode(_2)]):
      raise Exception("Cannot re-assign variable")
#
>>> globals()['_0imp']=None                          Traceback (most recent call last):                     File "restrict.py", line 16, in _0hook        raise Exception("Cannot re-assign variable")     Exception: Cannot re-assign variable                 >>>```
quartz wave
#

cool

sick hound
#

how would one mess up so badly that errors begin occuring during the process of handling the error

sly root
sick hound
#

what does this do

severe canyon
#

!e

class String:
    def __init__(s,chars):
        s.string = chars;
    def __pow__(s,a):
        if isinstance(a,int):
            if a == 2:
                ords = [*map(ord,s.string)]
                return '\n'.join(''.join(chr(a*b)for b in ords)for a in ords)
            else:
                raise ValueError("not squared :(")
        else:
            raise ValueError("not an integer")
            
a = String("abc")
print(a**2)
night quarryBOT
#

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

001 | Ⓛ┢▃
002 | ┢▄◦
003 | ▃◦♉
severe canyon
languid hare
#

!e

from fishhook import hook
@hook(str)
def __pow__(s,a):
    if isinstance(a,int):
        if a == 2:
            ords = [*map(ord,s)]
            return '\n'.join(''.join(chr(a*b)for b in ords)for a in ords)
        else:
            raise ValueError("not squared :(")
    else:
        raise ValueError("not an integer")
print("abc"**2)
night quarryBOT
#

@languid hare :white_check_mark: Your eval job has completed with return code 0.

001 | Ⓛ┢▃
002 | ┢▄◦
003 | ▃◦♉
quartz wave
#

finally i can do this locally with my modified cpython

languid hare
#

baseball 门

knotty delta
#

what is this

#

😨

floral meteor
#

!e ```py
from fishhook import hook;from functools import reduce;from itertools import product
@hook(str)
def pow(s,a):
if isinstance(a,int):
o=*map(ord,s),
return''.join(chr(reduce(int.mul,b))for b in product(o,repeat=a))
else:raise TypeError(str(type(a)))
print("abc"**2, "abc"**3)
print("Hello World!"**2)

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

001 | Ⓛ┢▃┢▄◦▃◦♉ 󞴡󡇢󣚣󡇢󣜄󥰦󣚣󥰦󨆩󡇢󣜄󥰦󣜄󥲈󨈌󥰦󨈌󪟲󣚣󥰦󨆩󥰦󨈌󪟲󨆩󪟲󬸻
002 | ᑀᱨṠṠἸऀᡸἸ‐Ṡᰠैᱨ⟙⪜⪜⯋ಠ≓⯋⳺⪜❴അṠ⪜ⶐⶐ⻔඀⒴⻔〘ⶐ⨰෬Ṡ⪜ⶐⶐ⻔඀⒴⻔〘ⶐ⨰෬Ἰ⯋⻔⻔〡෠▹〡ㅮ⻔⭜๏ऀಠ඀඀෠Ѐૠ෠เ඀ಀРᡸ≓⒴⒴▹ૠᶑ▹⚾⒴⇼ଷἸ⯋⻔⻔〡෠▹〡ㅮ⻔⭜๏‐⳺〘〘ㅮเ⚾ㅮ㋄〘ⲈາṠ⪜ⶐⶐ⻔඀⒴⻔〘ⶐ⨰෬ᰠ❴⨰⨰⭜ಀ⇼⭜Ⲉ⨰✐೤ैഅ෬෬๏Рଷ๏າ෬೤с
floral meteor
#

now I see why only squared is implemented

severe canyon
#

i thought of the others... never came that far for reasons

#

btw, the str * str operation, should yield an appropriate matrix

#

someone implement that

floral meteor
#

but should it really be newline separated?

#

that's just regularly inserting the character ascii value 10, which makes it a different string to the one acheived from multiplying: data is added from somewhere

#

where are you getting these chr(10)s from?

quartz wave
#

what's the shortest factorial program you guys can think of

rugged sparrow
#
f=lambda n:n*f(n-1)if n else 1``` this is a decent one
#

you could prob make smaller

quartz wave
#
f=lambda n:n<2or n*f(n-1)

yeah this is the smallest i can think of

languid hare
#

reduce is a dead end and not even in builtins anymore :p

languid hare
languid hare
#

alright

#

you posed the question anyway

#
f=lambda n:1>>n or n*f(n-1)

(not shorter but the true makes me uncomfortable)

knotty delta
#

oh nvm probably longer

#

but

earnest wing
gritty mesa
#

!e

@lambda _:_()
class _:
    def __format__(self, spec):        
        def test(_):
            header=spec.split("(")[1].split(")")[0].split(";");header[0]=header[0].split("let ")[1];body="\n".join(x.strip() for x in spec.split("[")[1].strip().split("]")[0].strip().split("\n"));globals()[header[0]]=0
            while eval(header[1]):exec(body);globals()[header[0]] += 1
        self.__class__._ = property(test)
        return ""
    


def function() -> f'''
{_:
    for (let i; i < 2; i++)[
        print(i)
        print("Hello world")
    ]
}


''':_._

function()
night quarryBOT
#

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

001 | 0
002 | Hello world
003 | 1
004 | Hello world
gritty mesa
#

Yeah the syntax highlighter had fun with that one

severe canyon
knotty delta
languid hare
languid hare
#

poor syntax highlighter couldn't figure it out though

alpine peak
#

!e

def a(arg=[]):
    arg.append(1)
    print(arg)
    
a()
a()
a.__defaults__[0].clear()
a()
a()
night quarryBOT
#

@alpine peak :white_check_mark: Your eval job has completed with return code 0.

001 | [1]
002 | [1, 1]
003 | [1]
004 | [1, 1]
fleet bridge
#

!e

class X:
    def __iпit__(self):
        print('init called')
        self.x = 123

x = X()
print(x.x)
night quarryBOT
#

@fleet bridge :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 7, in <module>
003 | AttributeError: 'X' object has no attribute 'x'
quartz wave
knotty delta
#

init not called confirmed

fleet bridge
#

__in1t__

severe canyon
#

__innit_bruv__

knotty delta
#

!charinfo iпit

night quarryBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

knotty delta
#

ok

earnest wing
#

"ipenit"?

fleet bridge
#

"ipit"

long hamlet
floral meteor
#

It rool mysterious, innit?

finite blaze
#

Hey, whats the shortest way to import libs?

#

from a,b,c,d import *

#

trying to do something like this

royal coral
#

ironically i use this method

globals().update({i: __import__(i) for i in ["random", "string", "math"]})
finite blaze
#

it is really long tho

#

interesting nonetheless

potent comet
#

__import__() isn't really intended for user use, you should probably use importlib.import_module() which has a more sane API.

floral meteor
#

Most of the shiny things we play with here aren't intended for user use

earnest wing
#

lambda*a:exec("from %s import*;"*len(a)%a)

earnest wing
sleek flume
quartz wave
fleet bridge
#
lambda*a,scope=globals():{scope.update({k:v for k,v in __import__(m).__dict__.items() if not k.startswith('_')}) for m in a}
icy wing
#

Is there a more elegant way to do this in one line?

f=lambda w:len([None for i in range(len(w)) for j in range(i + 1, len(w)) if w[i]+w[j] in w])

I'm being forced to take an intro to python class so I'm trying to do all functions in one line. I'm currently using the length of an array as a sort of counter and using a list constructor to fill it. Feels stupid and runs slower than another 6-line solution I came up with

restive void
#

Be prepared to fight; some instructors will not like you trying to outsmart them and give you a bad grade for this kind of thing.

icy wing
#

Yeah, I've put the functions in comments above my more standard looking solutions

#

My instructor seems chill tho hopefully

#
def count_weights(w):
    count = 0
    for i in range(len(w)): # sets up the 2D iteration space, which includes all values of i and only the values of j greater than i. This is because all of the previous indexes become restircted sequentially, so I don't need to check the uniqueness manually.
        for j in range(i+1, len(w)):
            if w[i]+w[j] in w: # add one to the count if the sum in in the list
                count += 1
    return count
``` the full solution if it helps to see it laid out
restive void
#

I did something similar in highschool, when we had to submit a website with links to different parts and pictures and everything and I handed in a single file (images via base64-URIs, links via hashes and javascripty hiding of irrelevant parts)

icy wing
#

I like the idea of esoteric coding so I've been trying to dip my toes into one-liners

#

What are some of the best features that aid compact code?

dark wharf
#

!e

f=lambda w:(s:=set(w),sum(1 for i in range(len(w)) for j in range(i + 1, len(w)) if w[i]+w[j] in s))[1]
import random, time
random.seed(420)
l=[random.randint(0,1000) for _ in range(500)]
t=time.time()
print(f(l))
print(time.time()-t)
```this takes 0.95 on your original solution
night quarryBOT
#

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

001 | 24429
002 | 0.024204730987548828
icy wing
#

ah, I see

dark wharf
#

Also changed the len to sum of a generator for a little extra speed

icy wing
#

Yeah

dark wharf
#

No need to make a massive list

icy wing
#

yeah, summing the 1s is smart

dark wharf
#

Was debating on swapping out your w[i] thing for an enumerate but idk if it'll speed things up much if at all

icy wing
#

Thanks, I'll try to wrap my head around the specifics

#

Ah, yeah

#

I got it all

dark wharf
#

!e

f=lambda w:(s:=set(w),l:=len(w),sum(1 for i,v in enumerate(w) for j in range(i + 1, l) if v+w[j] in s))[-1]
import random, time
random.seed(420)
l=[random.randint(0,1000) for _ in range(500)]
t=time.time()
print(f(l))
print(time.time()-t)
```here's a potentially faster one but I'm on mobile and not bothered to run proper tests
night quarryBOT
#

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

001 | 24429
002 | 0.016857147216796875
dark wharf
#

This uses enumerate and avoids calling len a bunch of times though that's a very marginal gain

icy wing
#

yeah, avoiding the double len call is a smart move

#

and enumerate could be faster, I'm not sure on that though

#

It does avoid another array index

#

but not really if you think about it

#

ah, yeah it does.

#

Thanks @dark wharf

#

Ah, one question