#esoteric-python

1 messages · Page 9 of 1

versed eagle
#

the python docs talks about it somewhere

quartz wave
#

__builtins__["__import__"] if __builtins__.__class__ is dict else __builtins__.__import__

versed eagle
ruby raft
#

@versed eagle can you please explain what you meant in this part

quartz wave
versed eagle
#

basically, the users file looks something like this:

import yourmodule
# then their code goes here

and then your module looks something like this

def preprocess(code):
    # do your preprocessing here
    return code
exec(preprocess(open(__import__("__main__").__file__).read()))
exit()
ruby raft
#

Right

versed eagle
ruby raft
#

Ah i get it

versed eagle
ruby raft
#

Will __main__ refer to the file that imports the module?

versed eagle
#

__main__ will be the file that is named here
|
\|/
python somefile.py

#

if you exec its code, then you'll get all modules it imports as well
because you'll set up import hooks

#

you do have to remove the import of your module, though, or exec will recurse

#

that would be part of the preprocessing

ruby raft
#

Ah yeah

solar tulip
#

Hey guys.

I have written some working code, but it really feels like I am doing something really simple that could work on one line.

#

!e

def min_next(x, *array):
    if x >= array[-1]: return array[-1], array[-1]
    if x <= array[0]: return array[0], array[1]
    for a in array[::-1]:
        if x >= a: 
            b = array[array.index(a)+1]
            return a, b
 
for x in range(17):
     print(x, 'times', min_next(x, 0,5,10,15))
        ```
night quarryBOT
#

@solar tulip :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 0 times (0, 5)
002 | 1 times (0, 5)
003 | 2 times (0, 5)
004 | 3 times (0, 5)
005 | 4 times (0, 5)
006 | 5 times (5, 10)
007 | 6 times (5, 10)
008 | 7 times (5, 10)
009 | 8 times (5, 10)
010 | 9 times (5, 10)
011 | 10 times (10, 15)
... (truncated - too many lines)

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

split kestrel
#

!e

import bisect

def min_next(x, *arr):
    return arr[bisect.bisect_right(arr, x) - 1]

for x in range(17):
    print(x, 'times', min_next(x, 0, 5, 10, 15))```
night quarryBOT
#

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

001 | 0 times 0
002 | 1 times 0
003 | 2 times 0
004 | 3 times 0
005 | 4 times 0
006 | 5 times 5
007 | 6 times 5
008 | 7 times 5
009 | 8 times 5
010 | 9 times 5
011 | 10 times 10
... (truncated - too many lines)

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

split kestrel
#

whoops forgot about edge cases

#

!e

import bisect

def min_next(x, *arr):
    i = bisect.bisect_right(arr, x)
    if i:
        return arr[i-1], arr[min(i, len(arr)-1)]
    else:
        return arr[0], arr[1]

for x in range(17):
    print(x, 'times', min_next(x, 0, 5, 10, 15))```
night quarryBOT
#

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

001 | 0 times (0, 5)
002 | 1 times (0, 5)
003 | 2 times (0, 5)
004 | 3 times (0, 5)
005 | 4 times (0, 5)
006 | 5 times (5, 10)
007 | 6 times (5, 10)
008 | 7 times (5, 10)
009 | 8 times (5, 10)
010 | 9 times (5, 10)
011 | 10 times (10, 15)
... (truncated - too many lines)

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

solar tulip
#

Oh wow if you need to import something just to simplify than my code seems to be not so bad.

#

!e

def min_next(x, *array):
    if x >= array[-1]: return array[-1], array[-1]
    if x <= array[0]: return array[0], array[1]
    for a in array[::-1]:
        if x >= a: 
            b = array[array.index(a)+1]
            return a, b
 
for x in range(17):
     print(x, 'times', min_next(x, 0,5,10,15))
        ```
night quarryBOT
#

@solar tulip :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 0 times (0, 5)
002 | 1 times (0, 5)
003 | 2 times (0, 5)
004 | 3 times (0, 5)
005 | 4 times (0, 5)
006 | 5 times (5, 10)
007 | 6 times (5, 10)
008 | 7 times (5, 10)
009 | 8 times (5, 10)
010 | 9 times (5, 10)
011 | 10 times (10, 15)
... (truncated - too many lines)

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

solar tulip
#

I guess I'll stick to that unless someone comes up with something way smarter...

versed eagle
solar tulip
#

True, but I don't know how.

#

Really thought this would be possible for such a non-complex function.

#

Sure you can do

_MN = lambda x, *arr: ...

earnest wing
#

The first couple checks can be easily converted into an expression

versed eagle
#

multiple statements -> tuple
function definition -> lambda
class definition -> type
import -> __import__
for loop -> {stuff for var in somelist}
for loop to make a list -> [var for var in somelist]
while loop -> {stuff for i in iter((lambda: boolean_expression), end_value)}
if statement -> ternary, or multiplication if you're dealing with integers/strings and want to take less chars

earnest wing
#

The for loop can be turned into a generator with next() since you just return the first matching instance.

solar tulip
#

However never used next() before.

earnest wing
#

It just fetches the next value from an iterator

#

in this case next(blah for a in array[::-1] if x >= a) is equivalent, I think

#

at least, assuming this loop always succeeds at least once

#

I don't remember whether next() raises on empty iterators

versed eagle
#

it raises StopIteration

solar tulip
#

Can I return two values with lambda?

earnest wing
#

yeah, that's just a tuple

#

it needs parentheses though

solar tulip
#

Makes sense.

#

_MN = lambda x, *arr: ([a for a in arr[::-1] if x >= a], [a for a in arr[0] if x <= a])```
#

This will probably fail horribly.

versed eagle
solar tulip
#

I'll just try.

versed eagle
#

probably better to have arr be a list of lists?
like lambda x, arr
so that its required

#

idk

solar tulip
#

Ah wait.

#

!e


_MN = lambda x, *arr: ([a for a in arr[::-1] if x >= a], [a for a in arr[0] if x <= a])

print(_MN(3, 0,2,3,4))```
#

!e


_MN = lambda x, *arr: (next(a for a in arr[::-1] if x >= a), next(a for a in arr if x <= a))

print(_MN(3, 0,2,3,4))```
night quarryBOT
#

@solar tulip :white_check_mark: Your 3.11 eval job has completed with return code 0.

(3, 3)
solar tulip
#

!e


_MN = lambda x, *arr: (next(a for a in arr[::-1] if x >= a), next(a for a in arr if x <= a))

print(_MN(0, 0,2,3,4))```
night quarryBOT
#

@solar tulip :white_check_mark: Your 3.11 eval job has completed with return code 0.

(0, 0)
solar tulip
#

False. Need 0, 2

#

!e


_MN = lambda x, *arr: (next(a for a in arr[::-1] if x >= a), next(a for a in arr if x <= a))

print(_MN(4, 0,2,3,4))```
night quarryBOT
#

@solar tulip :white_check_mark: Your 3.11 eval job has completed with return code 0.

(4, 4)
solar tulip
#

This is correct.

#

!e


_MN = lambda x, *arr: (next(a for a in arr[::-1] if x >= a), next(a for a in arr if x <= a))

print(_MN(3, 0,2,3,4))```
night quarryBOT
#

@solar tulip :white_check_mark: Your 3.11 eval job has completed with return code 0.

(3, 3)
solar tulip
#

False. Need 3, 4

#

So only if x > max(arr) it works.

versed eagle
#
_MN=lambda x,*arr:(arr[-1],)*2 if x>=arr[-1]else((arr[0],arr[1])if x<=arr[0]else[(a,arr[i+1])for i,a in enumerate(arr)if x>=a][0])
#

try that

#

it should copy the exact behaviour of your original code
can be shortened further, but first i wanna see if it works

solar tulip
#

!e

_MN=lambda x,*arr:(array[-1],)*2 if x>=arr[-1]else((array[0],)*2 if x<=arr[0]else [(a, array[i+1])for i,a in enumerate(array) if x >= a][0])

print(_MN(0, 0,1,2,3,4))
print(_MN(1, 0,1,2,3,4))
print(_MN(4, 0,1,2,3,4))
night quarryBOT
#

@solar tulip :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 |   File "<string>", line 1, in <lambda>
004 | NameError: name 'array' is not defined
versed eagle
#

oops

#

that should be arr

#

i edited my code to fix that

solar tulip
#

!e

_MN=lambda x,*arr:(arr[-1],)*2 if x>=arr[-1]else((arr[0],)*2 if x<=arr[0]else [(a, arr[i+1])for i,a in enumerate(arr) if x >= a][0])

print(_MN(0, 0,1,2,3,4))
print(_MN(1, 0,1,2,3,4))
print(_MN(4, 0,1,2,3,4))
night quarryBOT
#

@solar tulip :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | (0, 0)
002 | (0, 1)
003 | (4, 4)
versed eagle
#

is that correct?

solar tulip
#

For x == 0 output must be 0, 1

#

Else is true.

versed eagle
solar tulip
#

No problem

versed eagle
#
_MN=lambda x,*arr:(arr[-1],)*2 if x>=arr[-1]else((arr[0],arr[1])if x<=arr[0]else[(a,arr[i+1])for i,a in enumerate(arr)if x>=a][0])
#

fixed version

solar tulip
#
_MN=lambda x,*arr:(arr[-1],)*2 if x>=arr[-1]else((arr[0],arr[1])if x<=arr[0]else[(a,arr[i+1])for i,a in enumerate(arr)if x>=a][0])

print(_MN(0, 0,1,2,3,4))
print(_MN(1, 0,1,2,3,4))
print(_MN(4, 0,1,2,3,4))
#

!e

_MN=lambda x,*arr:(arr[-1],)*2 if x>=arr[-1]else((arr[0],arr[1])if x<=arr[0]else[(a,arr[i+1])for i,a in enumerate(arr)if x>=a][0])

print(_MN(0, 0,1,2,3,4))
print(_MN(1, 0,1,2,3,4))
print(_MN(4, 0,1,2,3,4))
night quarryBOT
#

@solar tulip :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | (0, 1)
002 | (0, 1)
003 | (4, 4)
versed eagle
#

is that correct?

solar tulip
#

Nope.

#

For x == 1 ouput must be 1, 2

versed eagle
#

hm

solar tulip
#

What type of encoding do you need.

#

There are many ways to encode and decode.

#

You can encode with XOR bitwise for example.

versed eagle
#
# utf-8 is arbitrary, you can pick whichever one you like
b = bytes(yourstring, "utf-8")
decoded = b.decode("utf-8")
#

if you're looking for something like that, try import base64

solar tulip
#

Can you tell me the exact usecase?

#

Then I can tell you a solution.

#

I see.

#

Should be easy.

#

Sure you can send it to me privately.

split kestrel
#

!e

def min_next(x, *a):
    i = a.index(max([n for n in a if n <= x] + [a[0]]))
    return a[i], a[min(i+1, len(a)-1)]

for x in range(17):
    print(x, 'times', min_next(x, 2, 5, 10, 15))
night quarryBOT
#

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

001 | 0 times (2, 5)
002 | 1 times (2, 5)
003 | 2 times (2, 5)
004 | 3 times (2, 5)
005 | 4 times (2, 5)
006 | 5 times (5, 10)
007 | 6 times (5, 10)
008 | 7 times (5, 10)
009 | 8 times (5, 10)
010 | 9 times (5, 10)
011 | 10 times (10, 15)
... (truncated - too many lines)

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

solar tulip
#

For x == 0 it must be (0, 5) in this case.

split kestrel
#

!e

def min_next(x, *a):
    i = a.index(max([n for n in a if n <= x] + [a[0]]))
    return min(x, a[i]), a[min(i+1, len(a)-1)]

for x in range(17):
    print(x, 'times', min_next(x, 2, 5, 10, 15))
night quarryBOT
#

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

001 | 0 times (0, 5)
002 | 1 times (1, 5)
003 | 2 times (2, 5)
004 | 3 times (2, 5)
005 | 4 times (2, 5)
006 | 5 times (5, 10)
007 | 6 times (5, 10)
008 | 7 times (5, 10)
009 | 8 times (5, 10)
010 | 9 times (5, 10)
011 | 10 times (10, 15)
... (truncated - too many lines)

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

split kestrel
#

like this?

solar tulip
#

!e

def min_next(x, *array):
    if x >= array[-1]: return array[-1], array[-1]
    if x <= array[0]: return array[0], array[1]
    for a in array[::-1]:
        if x >= a: 
            b = array[array.index(a)+1]
            return a, b
 
for x in range(17):
     print(x, 'times', min_next(x, 0,5,10,15))
        ```
night quarryBOT
#

@solar tulip :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 0 times (0, 5)
002 | 1 times (0, 5)
003 | 2 times (0, 5)
004 | 3 times (0, 5)
005 | 4 times (0, 5)
006 | 5 times (5, 10)
007 | 6 times (5, 10)
008 | 7 times (5, 10)
009 | 8 times (5, 10)
010 | 9 times (5, 10)
011 | 10 times (10, 15)
... (truncated - too many lines)

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

solar tulip
#

Exactly like this.

#

The code is just bloated.

#

x = 0
Output: 0, 5
x = 5
Output: 5, 10
x = 6
Output: 6, 10
x = 16
Output: 15, 15

#

You see? The first number of the output states the highest number of the array that is equal or smaller than x.

#

The second number of the output states the next number of the array that comes after.

split kestrel
solar tulip
#

For x ==1 the ourput is (1, 5) but 1 is not the lowest number of the array that is higher than x.

#

In fact 1 is not part of array.

#

The array is 2, 5, 10, 15 in your code.

#

If x == 0:
Output must be 0, 5
If x == 4:
Output must be 0, 5
If x == 5:
Output must be 5, 10
If x == 14:
Output must be 10, 15
If x == 15:
Output must be 15, 15

solar tulip
#
_MN = lambda x, *arr:
    (
    [
    ( b := 
next(a for a in arr[::-1] if x >= a)
    )
    ]
    ,
    [
    arr[arr.index(b)+1]
    ]
    )
#

!e

_MN = lambda x, *arr: ([( b := next(a for a in arr[::-a] if x >= a))], [arr[arr.index(b)+1] if b != arr[-1] else arr[-1]])

print(_MN(0, 0,1,2,3,4))
print(_MN(1, 0,1,2,3,4))
print(_MN(4, 0,1,2,3,4))```
#

!e

_MN = lambda x, *arr: ([( b := next(a for a in arr[::-a] if x >= a))], [arr[arr.index(b)+1] if b != arr[-1] else arr[-1]])

print(_MN(0, 0,1,2,3,4))
print(_MN(1, 0,1,2,3,4))
print(_MN(4, 0,1,2,3,4))```
night quarryBOT
#

@solar tulip :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 |   File "<string>", line 1, in <lambda>
004 | NameError: name 'a' is not defined
solar tulip
#

I knew it would fail c.c

#

!e

_MN = lambda x, *arr: ([( b := next(a for a in arr[::-1] if x >= a))], [arr[arr.index(b)+1] if b != arr[-1] else arr[-1]])

print(_MN(0, 0,1,2,3,4))
print(_MN(1, 0,1,2,3,4))
print(_MN(4, 0,1,2,3,4))```
night quarryBOT
#

@solar tulip :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | ([0], [1])
002 | ([1], [2])
003 | ([4], [4])
solar tulip
#

The f is even that.

#

!e

_MN = lambda x, *arr: ([( b := next(a for a in arr[::-1] if x >= a))], [arr[arr.index(b)+1] if b != arr[-1] else arr[-1]])

print(_MN(0, 0,1,2,3,4))
print(_MN(1, 0,1,2,3,4))
print(_MN(5, 0,1,2,3,4))```
night quarryBOT
#

@solar tulip :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | ([0], [1])
002 | ([1], [2])
003 | ([4], [4])
solar tulip
#

Wait it works?

#

No fucking way did I do it on my own?

#

!e

_MN = lambda x, *arr: ([( b := next(a for a in arr[::-1] if x >= a))], [arr[arr.index(b)+1] if b != arr[-1] else arr[-1]])

print(_MN(0, 0,5,15,16,35))
print(_MN(4, 0,5,15,16,35))
print(_MN(5, 0,5,15,16,35))
print(_MN(16, 0,5,15,16,35))
print(_MN(35, 0,5,15,16,35))
night quarryBOT
#

@solar tulip :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | ([0], [5])
002 | ([0], [5])
003 | ([5], [15])
004 | ([16], [35])
005 | ([35], [35])
solar tulip
#

I fucking did it. I am a fcking legend.

#

!e

_MN = lambda x, *arr: (( b := next(a for a in arr[::-1] if x >= a)), arr[arr.index(b)+1] if b != arr[-1] else arr[-1])

print(_MN(0, 0,5,15,16,35))
print(_MN(4, 0,5,15,16,35))
print(_MN(5, 0,5,15,16,35))
print(_MN(16, 0,5,15,16,35))
print(_MN(35, 0,5,15,16,35))
night quarryBOT
#

@solar tulip :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | (0, 5)
002 | (0, 5)
003 | (5, 15)
004 | (16, 35)
005 | (35, 35)
solar tulip
#

Yep this is what I needed.

#

@earnest wing thanks! @split kestrel thanks!

night quarryBOT
gleaming timber
#
tuple=lambda _:*_,```
gleaming timber
#

!e py tuple=lambda _:*_,

night quarryBOT
#

@gleaming timber :x: Your 3.11 eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     tuple=lambda _:*_,
003 |                    ^
004 | SyntaxError: invalid syntax
gleaming timber
#

bruh

#

!e py tuple=lambda _:(*_,) print(tuple([1, 2, 3]))

night quarryBOT
#

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

(1, 2, 3)
pastel sparrow
orchid nymph
#
m=lambda x,*a:(x,a[str([x>=i for i in a]).find("F")//6])
m=lambda x,*a:(x,a[str([x<i for i in a]).find("T")//7])
solar tulip
#

!e

_MN=lambda x,*a:(x,a[b.index(0)if 0 in(b:=[x>=i for i in a])else -1])


print(_MN(0, 0,5,15,16,35))
print(_MN(4, 0,5,15,16,35))
print(_MN(5, 0,5,15,16,35))
print(_MN(16, 0,5,15,16,35))
print(_MN(35, 0,5,15,16,35))```
night quarryBOT
#

@solar tulip :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | (0, 5)
002 | (4, 5)
003 | (5, 15)
004 | (16, 35)
005 | (35, 35)
solar tulip
#

!e

_MN=lambda x,*a:(x,a[-all(b:=[x>=i for i in a])or b.index(0)])


print(_MN(0, 0,5,15,16,35))
print(_MN(4, 0,5,15,16,35))
print(_MN(5, 0,5,15,16,35))
print(_MN(16, 0,5,15,16,35))
print(_MN(35, 0,5,15,16,35))```
night quarryBOT
#

@solar tulip :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | (0, 5)
002 | (4, 5)
003 | (5, 15)
004 | (16, 35)
005 | (35, 35)
pastel sparrow
#

wait did i misunderstand what it was supposed to do

#

LMAO

#

just realised the output is different

#

yeah i did oops

#

golfed it wrongly

solar tulip
#

Is the output not exactly the same?

pastel sparrow
#

nope

solar tulip
#

Where is the difference?

pastel sparrow
#

002 | (0, 5)

#

002 | (4, 5)

solar tulip
#

001 | (0, 5)
002 | (4, 5)

==

001 | (0, 5)
002 | (4, 5)

#

What do you mean? It is the same,

pastel sparrow
solar tulip
#

Ahhh

#

Just looked at the new code.

#

Yes in both cases the output is wrong.

#

!e

_MN = lambda x, *arr: (( b := next(a for a in arr[::-1] if x >= a)), arr[arr.index(b)+1] if b != arr[-1] else arr[-1])

print(_MN(0, 0,5,15,16,35))
print(_MN(4, 0,5,15,16,35))
print(_MN(5, 0,5,15,16,35))
print(_MN(16, 0,5,15,16,35))
print(_MN(35, 0,5,15,16,35))
night quarryBOT
#

@solar tulip :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | (0, 5)
002 | (0, 5)
003 | (5, 15)
004 | (16, 35)
005 | (35, 35)
solar tulip
#

So far this is the only correct solution on one line.

solar tulip
sick hound
#

Whats this?

solar tulip
#

Which one?

sick hound
#

!e

print("Hello")
night quarryBOT
#

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

Hello
sick hound
#

Esotric Python

solar tulip
#

Esoteric Python is for code optimization OR writing code on one line.

#

Basicly we are the big brains.

orchid nymph
#

but added a little trick

versed eagle
#

!e

(lambda f:(lambda*a,**k:f(*a,**k)))(print)("Hello world")
night quarryBOT
#

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

Hello world
versed eagle
#

mildly esoteric

solar tulip
#

That is a stroke.

sick hound
#

Brain.exe stopped working...

solar tulip
versed eagle
sick hound
#

No .exe.

solar tulip
#

brain.json is also acceptable.

#

You sure?

versed eagle
sick hound
#

Brain.png 🧠

solar tulip
#

Hahahah.

#

Png is actually really funny.

versed eagle
#

yeah

#

I started laughing in the middle of class and everyone stared at me

sick hound
#

Lol

solar tulip
#

Lmao.

sick hound
#

Felt good to hear that.

#

I mean because I could make you laugh.

#

Not because everyone stared at you.

solar tulip
#

Yea esotheric-python is also not about beeing political correct.

#

No need to clearify intentions to protect feelings.

sick hound
#

0.0

solar tulip
#

Now I got you interested, am I right?

sick hound
#

Wdym

#

Interested in what?

solar tulip
#

I don't.

sick hound
orchid nymph
#
m=lambda x,*a:(b:=a[i:=([x>=e for e in a]+[0]).index(0)-1],(a+a[-1:])[i+1])
solar tulip
#

!e

_MN=lambda x,*a:(b:=a[i:=([x>=e for e in a]+[0]).index(0)-1],(a+a[-1:])[i+1])

print(_MN(0, 0,5,15,16,35))
print(_MN(4, 0,5,15,16,35))
print(_MN(5, 0,5,15,16,35))
print(_MN(16, 0,5,15,16,35))
print(_MN(35, 0,5,15,16,35))```
night quarryBOT
#

@solar tulip :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | (0, 5)
002 | (0, 5)
003 | (5, 15)
004 | (16, 35)
005 | (35, 35)
orchid nymph
#

!e

m=lambda x,*a:(b:=a[i:=([x>=e for e in a]+[0]).index(0)-1],(a+a[-1:])[i+1])

print(m(0, 0,5,15,16,35))
print(m(4, 0,5,15,16,35))
print(m(5, 0,5,15,16,35))
print(m(16, 0,5,15,16,35))
print(m(35, 0,5,15,16,35))
night quarryBOT
#

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

001 | (0, 5)
002 | (0, 5)
003 | (5, 15)
004 | (16, 35)
005 | (35, 35)
solar tulip
#

That works.

sick hound
#

!e

(lambda x: print(x+10))(10)
solar tulip
#

No clue why it works but it does.

night quarryBOT
#

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

20
sick hound
#

hmm

solar tulip
#

m=lambda x,*a:
(b:=a [
i := ([x>=e for e in a]+[0]).index(0)-1],
(a+a[-1:])[i+1])

#

Dude that is fcking complicated.

orchid nymph
#
m=lambda x,*a:(b:=a[i:=(*[x>=e for e in a],0).index(0)-1],(a+a[-1:])[i+1])
solar tulip
#

!e

_MN = lambda x,*a:(b:=a[i:=(*[x>=e for e in a],0).index(0)-1],(a+a[-1:])[i+1])

print(_MN(0, 0,5,15,16,35))
print(_MN(4, 0,5,15,16,35))
print(_MN(5, 0,5,15,16,35))
print(_MN(16, 0,5,15,16,35))
print(_MN(35, 0,5,15,16,35))```
night quarryBOT
#

@solar tulip :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | (0, 5)
002 | (0, 5)
003 | (5, 15)
004 | (16, 35)
005 | (35, 35)
solar tulip
#

Also works.

#

What is going on though?

orchid nymph
#

ow forgot to remove b:=

#
m=lambda x,*a:(a[i:=(*[x>=e for e in a],0).index(0)-1],(a+a[-1:])[i+1])
solar tulip
#

!e

_MN = lambda x,*a:(a[i:=(*[x>=e for e in a],0).index(0)-1],(a+a[-1:])[i+1])

print(_MN(0, 0,5,15,16,35))
print(_MN(4, 0,5,15,16,35))
print(_MN(5, 0,5,15,16,35))
print(_MN(16, 0,5,15,16,35))
print(_MN(35, 0,5,15,16,35))```
night quarryBOT
#

@solar tulip :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | (0, 5)
002 | (0, 5)
003 | (5, 15)
004 | (16, 35)
005 | (35, 35)
solar tulip
#

Also works.

#

Soo... Can you explain?

orchid nymph
#

so
(*[x>=e for e in a],0).index(0) searches for the index of first element in a that is > x

solar tulip
#

Makes sense so far.

orchid nymph
#

I added 0 in last in case all of them <=x

#

and then -1 to get element before that

solar tulip
#

What does the * do?

orchid nymph
#

unpacks the list in tuple (*[1,2,3],) => (1,2,3)

#

(*[1,2,3],4) => (1,2,3,4)

solar tulip
#

That is nice to know.

#

So in other words if x>= e in a returns all e that are <= x

#

?

orchid nymph
#

(*[x>=e for e in a],0) => list where element = True if e=<x else False .index(0) find the index of the first False/0 (e>x) and then -1 to get the index of the last e=<x

#
m=lambda x,*a:(a+a[-1:])[(*(x>=e for e in a),0).index(0)-1:][:2]
solar tulip
#

!e

_MN = lambda x,*a:(a+a[-1:])[(*(x<e for e in a),1).index(1)-1:][:2]

print(_MN(0, 0,5,15,16,35))
print(_MN(4, 0,5,15,16,35))
print(_MN(5, 0,5,15,16,35))
print(_MN(16, 0,5,15,16,35))
print(_MN(35, 0,5,15,16,35))```
night quarryBOT
#

@solar tulip :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | (0, 5)
002 | (0, 5)
003 | (5, 15)
004 | (16, 35)
005 | (35, 35)
arctic skiff
#

even compass are not allowed in my in school they say use your hand

orchid nymph
solar tulip
#

!e

_MN = lambda x,*a:(a+a[-1:])[(*(x<e for e in a),1).index(1)-1:][:2]

print(_MN(0, 0,5,15,16,35))
print(_MN(4, 0,5,15,16,35))
print(_MN(5, 0,5,15,16,35))
print(_MN(16, 0,5,15,16,35))
print(_MN(35, 0,5,15,16,35))```
night quarryBOT
#

@solar tulip :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | (0, 5)
002 | (0, 5)
003 | (5, 15)
004 | (16, 35)
005 | (35, 35)
pastel sparrow
#

the whole thing

#

nice

#

thought of using recursion but couldn't get it to work

wintry mulch
#

!e

night quarryBOT
#
Missing required argument

code

solar tulip
#

!e

# do nothing
night quarryBOT
#

@solar tulip :warning: Your 3.11 eval job has completed with return code 0.

[No output]
solar tulip
#

🙂

solar tulip
#

!e

_MN = lambda x,*a:(a+a[-1:])[(*(x<e for e in a),1).index(1)-1:][:2]

print(_MN(0, 0,5,15,16,35))
print(_MN(4, 0,5,15,16,35))
print(_MN(5, 0,5,15,16,35))
print(_MN(16, 0,5,15,16,35))
print(_MN(35, 0,5,15,16,35))```
night quarryBOT
#

@solar tulip :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | (0, 5)
002 | (0, 5)
003 | (5, 15)
004 | (16, 35)
005 | (35, 35)
solar tulip
#

!e

_MN = lambda x,*a:(a+a[-1:])[(*(x<e for e in a),1).index(1)-1:][:]

print(_MN(0, 0,5,15,16,35))
print(_MN(4, 0,5,15,16,35))
print(_MN(5, 0,5,15,16,35))
print(_MN(16, 0,5,15,16,35))
print(_MN(35, 0,5,15,16,35))```
night quarryBOT
#

@solar tulip :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | (0, 5, 15, 16, 35, 35)
002 | (0, 5, 15, 16, 35, 35)
003 | (5, 15, 16, 35, 35)
004 | (16, 35, 35)
005 | (35, 35)
solar tulip
#

!e

_MN = lambda x, *a: [(a:=a[1:]) for _ in a]
print(_MN(0, 0,5,15,16,35))
print(_MN(4, 0,5,15,16,35))```
last locust
#

You might be wanting if f > a[x]

#

if x > a[f] means you'll be doing a[35] which isn't right

solar tulip
#

No no. X is a number that is either larger than a[_] or smaller, or equal.
I am trying to dump all numbers of the array that are smaller than x.

last locust
#

Since f is already the item inside a

#

for _ in a -> for f in a

solar tulip
#

Hmm...

#

v

#

!e

_MN = lambda x, *a: [(a:=a[1:]) for _ in a if x >= _]
print(_MN(12, 0,5,15,16,35))
print(_MN(4, 0,5,15,16,35))```
night quarryBOT
#

@solar tulip :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | [(5, 15, 16, 35), (15, 16, 35)]
002 | [(5, 15, 16, 35)]
solar tulip
#

Why does it return two touples?

versed eagle
versed eagle
opaque quiver
#

guys

#

help i learn python and i cunfused a class

#

def list_of_case(self):
lisx=[]
for gulty in self.bomb:
lisx.append(gulty['category'])
return lisx

#

and allways it give to me a type error

#

for it gives to me from for loop

ruby raft
#

I dont want to write an interpreter just for that

#

I cant use the ast module because it wouldnt be able to parse the custom syntax in the file

#

Unless I can somehow make it stop once the import line is found

#

or I preprocess the custom syntax first and then ast parse it hmmm

#

but that wouldnt be efficient

solar tulip
#

!e

_MN = lambda x,*a:(a+a[-1:])[(*(x<e for e in a),1).index(1)-1:][:2]

print(_MN(0, 0,5,15,16,35))
print(_MN(4, 0,5,15,16,35))
print(_MN(5, 0,5,15,16,35))
print(_MN(16, 0,5,15,16,35))
print(_MN(35, 0,5,15,16,35))```
night quarryBOT
#

@solar tulip :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | (0, 5)
002 | (0, 5)
003 | (5, 15)
004 | (16, 35)
005 | (35, 35)
solar tulip
#
_MN = lambda x,*a:(b:=a[i:=(*[x>=e for e in a],0).index(0)-1],(a+a[-1:])[i+1])
quartz wave
solar tulip
#

What is that 😂

#
    xy, ct = '', 0
    for number in list(sorted(numbers)):
        xy += str(number)+'x '
        for user in unique:
            if number == total.count(user):
                ct += 1
        xy += str(ct)+' | '
        ct = 0```
#

I want to simplify this now.

quartz wave
#
xy=''.join(f"{n}x {sum(n==total.count(u)for u in unique)} | "for n in sorted(numbers))
solar tulip
#

Does not look like the string is constructed properly.

#

You sure?

#

If yes I will try it in code.

quartz wave
solar tulip
#
STR, CT = '', 0
for NR in list(sorted(array)):
    STR += str(NR) + 'x '
    for user in unique:
        if NR == total.count(user):
            CT += 1
    STR += str(CT) + ' | '
    ct = 0```
#

Its the same.

quartz wave
solar tulip
#

Okay I will try the code.

#
xy=''.join(f"{n}x {sum(n==total.count(u)for u in unique)} | "for n in sorted(numbers))
#

Yes it works.

#

Wow awesome!

wispy ivy
#

Hello smart peoples!
How do I optimise this for speed?

def search_pascal_multiples_fast(row_limit):
    triangle = [[1]]
    for i in range(row_limit):
        triangle.append([1] + [triangle[i][j-1] + triangle[i][j] for j in range(1, len(triangle[i]))] + [1])
    return sorted([number for number, count in Counter([number for row in [row[1:-2] for row in triangle] for number in row]).items() if count > 3])

After many benchmarking the return is what slow the program by a lot

versed eagle
#

i have a version independent way

night quarryBOT
#

Hey @versed eagle!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

versed eagle
#

works on 3.8, 3.9, and 3.11.0rc1

#

@mellow salmon @quartz wave
got it in a version independent way

#

:D

vague cairn
#

second, the line with sorted([]) is probably much higher omega than you need.

#

for instance:

                   Counter([
                       number
                       for row in triangle
                       for number in row[1:-2]
                       ]).items()
                   if count > 3
                   ])```
skips building a huge list several dozen times. so it's both is less memory intense, and maybe a little less processor intense.
vague cairn
#

replacing your list comprehensions with generators speeds up another few thousandths.

return sorted((number for number, count in
                   Counter((
                       number
                       for row in triangle
                       for number in row[1:-2]
                       )).items()
                   if count > 3
                   ))```
#

The triangle is symmetrical, You could in theory only generate half of it. you could also cache the contents of the counter after each row, it really depends on how you are going to be calling this.

vague cairn
#

Something like this could be useful, but I'm not sure it's better than just memoizeing the function.

from collections import Counter
triangle = [[1]]
counters = []
def search_pascal_multiples_fast(row_limit):
    for i in range(len(triangle)-1, row_limit):
        triangle.append([1] + [triangle[i][j-1] + triangle[i][j] for j in range(1, len(triangle[i]))] + [1])
        counters.append(Counter(triangle[-1][1:-2]))

    c = Counter()
    {c.update(counter)
     for counter in counters[0:row_limit]
     }
    
    return sorted((number
                   for number, count in c.items()
                   if count > 3
                   ))```
#

it really depends on how you're using it.

wispy ivy
#

You are a monster

#

Took me like 15 hours to get to mine and you did that so quick

#

ty so much

wispy ivy
split kestrel
#

I saw your post in #algos-and-data-structs earlier and you definitely nerd sniped me for the better part of the day
I mostly worked on a different but similar problem (count the number of times something appears in the triangle) but looking at this you should be able to speed it up by only keeping track of the current and previous rows```py
def search1(row_limit):
c = Counter()
prev_row = []
for i in range(3, row_limit+1):
prev_row = [i, *starmap(add, zip(prev_row, prev_row[1:])), i]
c.update(prev_row)

return sorted(v for v, n in c.items() if v > row_limit and n > 3 or n > 5)
You could also take advantage of the fact that the second column of the triangle contains every number (very small speedup)```py
def search2(row_limit):
    c = Counter()
    prev_row = []
    for i in range(4, row_limit):
        edge = i*(i+1)//2
        prev_row = [edge, *starmap(add, zip(prev_row, prev_row[1:])), edge]
        c.update(prev_row)
    
    return sorted(v for v, n in c.items() if n > 3)
#

Oh yeah imports
Counter is from collections,
add is from operator,
and starmap is from itertools

… which reminds me of itertools's pairwise (3.10+)
zip(prev_row, prev_row[1:]) can be replaced with pairwise(prev_row)
It doesn't really speed it up, but it can be more readable

wispy ivy
#

Gonna look into it ty 🙂

quartz wave
#
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method object.__sizeof__() needs an argument
#

in the REPL it doesn't

quartz wave
#

a simple solution is to just execute a custom function to get its index, obfuscate that index, and do __name__.__class__.__base__.__subclasses__().__getitem__(<obfuscated index>)

fleet bridge
#

!e

c = lambda n: next(c for c in object.__subclasses__() if c.__name__ == n)
print(c('int'))
print(c('type'))
print(c('str'))
print(c('function'))
print(c('code'))
night quarryBOT
#

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

001 | <class 'int'>
002 | <class 'type'>
003 | <class 'str'>
004 | <class 'function'>
005 | <class 'code'>
fleet bridge
#

version-independent way to get some class, if you know its name

quartz wave
fleet bridge
#

!e

bltndict = __builtins__.__dict__ if __builtins__.__class__.__name__.__len__() == 6 else __builtins__
n = ().__len__().__class__.__name__.__getitem__(((),).__len__())
e = ().__class__.__class__.__name__.__getitem__(((),).__len__().__neg__())
complex = ((),).__len__().__truediv__(((),).__len__().__add__(((),).__len__())).__rpow__(((),).__len__().__neg__())
x = complex.__class__.__name__.__getitem__(((),).__len__().__neg__())
t = ().__len__().__class__.__name__.__getitem__(((),).__len__().__neg__())
next = bltndict.__getitem__(n + e + x + t)
_ = lambda __: next(_ for(_)in().__class__.__base__.__subclasses__()if _.__name__==__)
print(_('int'))
print(_('type'))
print(_('str'))
print(_('function'))
print(_('code'))

night quarryBOT
#

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

001 | <class 'int'>
002 | <class 'type'>
003 | <class 'str'>
004 | <class 'function'>
005 | <class 'code'>
fleet bridge
#

== 6 oh, forgot that

quartz wave
#

() (and by extension ((),)) is a constant

fleet bridge
#
zero = ().__len__()
neg_one = zero.__invert__()
one = neg_one.__neg__()
bltndict = __builtins__.__dict__ if __builtins__.__class__.__name__.__len__() == one.__add__(one).__add__(one).__mul__(one.__add__(one)) else __builtins__
n = ().__len__().__class__.__name__.__getitem__(one)
e = ().__class__.__class__.__name__.__getitem__(neg_one)
complex = one.__truediv__(one.__add__(one)).__rpow__(neg_one)
x = complex.__class__.__name__.__getitem__(neg_one)
t = ().__len__().__class__.__name__.__getitem__(neg_one)
next = bltndict.__getitem__(n + e + x + t)
_ = lambda __: next(_ for(_)in().__class__.__base__.__subclasses__()if _.__name__==__)

print(_('int'))
print(_('type'))
print(_('str'))
print(_('function'))
print(_('code'))

no ((),), but () exists

#
zero = __name__.__class__().__len__()
neg_one = zero.__invert__()
one = neg_one.__neg__()
bltndict = __builtins__.__dict__ if __builtins__.__class__.__name__.__len__() == one.__add__(one).__add__(one).__mul__(one.__add__(one)) else __builtins__
n = zero.__class__.__name__.__getitem__(one)
e = __name__.__class__.__base__.__name__.__getitem__(neg_one.__add__(neg_one).__add__(neg_one))
complex = one.__truediv__(one.__add__(one)).__rpow__(neg_one)
x = complex.__class__.__name__.__getitem__(neg_one)
t = zero.__class__.__name__.__getitem__(neg_one)
next = bltndict.__getitem__(n + e + x + t)
_ = lambda __: next(_ for(_)in().__class__.__base__.__subclasses__()if _.__name__==__)

print(_('int'))
print(_('type'))
print(_('str'))
print(_('function'))
print(_('code'))

``` no literals at all
#

im using only __name__ and __builtins__ gobal vars

quartz wave
fleet bridge
#

now im going to assemble it into one line

fleet bridge
fleet bridge
#

can i use ternary operator and ...for...if... generator?

#

is it allowed?

quartz wave
#

no

fleet bridge
#

bruh

quartz wave
#

it's a pretty limiting challenge

#

a lot of things i can't unparse in the normal code to dunder code because of that

fleet bridge
#

!e ```py
_ = lambda : (builtins.dict if builtins.class.name.len().eq(name.class().len().invert().neg().add(name.class().len().invert().neg()).add(name.class().len().invert().neg()).mul(name.class().len().invert().neg().add(name.class().len().invert().neg()))) else builtins).getitem(name.class().len().class.name.getitem(name.class().len().invert().neg()).add(name.class.base.name.getitem(name.class().len().invert().add(name.class().len().invert()).add(name.class().len().invert()))).add(name.class().len().invert().neg().truediv(name.class().len().invert().neg().add(name.class().len().invert().neg())).rpow(name.class().len().invert()).class.name.getitem(name.class().len().invert())).add(name.class().len().class.name.getitem(name.class().len().invert())))( for _ in name.class.base.subclasses()if _.name.eq(_))

print(('int'))
print(
('type'))
print(('str'))
print(
('function'))
print(_('code'))

night quarryBOT
#

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

001 | <class 'int'>
002 | <class 'type'>
003 | <class 'str'>
004 | <class 'function'>
005 | <class 'code'>
quartz wave
#

what's a good way to get None

fleet bridge
#
  • lambda for convenience,
  • a if b else c for convenience, so it works in REPL and as script
  • __builtins__ and __name__ global vars used
  • ... for ... in ... if ... expression used
  • no literals (if i forgot remove some empty tuple literal, it can be easily replaced with __name__.__class__())
fleet bridge
quartz wave
#
True: "__name__.__eq__(__name__)",
False: "__name__.__ne__(__name__)",
None: "___name__.__getstate__()",
``` here's my list of constants now
fleet bridge
#

0 = True.__int__()

#

i mean 0 = False.__int__() and 1 = True.__int__() 😄

#

'': __name__.__class__()

#

object(): __name__.__class__.__base__()

quartz wave
#

and well it works

fleet bridge
#
str = __name__.__class__
object = str.__base__
type = object.__class__
list = object.__subclasses__().__class__
tuple = object.__bases__.__class__
obj = object()
true = __name__.__eq__(__name__)
false = __name__.__ne__(__name__)
bool = true.__class__
none = obj.__init__()
one = true.__int__()
zero = false.__int__()
negone = one.__neg__()
int = one.__class__
float = one.__truediv__(one).__class__
complex = one.__truediv__(one.__add__(one)).__rpow__(negone).__class__
under = int.__init__.__name__.__getitem__(zero)

pprint(globals())
#

only using __name__ global var

#

no literals, no operators except call and attr access

versed eagle
versed eagle
#

except with only dunders

versed eagle
versed eagle
night quarryBOT
#

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

<class 'function'>
versed eagle
#

what i do is that but with dunders

arctic skiff
fleet bridge
#

why phones shouldn't be allowed in school?

stone junco
#

policy

fleet bridge
#

police

arctic skiff
#

Except watch

#

Which is still not allowed in primary

fleet bridge
#

weird
what country are you in?

arctic skiff
#

India

#

And its not weird

serene stratus
arctic skiff
versed eagle
versed eagle
versed eagle
versed eagle
#

am Canadian, not American :p

arctic skiff
versed eagle
arctic skiff
#

commonly

#

see context

versed eagle
#

actually, no
sorry
I was wrong

#

it only means someone from the US

#

not commonly, only

#

my bad

#

I'm not American

#

please don't call me American

#

<3

arctic skiff
#

not only

arctic skiff
versed eagle
#

not to most people, but I don't like being called American for personal reasons
and its not that Americans are "bad people", or that I'm somehow better than them, or anything like that
its that i, for personal reasons, deeply dislike being called American

arctic skiff
#

anyways lets continue in ot

versed eagle
#

why would I want to continue this conversation

arctic skiff
#

!e```py
print('go to ot else i am gonna bonk you both')

night quarryBOT
#

@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.

go to ot else i am gonna bonk you both
versed eagle
#

i have respectfully asked you to not call me American, and that's that
there's not really anything else to discuss

versed eagle
#

I am going to leave now
have a nice day and/or {insert timezone here}

arctic skiff
#

have a nice day

versed eagle
sick hound
#

i am from future honey

solar tulip
#

Hi guys.

#

I don't get why someone would use a class...

royal whale
#

Classes can have methods for example!

solar tulip
#

Hmm...

#

Yea that is one good reason.

royal whale
#

You might want to do something like this:

class Score:
    def __init__(self, user_ID:str, _type:str, contact_ID:str, date:int, comment:str):
        self.user = user_ID
        self.type = _type
        self.contact = contact_ID
        self.date = date
        self.comment = comment
    def __setattr__(self, name, value):
        self.__dict__[name] = value
    def to_dict(self):
      return {"user": self.user, "type": self.type, "contact": self.contact, "date": self.date, "comment": self.comment}
#

for example

#

but yes

#

Depends on what you're using it for, but I would probably use a class if I wanted to expand functionality later

solar tulip
#

Hmm...

royal whale
#

even if not, it's not a bad idea to use a class

solar tulip
#

Is this not worse for performance?

royal whale
#

But for what you have, you might want a dataclass?

royal whale
#
from dataclasses import dataclass

@dataclass
class Score:
    user: str
    type: str
    contact: str
    date: int
    comment: str
solar tulip
#

I don't know the difference yet about dataclasses.
I just started with using JSON, then I learned to create a class and now I wonder if I have any practical use for it now.

royal whale
#

Hmm

#

Dataclasses are pretty much ready-made classes

#

I'd recommend researching them

solar tulip
#

Trying it like this, but that is just stupid.

#

@royal whale

royal whale
#

Yes.
Not like what you tried though.

solar tulip
#

Hmm..

#

Can you tell me how?

royal whale
#
class Contact:
    def __init__(self, contact:str, date:str, result: int, comment:str):
        self.contact = contact_ID
        self.date = date
        self.result = result
        self.comment = comment

class Score:
    def __init__(self, user_ID:str, _type:str, title:str, contact: Contact):
        self.user = user_ID
        self.type = _type
        self.title = title
    def __setattr__(self, name, value):
        self.__dict__[name] = value

print(Score("id", "type", "title", Contact("a", "b", "c", "d")).__dict__)
solar tulip
#

Ah yes, that makes sense.

royal whale
#

I'm not sure what you mean.

earnest wing
#

contact: Contact | None = None

#

then if you pass None, there is no contaxt

#

but this is hardly esoteric

#

so on topic for this channel

#

you should use

#

{}.__dir__.__class__.__dir__.__class__

solar tulip
#

@earnest wing thanks.

quartz wave
# versed eagle

there's probably a difference between 3.11.0rc1 and 3.11.0

versed eagle
#

probably
but I don't know why it would work in 3.8, 3.9, and 3.11.0rc1 but not 3.11

#

what was the error you said you got?

versed eagle
#

found it (finally stopped being lazy and scrolled like 20 messages upwards lmao)

  File "<stdin>", line 1, in <module>
TypeError: unbound method object.__sizeof__() needs an argument```
i dont think i ever used `object.__sizeof__()`
i know I used `(0).__sizeof__()`
and i used `*.__sizeof__().__class__()` to get 0 a lot
ill read through my code and see if I can find whats going on
solar tulip
#

Hi guys, am I beeing stupid or is this not what I wanted?

def initialize(user, title, status, balance, contact, result, comment, date): return {'user': user, 'title': title, 'status': status, 'balance': balance, 'contacts': {'contact': contact, 'result': result, 'instance': {'comment': comment, 'date': date}}}
with open('test.json','w') as file: json.dump(initialize('user', 'title', 'status', 'balance', 'contact', 'result', 'comment', 'date'), file, indent = 4)```
#

I feel like I am doing something wrong.

#
{
    "user": "user",
    "title": "title",
    "status": "status",
    "balance": "balance",
    "contacts": {
        "contact": "contact",
        "result": "result",
        "instance": {
            "comment": "comment",
            "date": "date"
        }
    }
}```
#

But output looks correct.

earnest wing
solar tulip
#

I know I know.

#

But someone told me here to do it differently.

#

And this is esoteric.

earnest wing
#

not really

earnest wing
solar tulip
#

Oneline solutions are the ones I give as well.

dire galleon
#

What is truly esoteric is figuring out what it is that you want to achieve

#

!rule 7

night quarryBOT
#

7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.

solar tulip
#

!rule 7

night quarryBOT
#

7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.

solar tulip
#
def initialize(user, title, status, balance, contact, result, comment, date): return {'user': user, 'title': title, 'status': status, 'balance': balance, 'contacts': {'contact': contact, 'result': result, 'instance': {'comment': comment, 'date': date}}}
with open('test.json','w') as file: json.dump(initialize('user', 'title', 'status', 'balance', 'contact', 'result', 'comment', 'date'), file, indent = 4)```
#
{"user": "user", "title": "title", "status": "status", "balance": "balance", "contacts": {"contact": "contact", "result": "result", "instance": {"comment": "comment", "date": "date"}}}```
#

What do you want from me?

#

Some nuts asking me why I asked a question here.

#

It was if I am doing something wrong with my code.

#

People gave me weird solutions and now I wrote those two lines.

solar tulip
#

People suggested that I use classes or dataclases.

#

Now I only used ONE LINE.

#

And I am weirded out that it works while people told me that I have to use classes and dataclasses.

#

So I am asking if I am doing something wrong.

#

Wtf.

#

Dude I got 12 line solutions from others for the same output.

#

Anyway, thanks.

dire galleon
royal whale
#

it's a best practice imo

solar tulip
#

@royal whale thanks a lot 👍💖

serene stratus
royal whale
versed eagle
#

certainly, you don't have to use classes or dataclasses

#

but they can help a lot in some cases

versed eagle
dense nova
#

!e

def func(a, b):
  print(func.__code__.co_varnames)

func(1, 2)
night quarryBOT
#

@dense nova :white_check_mark: Your 3.11 eval job has completed with return code 0.

('a', 'b')
dense nova
#

ight

#

!e

def func(a, b):
  print(dir(func.__code__))

func(1, 2)
night quarryBOT
#

@dense nova :white_check_mark: Your 3.11 eval job has completed with return code 0.

['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_co_code_adaptive', '_varname_from_oparg', 'co_argcount', 'co_cellvars', 'co_code', 'co_consts', 'co_exceptiontable', 'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars', 'co_kwonlyargcount', 'co_lines', 'co_linetable', 'co_lnotab', 'co_name', 'co_names', 'co_nlocals', 'co_positions', 'co_posonlyargcount', 'co_qualname', 'co_stacksize', 'co_varnames', 'replace']
quartz wave
dense nova
#
[globals().__setitem__(i, j) for i, j in {'DB': type('DB',(),{'s': __import__('string'),'__init__': lambda self, database: (setattr(self, 'database', database), None)[-1]}),'SeatRange': type('SeatRange',(),{'__init__': lambda self, start, end: (setattr(self, 'start', start),setattr(self, 'end', end),setattr(self, 'seats', [(DB.s.ascii_uppercase[i], j) for i in range(DB.s.ascii_uppercase.index(start[0]),DB.s.ascii_uppercase.index(end[0])) for j in range(start[1], end[1])]),None)[-1]}),'Airplane': type('Airplane',(),{'__init__': lambda self, name, plane_cost, esc, bsc, ec, bc, location=None, w=3, db=None: (setattr(self, 'name', name),setattr(self, 'plane_cost', plane_cost),setattr(self, 'esc', esc),setattr(self, 'bsc', bsc),setattr(self, 'ec', ec),setattr(self, 'bc', bc),setattr(self, 'mr', (esc * ec) + (bsc * bc)),setattr(self, 'seat_count', ec+bc),setattr(self, 'seats', SeatRange(('A', 1), ((db or DB).s.ascii_uppercase[self.seat_count//w], w+1))),setattr(self, 'location', location),setattr(self, 'width', w),setattr(self, 'owners', dict(__import__('itertools').zip_longest(self.seats.seats, ()))),(quit() if not self.check() else None),None)[-1],'compress': lambda self: f'{self.name!r}..{self.plane_cost}..{self.economy_seat_cost}..{self.business_seat_cost}..{self.economy_capacity}..{self.business_capacity}..{(self.location or "None")!r}','decompress': lambda compressed: Airplane(*map(lambda item: item[1:-1] if item.startswith("'") and item.endswith("'") else ((float(item) if '.' in item else int(item)) if item != 'None' else None), compressed.split('..'))),'check': lambda self: (self.seat_count % self.width == 0),'fly': lambda self, l: (setattr(self, 'location', l), self)[-1],'book': lambda self, l: (self.owners.__setitem__(l, "Owned") if self.owners[l] is None else print(f'Failed to book seat {l[0]}{l[1]}')),'book_all': lambda self, *ls: [self.book(l) for l in ls]})}.items()]
#

my WIP airport sim

#

as you can see i havent put much effort into obfuscation

#

its unreadable but you can understand it

#

if you add a few line breaks

pastel sparrow
#

you can probably golf it down a lot by just not using classes

dense nova
pastel sparrow
#

ah, what are you going for

dense nova
dense nova
pastel sparrow
#

ah nice

sick hound
#

Tried asking #python-discussion and there 0 help, kinda brain dead to the whole thought of obfuscation.

So I guess ile ask here how could i get a var // find a var by its name than replace its contents.

versed eagle
#

if it's a global, you can use globals().__setitem__

sick hound
versed eagle
#

ah
so more of a preprocessing thing than a runtime thing?

sick hound
#

Kinda like i have a string called
FileHash = ''
and i wanna drag in drop a file into the main file and it takes FileHash = and rewrites it to what i would like it to\

versed eagle
#
f = open(file).read()
new = ""
while "FileHash =" in f:
    i = f[:f.index("ileHash =")]
    new += f[:i]+"ileHash ="
    s = f.split()
    new +=  your_replaced_value_as_str
    new += s[2:]
    f = f[i:]
dense nova
#

I tried experimenting with something like that once, couldn't get anything.to work

versed eagle
#

that will fail if there's whitespace, or no space between the varname and the =

versed eagle
#

because I'm too lazy to add actual parsing

sick hound
#

could you use tokenizer?

versed eagle
#

you probably could

#

I'm too lazy to implement anything other than the basic thing there

sick hound
#

Crappy method but

#

easy

versed eagle
#

or the last

sick hound
#

thanks!
ile attempt to make some type of function with this or use tokenizer

versed eagle
#

if I wasn't on my phone I'd make something better

#

if you ping me in like 10 hours

#

I can make something better

sick hound
#

alr, ima attempt to use tokenzier

earnest wing
#

ast.parse, use a NodeTransformer that replaces Name("FileHash", ctx=Store()) with Name("whatever you want", ctx=Store()), then ast.unparse

#

this is the most stable

sick hound
versed eagle
#

he wants to change the value of the var
not the name

earnest wing
#

since it won't replace foo(FileHash=123)

#

aha

#

sure

#

you do the same but one level up,

#

using Assign

versed eagle
#

interesting

sick hound
#

0-0

versed eagle
#

I've never had the time to play around with ast/cst before

earnest wing
#

this is honestly an overkill solution

#

so no practical solutions here BABAXD

sick hound
#

I have 0 clue how to use ast.

versed eagle
#

I often greatly overestimate what I'm capable of lmao

sick hound
#
    new += f[:i]+"FileHash ="
#

TypeError: can only concatenate str (not "list") to str

versed eagle
#

I was tired af when I wrote that, sorry

#

I don't have time to write something better rn, but in a few hours I can write a parser

tough sparrow
#
(lambda text = "Hello World!" : [print(text) for i in range(4)] * int(print(f"{text[2:7]}\n{text[::2]}\n{text[::-1]}") != 1) * int([print(t * 2, end = '') for t in text] == 69) + [print()])()
``` got any of this shet?
vital dirge
pure dew
#

i've got a wip thing that adds full ast macros

royal whale
#

NO
HERESY

#

!e

from __future__ import braces
night quarryBOT
#

@royal whale :x: Your 3.11 eval job has completed with return code 1.

001 |   File "<string>", line 1
002 | SyntaxError: not a chance
royal whale
#

See?

#

The Python deities have spoken

#

What would happen to colons? Indentation? Would those be necessary?
Will it become a new JavaScript?

#

It must not be done

#

yeah I think so

royal whale
#

Then there's no point

royal whale
# full talon yes

Try keeping the colons and indentation as well as the braces
That might be more original

full talon
#
// Use braces in Python!

def fib(n) {
  a, b = 0, 1
  while (a < n) {
    print(a, end=' ')
    a, b = b, a+b
  }
  print()
}

/*
  Powerful anonymous functions
*/

print([def(x) {
  if(x in [0, 1]) {
    return x
  };
  while (x < 100) {
    x = x ** 2
  };
  return x
}(x) for x in range(0, 10)])

@royal whale see this

#

its from brackets

royal whale
#

that is not python

full talon
#

thing is: the docs and it are dead

royal whale
#

that is a glorified javascript

royal whale
full talon
royal whale
#

YES

full talon
#

I should make ptp (PythonTypedPreprocessor)

royal whale
#

You may as well make a language from scratch if you want to do that

full talon
#

it takes ur code

def dosmth(task: str):
  print("Doing " + task)

dosmth(['workouts', 'homework'])
```it would go```
InvalidTypeError: Type "list[str*2]" is not assignable to type "str", did you forgot to use a property?
#

oh yeah also interfaces

#

they get turned into classes

#

@royal whale would you use that

royal whale
#

possibly

#

there's mypy though

#

convince me that your version is better

full talon
#

AND, this is a big one: AUTOMATIC TYPE CONVERSIONS

#

like```py
def print_any_as_string(...args: list[auto str]):
for arg in args:
print(arg)

print_any_as_string(10, ['shit', 'moreshit'])

#

@royal whale what u think

royal whale
#

🤨

#

that's not the Pythonic way

full talon
royal whale
#

true

#

but

#

you have yet to convince me of its worth

#

Also this is more a conversation for #type-hinting or an off-topic channel

full talon
# royal whale you have yet to convince me of its worth
import somelib as anotherlib # Warns, somelib can't overwrite the name of anotherlib

class my_class: # Causes a warn: my_class doesn't follow UpperCamelCase
    ...some code

SOMEVAR: str = 'abc'
SOMEVAR = 'def' # Error: constant is being overwritten

nonconst: str = 'abc' 
nonconst = 123 # Error: Type overwritten

correct: any = 'abc' # In strict mode, this warns
correct = 123 # Works! any means it can be anything (doesn't work in strict mode tho)

def smth():
    print("Hello World!") # Warn: functions containing only one statement should be turned into lambdas
royal whale
#

Hmm

#

It looks nice

full talon
royal whale
#

It'd be very hard to implement but go ahead if you want
It's a cool idea

full talon
#

Oh yeah also generics```py
def smth<T>(anarg: T):
print("T is of type" + type(T))

#

@royal whale

royal whale
#

Okay that is not something Python should have

#

that's too far for me

#

😂

#

but a neat idea

full talon
royal whale
night quarryBOT
#
**PEP 695 - Type Parameter Syntax**
Status

Draft

Python-Version

3.12

Created

15-Jun-2022

Type

Standards Track

full talon
#

bunch of builtin ones

royal whale
full talon
royal whale
#

Good

astral rover
royal whale
#

The rest is pretty neat

astral rover
#

this is just object

royal whale
astral rover
#

no as in everything supports str()

#

so this trait is pointless

full talon
#

also ```py
class smth(hashable):
def hash(self: Self):
return hash(self.num)

def __str__():
    return "This is class smth"
#

also some cool new features

#

like aliases

royal whale
#

At this point

#

It's just Rust

#

but higher-level

#

and with Python's syntax

full talon
#
# OBJ defines any, except you can't access props or check its type
def getType(TYPE: obj):
    return name(TYPE) + " is of type " +type(obj)

e = getType

print(e('abc')) # When compiled this would be turned into print(getType('abc')) (with optimization on it would become print("e is of type str"))
full talon
#

@royal whale what do u think of the optimization?

#

also built-in obfuscation

royal whale
#

Eh
I suppose it'd help a little

full talon
royal whale
#

It's a neat idea, but it won't matter unless someone makes it

versed eagle
#

so basically, a compiler for python

#

?

full talon
#

it outputs optimized obfuscated (if specified) python

royal whale
versed eagle
#

huh

full talon
#

its pythonlike?

#

Its basically python but with more shit

versed eagle
#

I don't actually use ts or js so idk

full talon
#

the features I am showing are all in typescript

#

with traits instead being interfaces

versed eagle
#

then use typescript

full talon
#

which I will call them

versed eagle
#

lmao

full talon
#

thing is: I WANT PYTHON

#

What should I call it

versed eagle
#

python isn't supposed to be typechecked

full talon
versed eagle
full talon
#

you can tell it with -w (--warnings) to just check

versed eagle
#

if you want other stuff

full talon
#

and optimize

#

nothing else

versed eagle
#

do other stuff

versed eagle
full talon
#

@inline go brr

versed eagle
#

for example, could it remove this?

for x in range(124):
    pass
versed eagle
#

what about this?

for x in range(124):
    object()
versed eagle
#

object init has no side effects

#

so that should get optimized

#

how are you going to detect if an initialization has side effects

versed eagle
versed eagle
full talon
#

it will go
🤔 - What is the definition of object?
🤔 - Oh I found it!
🤔 - What variables does it access?
🤔 - I see it just access e, where is e defined?
🤔 - Huh, e is defined inside object
🤔 - Are there any outside variables or functions called? If functions are called, go to step 1 for that function
🤔 - Aha, this function is useless without assignment
🤔 - Lets delete the usage of it
🤔 - Huh, this for loop now just passes, lets delete it
🤔 - What does range do?
🤔 - Hey range, oh step 1-6 on this
🤔 - Huh, range only returns highest in this context
🤔 - Lets see, is x used?
🤔 - Yeah its used later, lets replace it with an x=124

versed eagle
#

so you can't optimize that while having the same result

full talon
#

It basically sorta evaluates it to see what it references

versed eagle
#

it reads source code

#

to do that?

full talon
versed eagle
#

what about compiled modules

#

written in c/c++

full talon
versed eagle
#

how would it know where the names come from without being able to read the source

full talon
#

also compiled modules still have a .pyc so it can use that

versed eagle
#

for example:

from module import *
from module2 import *
# module has func1 in it
func1()

how does it know where func1 comes from

#

to find the definition

#

if they're both compiled .so

versed eagle
full talon
versed eagle
#

what do you do between versions where there are bytecode changes

#

like 3.10 and 3.11

#

have incompatible bytecode

full talon
#

simple: it goes
🤔 - what is inside module2?
🤔 - Ah, its a .pyc, lets read its exports
🤔 - I don't see a func1 in there
🤔 - <step 1-3 for module> ||| I see a func1 in module, lets use that

#

@versed eagle it reads bytecode using python itself

versed eagle
full talon
versed eagle
#

which definition does it find

full talon
#

also it kinda... warns with * imports

versed eagle
full talon
versed eagle
#

what happens when ctypes gets involved and globals behaves differently

#

because the behavior has been overridden?

full talon
versed eagle
#

cereal

#

I wrote an assembly implementation

#

in python

full talon
#

Ill make a minilang

versed eagle
#

using it

full talon
#

using docker

#

It'll go like HMMMMMMMMMMMM what will it do?

versed eagle
#

!e

from ctypes import *
class glob(dict):
    def __getitem__(self, item):
        try:
            return {}.__class__.__getitem__(self, "__builtins__").__getattribute__(item)
        except:
            return 4
py_object.from_address(id(globals())+8).value = glob
print(not_defined)
night quarryBOT
#

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

4
versed eagle
#

can it detect that

full talon
#
specialdef globals()[prop]:
    accesses prop IN globals
#

its like webpacks js plugin, it tries to obfuscate what it can

#

yes it supports node, SHUT

#

at the point you are modifying the V8 engines variables, what CAN you expect?

versed eagle
#

and takes no args

versed eagle
full talon
#

honestly I am at a loss

versed eagle
versed eagle
full talon
versed eagle
#

I've thought about doing something similar for a long time

#

so I have had lots of time to realize all the problems

#

with such an idea

full talon
#

and to EXPECT weirdness

#
@C(
  {variables: {
    'e': {
        expectRedefine: True,
        allowObfuscation: False,
        allowOptimization: False
      }
  }}
)
versed eagle
#

can it optimize the constant math expression 1/0?

versed eagle
#

what would it optimize to?

full talon
versed eagle
#

!timeit
1/0

night quarryBOT
#

@versed eagle :x: Your 3.11 timeit job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/usr/local/lib/python3.11/timeit.py", line 326, in main
003 |     number, _ = t.autorange(callback)
004 |                 ^^^^^^^^^^^^^^^^^^^^^
005 |   File "/usr/local/lib/python3.11/timeit.py", line 224, in autorange
006 |     time_taken = self.timeit(number)
007 |                  ^^^^^^^^^^^^^^^^^^^
008 |   File "/usr/local/lib/python3.11/timeit.py", line 178, in timeit
009 |     timing = self.inner(it, self.timer)
010 |              ^^^^^^^^^^^^^^^^^^^^^^^^^^
011 |   File "<timeit-src>", line 44, in inner
... (truncated - too many lines)

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

versed eagle
#

!timeit
try:
1/0
except:
pass

night quarryBOT
#

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

500000 loops, best of 5: 594 nsec per loop
versed eagle
#

!timeit
try:
raise ZeroDivisionError()
except:
pass

night quarryBOT
#

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

500000 loops, best of 5: 567 nsec per loop
full talon
#

with```py
@C({
behavior: {
ignore: {
divisionByZero: True
}
}})

versed eagle
#

30 ns of optimization :D

full talon
#

@versed eagle try in 3.10

#

!timeit
try:
raise ZeroDivisionError()
except:
pass

night quarryBOT
#

@full talon :white_check_mark: Your 3.10 timeit job has completed with return code 0.

500000 loops, best of 5: 557 nsec per loop
full talon
#

!timeit
try:
1/0
except:
pass

night quarryBOT
#

@full talon :white_check_mark: Your 3.10 timeit job has completed with return code 0.

500000 loops, best of 5: 598 nsec per loop
full talon
#

its consistantly faster

versed eagle
#

even better in 3.10
ok

#

cool

#

can it handle manipulating code objects?

versed eagle
#

I kinda wanna write that

#

not the typechecker part, but the optimizer part

pure dew
pure dew
astral rover
#

should just be *args: Any

pure dew
#

no? I haven't used pyright proper for a while

#

oh i see

astral rover
#

theres too much rust in your brain :p

pure dew
#

ya

#

i am working a little Quart website tho

#

gonna be part SSG and part regular webserver

glad basin
#

bro ngl, yall r impressive asf

#

i could never

solar tulip
#

Never say never except in this case.

#

U r impressive too, u just don't know yet.

glad basin
#

nahhh bruh like, this stuff is mind boggling

#

i need atleast 10 more years to even begin to process the works forged here

#

but thanks

solar tulip
#

Why does it not work?

royal whale
#

!e

def var(name, value):
    globals()[name] = value

var("a", 3)
print(a)
night quarryBOT
#

@royal whale :white_check_mark: Your 3.11 eval job has completed with return code 0.

3
royal whale
#

Modified a little

#

but it works

solar tulip
#

Thanks!

fleet bridge
night quarryBOT
#

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

42
fleet bridge
#

!e this also works as importable function

import sys
def var(**kwargs):
    sys._getframe(1).f_globals.update(kwargs)

var(a=13, b=29)
night quarryBOT
#

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

[No output]
fleet bridge
#
import sys
def var(**kwargs):
    loc = sys._getframe(1).f_locals
    print(loc)
    loc.update(kwargs)
    print(loc)


def f():
    x = 1
    if 0:
        a, b = 0, 0
    print(locals())
    var(a=13, b=29)
    print(locals())
    print(a, b)

f()

this doesnt work
i cant modify local vars from another function

quartz wave
night quarryBOT
#

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

001 | {'x': 1}
002 | {'x': 1}
003 | {'x': 1, 'a': 13, 'b': 29}
004 | {'x': 1, 'a': 13, 'b': 29}
005 | 13 29
quartz wave
#

that does

fleet bridge
#

nice

quartz wave
#

but a and b need to be local variables

fleet bridge
#

!e

import sys
import ctypes
ltf = ctypes.pythonapi.PyFrame_LocalsToFast
ltf.argtypes = [ctypes.py_object, ctypes.c_int]
def var(**kwargs):
    f = sys._getframe(1)
    f.f_locals.update(kwargs)
    ltf(ctypes.py_object(f), 0)

def f():
    print(locals())
    var(a=13, b=29)
    print(locals())
    print(a, b)

f()
night quarryBOT
#

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

001 | {}
002 | {'a': 13, 'b': 29}
003 | Traceback (most recent call last):
004 |   File "<string>", line 16, in <module>
005 |   File "<string>", line 14, in f
006 | NameError: name 'a' is not defined
fleet bridge
#

thats because here a and b are globals

full talon
#

@royal whale do you know how I can make a variable have 2 names

#

so abc and dfe both reference a string Hello World!

astral rover
#

abc = def = "Hello World"

full talon
#

will def be Hello Me!

#

?

astral rover
#

how are you planning on making abc "Hello Me!"?

astral rover
#

just using an assignment no it wont

#

ok yeah

full talon
#

.-.

quartz wave
#

you have to do some crazy string manipulation

versed eagle
#

then use ctypes to retrieve the object when you want to use it?

pure dew
full talon
pure dew
vague cairn
simple sphinx
#

I made a thing I think you will like 🙂

if __name__ == '__main__':
    n = int(input("what fibonachi number would you like to compute? "))
    current_sum = 0
    __name__ = '__not_main__'
    print(exec(open(__file__,'r').read()))
    __name__ = '__main__'

else:
    if n in [0,1]:
        current_sum += n
    else:
        n -= 1
        exec(open(__file__,'r').read())
        n -= 1
        exec(open(__file__,'r').read())
        n += 2

if __name__ == '__main__':
    print(current_sum)
dusty glen
#

what does esoteric python even mean, i can't find an accurate answer on google

potent comet
pure dew
# full talon sure

git repo is above, but here's one example

from traitor import impl
from traitor.traits.into import From, Into


class Foo:
    def __init__(self, n):
        self.name = n[::-1]

    def __repr__(self):
        return f"<Foo({self.name})>"


@impl(From[Foo] >> str)
class StrFromFoo:
    def from_(value):
        return value.name[::-1]


@impl(From[str] >> Foo)
class FooFromStr:
    def from_(value):
        return Foo(value)


# >>>>>>>>

f = "asd".into()
print(f)

name = From[Foo](str).from_(f)
print(name)
#

From/Into syntax is still kinda wip

simple sphinx
# simple sphinx I made a thing I think you will like 🙂 ```py if __name__ == '__main__': n ...

I needed something that is importable and will work on codewars and leetcode, I also needed to optimize the code so I can calculate to around 1000. so here is an updated version

def fibonacci(x):
    import sys
    sys.setrecursionlimit(3000)
    __name__ = 'this is a call for help'
    global current_sum
    current_sum = 0
    global optimisation_dict
    if not "optimisation_dict" in globals():
        optimisation_dict = {0:0, 1:1,}
    n = x
    exec(open(__file__,'r').read())
    return current_sum
    

if __name__ == 'this is a call for help':
    global current_sum
    if n in optimisation_dict:
        current_sum += optimisation_dict[n]
    else:
        n -= 1
        exec(open(__file__,'r').read())
        optimisation_dict[n+1] = optimisation_dict[n-1] + optimisation_dict[n]
        n -= 1
        exec(open(__file__,'r').read())
        n += 2

quartz wave
full talon
#

anyways I am trying to make mixins

#

in python

#

Uncompiling functions

gleaming timber
full talon
#

It works in local functions but not others?

fleet bridge
#

Im going to write asm interpreter in python lemon_exploding_head

quartz wave
vague cairn
#

Fair enough

#

I presume finding that is a pattern of something like:

def poke_attr(obj, attr, value):
    address = id(obj)
    if getattr(obj, attr) == value: return None
    for offset in range(sizeof(obj) or 100, step=sizeof(int)):
        monkey = ctypes.make_int(address+offset)
        backup = monkey.value
        monkey.value = id(value)
        if getattr(obj, attr) == value: return offset
        monkey.value = backup

(except that I haven't used ctypes often enough to memorize things real names)

night quarryBOT
#

Include/internal/pycore_frame.h lines 16 to 27

struct _frame {
    PyObject_HEAD
    PyFrameObject *f_back;      /* previous frame, or NULL */
    struct _PyInterpreterFrame *f_frame; /* points to the frame data */
    PyObject *f_trace;          /* Trace function */
    int f_lineno;               /* Current line number. Only valid if non-zero */
    char f_trace_lines;         /* Emit per-line trace events? */
    char f_trace_opcodes;       /* Emit per-opcode trace events? */
    char f_fast_as_locals;      /* Have the fast locals of this frame been converted to a dict? */
    /* The frame data, if this frame object owns the frame */
    PyObject *_f_frame_data[1];
};```
quartz wave
#

f_code is located in f_frame

#

its offset is object.__basicsize__ + tuple.__itemsize__

#

so you want to get ctypes.POINTER(ctypes.c_void_p).from_address(id(frame) + object.__basicsize__ + tuple.__itemsize__).contents to get the internal structure

night quarryBOT
#

Include/internal/pycore_frame.h lines 49 to 55

typedef struct _PyInterpreterFrame {
    /* "Specials" section */
    PyObject *f_funcobj; /* Strong reference. Only valid if not on C stack */
    PyObject *f_globals; /* Borrowed reference. Only valid if not on C stack */
    PyObject *f_builtins; /* Borrowed reference. Only valid if not on C stack */
    PyObject *f_locals; /* Strong reference, may be NULL. Only valid if not on C stack */
    PyCodeObject *f_code; /* Strong reference */```
quartz wave
#

then f_code is 4 more pointers after that so an offset of tuple.__itemsize__ * 4

simple sphinx
vague spade
#

hello guys can you help me with this question
Is there any?
sums the sum of even numbers between
write the code.

gleaming timber
fleet bridge
pastel sparrow
#

!e ```py
(:=getattr,:=dir,:=(:=(:=()==())+)+,(:=((:=((((),(())[]),(())[(:=()==[])][:]+()[-][+]+(())[][:][:]+()[-][--:]),(())[-(+)][:--]+()[-][-]+()[][--:])())[_((:=_(()[___],()[]))()[:(________(),()[+][-]+()[][-:][:]+()[-][+:][:])(([])[-][-:]+()[-][--])],(())[-])(((()))[*(+)])],(())[][+]+()[-][]+()[][::]+()[--][::+]+({})[--][+::]+({})[-][::])(()[-][+]+(())[-][]+()[-][::]+()[-][:][:][::-]+()[--][+:][:]),()[((())[:((()),()[+][-]+()[][-:][:]+()[-][+:][:])(()[-][]+__(())[][:])],(())[-])(((()))[*(+)])])((())[][:]+([])[-*(+)][--]+()[-][::]+(())[][+]+()[-][]+(())[][:____]))


the sequel, works in versions 3.8-3.11
night quarryBOT
#

@pastel sparrow :warning: Your 3.11 eval job has completed with return code 0.

[No output]
pastel sparrow
#

damn __import__("__hello__") doesn't work on the bot?

#

sad

arctic skiff
#

!epy __import__("__hello__").main()

night quarryBOT
#

@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.

Hello world!
pastel sparrow
#

.main() doesn't work for 3.10 or below though

quartz wave
#

!e 3.10 ```py
import("hello").main()

night quarryBOT
#

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

Hello world!
unreal echo
unreal echo
quartz wave
#

!e 3.10 ```py
import("hello")

night quarryBOT
#

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

[No output]
quartz wave
#

@unreal echo hmm?

unreal echo
#

what

#

but

#

it worked in 3.9

quartz wave
unreal echo
#

bruh

#

why would it be changed

#

they had no reason

quartz wave
unreal echo
#

bruh

quartz wave
#

it was just a frozen marshalled python test module generated from /Tools/scripts/flag.py

fleet bridge
#

i have iterable of functions and iterable of values
i want to apply every function to corresponding value and return iterable of results
my approach

F: Iterable[Callable]
X: Iterable[something]

[f(x) for f,x in zip(F,X)]

how can i do it without comprehension in efficient way?

fleet bridge
#

first argument of map must be funnction, in my case F is iterable of functions
basically i want [f1(x1), f2(x2), f3(x3), ...]

pure dew
#

maybe map(lambda f, x: f(x), zip(F, X))

quartz wave
quartz wave
#

map() doesn't automatically unpack an iterable

pure dew
#

oh

#

good to know

quartz wave
# pure dew oh

although you can pass multiple arguments to map() like in my example above

pure dew
#

i was away for 7 months and coming back is hard

quartz wave
fleet bridge
quartz wave
versed eagle
#

i sent a link earlier

fleet bridge
quartz wave
night quarryBOT
#

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

001 | 2
002 | [None, -1, 1.1]
003 | Traceback (most recent call last):
004 |   File "<string>", line 4, in <module>
005 | TypeError: <lambda>() takes 1 positional argument but 2 were given
quartz wave
#

@fleet bridge what are you on about

#

i'm trying hard not to get mad rn

fleet bridge
#

hmmmmmmmmmm

#

ok im dumb

#

thanks

fleet bridge
sick hound
#

is my anti-tamper project dying

#

wat the heck

serene stratus
#

Why does it always use the same junk code

#

It's not generating it

#

You're changing the function/var names

next flame
#

@sick hound your program doesnt even run lmfao

#
Traceback (most recent call last):
  File "/tmp/ExtraLayerMain.py", line 144, in <module>
    '''.format(LSendReason=UseExitReason,LSendInfo=UseDebugInfo,LDiscordWebhook=ELSelect3_WebHook)+r'''
NameError: name 'ELSelect3_WebHook' is not defined
#

if you select no to webhook

#

anyways

#

whats preventing an end-user from just
deleting all of the checks

serene stratus
#

It doesn't, he mentions in the readme that it should be combined with some other obfuscator

quartz wave
#

YES ```py

def f():
... get_stack().push(5)
...
f.code = f.code.replace(co_code=f.code.co_code[:-4]+f.code.co_code[-2:])
f()
5
def f():
... get_stack().push(5)
... return (get_stack().pop(),)
...
f()
5
def f():
... p1, p2 = get_stack().push, get_stack().pop
... p1(5)
... return (p2(),)
...
f()
5

#

after hours of working on the stack thingy i finally added proper .push() and .pop()

fleet bridge
fleet bridge
#

Hmm

quartz wave
#

ok it isn't perfect and doesn't work in all cases

next flame
#

they're just advertising a different but related tool

#

i would also assume that an "anti-tamper tool" is actually capable of preventing tampering by itself

serene stratus
serene stratus
serene stratus
#

I just read at the bottom that it needs to be used along with another obfuscator

serene stratus
#

Haha could be

#

How'd you do it

quartz wave
#

still now i have no idea how to operate it but i managed to control the stacktop pointer

#

turns out i had done the offsets wrong

#

i'm still struggling with it

serene stratus
#

Mind sharing the code you have so far?

quartz wave
#

it's quite messy

serene stratus
#

Fine for me

quartz wave
#

k wait

quartz wave
sick hound
#

WIll fix it here soon

#

Its much more of anti-debug than obfuscation

sick hound
floral meteor
#

whats preventing an end-user from just deobfuscating all of the checks?

sick hound
#

'obfuscation

#

Read the GitHub

#

Ik its hard to do

#

But it might just need to be done.

#

Also I have fixed it.

sick hound
#

ExtraLayer just helps prevent deobfuscation.

#

Also this was just a fun project, no reason to pound me into the ground for it.

serene stratus
#

They were just asking a question?

earnest ruin
#

opt = gradient_descent_v2.SGD(learning_rate=lr, decay=lr/epochs)
NameError: name 'lr' is not defined

I got this while performing a chatbot python code,
How to clear this error?

serene stratus
#

Anyway it's just an undefined variable?

#

You can choose yourself what it can be

sick hound
bright pier
#

do you guys know any teacher who has video tutorial for python

sick hound
#

Someone attempt to decode this PeepoWine

#
enc_str = [ 0x19f, 0x1bf, 0x1cb, 0x1d1, 0x1e0, 0xfc, 0x191 ]

for XKzQUH in range(7):
        VbgFfH = enc_str[XKzQUH];
        VbgFfH = ~VbgFfH;
        VbgFfH += 0x81;
        VbgFfH ^= 0x86;
        VbgFfH = ~VbgFfH;
        VbgFfH -= 0xec;
        VbgFfH ^= 0x94;
        VbgFfH = ~VbgFfH;
        VbgFfH ^= XKzQUH;
        VbgFfH += 0x11;
        VbgFfH = ~VbgFfH;
        enc_str[XKzQUH] = VbgFfH;

enc_str = ''.join([chr(i) for i in enc_str])
del XKzQUH, VbgFfH
print(enc_str)```
sick hound
#

You know how i know u just copied the output

quartz wave
sick hound
#

Because the orgin output does not include ''

#

Nah but fr someone needs to try

quartz wave
#
enc_str = [ 39, 72, 101, 108, 108, 111, 39 ]
enc_str = ''.join([chr(i) for i in enc_str])
print(enc_str)
``` that?
sick hound
#

I needa know how good it is.

quartz wave
#

wait