#esoteric-python

1 messages · Page 28 of 1

restive void
#

How so? You find it unintuitive that Python doesn't have block scoping?

versed eagle
#

i find it unintuitive that it has scoping for some things but not others

#

to me, the bindings for the case statement read a bit like function args

#

in general, they should go out of scope whenever that section is done

#

in my mind, that is

#

so is unintuitive to me that they don't

restive void
#

Why only match-case, and not with, for, if, ...?

versed eagle
#

it's not only match-case, but that was the subject at hand so i was talking about it specifically

fleet bridge
#

It is not new.
del x exists for a long time
Also exc in except Exception as exc: is "unbounded" (assigned to None) after except block finishes execution

vast wave
night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 6, in <module>
003 |     print(e)
004 |           ^
005 | NameError: name 'e' is not defined
fleet bridge
#

!e ```py
def f():
try:
raise Exception()
except Exception as e:
pass
print(e)
f()

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 7, in <module>
003 |     f()
004 |   File "/home/main.py", line 6, in f
005 |     print(e)
006 |           ^
007 | UnboundLocalError: cannot access local variable 'e' where it is not associated with a value
fleet bridge
#

So there is essentially del exc at the end of the block, not exc = None

vast wave
#

what in tarnation

#

!e ```py
def f():
a = "abc"
print(a)
del a

print(a)

f()
b = "bcd"
print(b)
del b
print(b)

#

oh right

night quarryBOT
#

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

001 | abc
002 | bcd
003 | Traceback (most recent call last):
004 |   File "/home/main.py", line 10, in <module>
005 |     print(b)
006 |           ^
007 | NameError: name 'b' is not defined
vast wave
#

what the fuck

#

del in a function != del in a module

#

i love python

fleet bridge
#

Global namespace and local namespace are behaving very differently

restive void
quartz wave
#

essentially ```py
exc = None
del exc

keen thicket
#

!e

f = lambda n, w, b: ''.join(reversed([chr(b+((n>>i)&(2**w-1))) for i in range(0, n.bit_length(), w)]))
print(f(198522, 4, 101), f(20297984, 5, 100))
night quarryBOT
#

@keen thicket :white_check_mark: Your 3.11 eval job has completed with return code 0.

hello world
pure dew
#

oh did we see that lecture video here too?

keen thicket
#

!e

string = "Hello World!"
words = string.split(" ")
enc_words = []
for word in [i.strip() for i in words]:
    letters = [ord(i) for i in word]
    b=min(letters)
    delta = [w-b for w in letters]
    w = max(delta).bit_length()
    if len(letters) == 1:
        enc_words.append(((1<<b.bit_length()), b.bit_length(), b))
        continue
    n=int("1"+''.join(([f'{i:0{w}b}'for i in delta])), 2)
    enc_words.append((n, w, b))

from sys import getsizeof
f=lambda n,w,b:''.join((chr(b+(n>>i&2**w-1))for i in reversed(range(0,n.bit_length()-1,w))))
print(' '.join([f(*i) for i in enc_words]))
print(sum([sum([getsizeof(z) for z in i]) for i in enc_words]))
print(sum([getsizeof(i)for i in string]))
night quarryBOT
#

@keen thicket :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | Hello World!
002 | 176
003 | 600
keen thicket
#

compression using deltas for each word to convert the string into an initial value, an integer describing the deltas, and the width in bits of each delta 🙂

versed eagle
#

fun

keen thicket
#

I wonder if it's possible to make a more efficient packer for python source code by using all the kws and soft kws

leaden valley
#

can undefined be any variable name?

frail token
#

Yes, there is nothing special about the variable name 'undefined', it is not a Python keyword or singleton (like None, True or False).

arctic plume
#

!e

print("".join([chr(round(-4412.70555564*x+12008.5182542*x**2-13041.0511356*x**3+7566.06024046*x**4-2619.91695608*x**5+567.42766205*x**6-77.5228009278*x**7+6.48776455043*x**8-0.303552138456*x**9+0.00607914462098*x**10+104)) for x in range(11)]))```
night quarryBOT
#

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

hello world
keen thicket
#

is that like a fitted curve to the ascii values or something

digital mesa
digital mesa
#

extra chars for no reason

keen thicket
digital mesa
#

😭

digital mesa
#

adjusted to be without [], and no space between ) and for

arctic plume
#

You can try putting it into desmos if you want

digital mesa
#

otherwise the fitted curve would be a straight line, no?

arctic plume
#

You can think of it as a function f(x) that you run for every value of x between 0 and 10

#

Actually, what am I even saying, this is esoteric python, you figure it out!

digital mesa
#

I mean it's not too complicated

#

just looks complicated

arctic plume
#

A lot of numbers indeed

digital mesa
#

now write a one-liner that will generate a function for a given string 😂

arctic plume
#

Lmao

digital mesa
#

L bozo

#

get error-slapped

arctic plume
night quarryBOT
#

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

001 |   File "/home/main.py", line 7
002 |     [chr(ord(b) + 1) for b in a]) for a in x][0])(g, 12)))
003 |                                                         ^
004 | SyntaxError: closing parenthesis ')' does not match opening parenthesis '[' on line 2
tough willow
arctic plume
tough willow
arctic plume
#

You could probably remove some decimals and have it still work actually

#

If only it was more readable

Oh wait...

arctic plume
#

5 minutes perhaps?

keen thicket
# digital mesa competing with 239 chars

!e

print("".join(map(lambda x:chr(round((-4412.70*x+12008.518*x**2-13041.0511*x**3+7566.0602*x**4-2619.91695*x**5+567.427662*x**6-77.52280092*x**7+6.48776455*x**8-0.3035521384*x**9+0.00607914462*x**10+104))),range(11))))
night quarryBOT
#

@keen thicket :white_check_mark: Your 3.11 eval job has completed with return code 0.

hello world
keen thicket
#

I had to resort to chopping off a lot of the decimals that weren't needed lol

#

but it's 217

#

gottem 🙂

arctic plume
#

It's that bad?

keen thicket
#

I tried a lot of stuff

digital mesa
#

Lol

keen thicket
#

but it really is just wasted chars

#

but it was a fun exercise

arctic plume
#

It's possible that there's an equation, say using a^x that would be shorter

keen thicket
#

there is actually: ```python
print("hello world")

arctic plume
#

What if I forget what how to spell it?

#

But remember the polynomial equation for it

keen thicket
#

HAHAHAHAHA

#

needs more lambdas for sure

#

Wait that would be funny, imagine if you made a program that messed with the code object so that when you viewed the backtrace it would be different

fleet bridge
#

Ohh, lambda calculus in python...

#

Literally

keen thicket
#

Then you could make an infinite lambda scroller

#

at the top and bottom

arctic plume
#

You can just spell hello world with the lambda argument names at that point...

#

Already have the majority of the alphabet lmao

fleet bridge
#

It is the entire alphabet

arctic plume
#

Forgot åäö

keen thicket
arctic plume
#

Uh oh...

tough willow
arctic plume
tough willow
#

ß and ẞ

arctic plume
#

ẞ haha looks so silly

tough willow
#

that's the capitalized ß

night quarryBOT
#

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

001 |   File "/home/main.py", line 1
002 |     (lambda a: (lambda b: (lambda c: (lambda d: (lambda e: (lambda f: (lambda g: (lambda h: (lambda i: (lambda j: (lambda k: (lambda l: (lambda m: (lambda n: (lambda o: (lambda p: (lambda q: (lambda r: (lambda s: (lambda t: (lambda u: (lambda v: (lambda w: (lambda x: (lambda y: (lambda z: (lambda a1: (lambda b1: (lambda c1: (lambda d1: (lambda e1: (lambda f1: (lambda g1: (lambda h1: (lambda i1: (lambda j1: (lambda k1: (lambda l1: (lambda m1: (lambda n1: (lambda o1: (lambda p1: (lambda q1: (lambda r1: (lambda s1: (lambda t1: (lambda u1: (lambda v1: (lambda w1: (lambda x1: (lambda y1: (lambda z1: __import__('sys').stdout.buffer.write(bytes(map(lambda x: round((a(x)+b(x)*x+c(x)**2+d(x)**3+e(x)**4+f(x)**5+g(x)**6+h(x)**7+i(x)**8+j(x)**9+k(x)**10+l(x)**11+m(x)**12+n(x)**13+o(x)**14+p(x)**15+q(x)**16+r(x)**17+s(x)**18+t(x)**19+u(x)**20+v(x)**21+w(x)**22+z(x)**23), range(24)))))))))))))))))))))))))))))))))))))))))))))))))))))))))(lambda a: 0))(lambda
... (truncated - too long)

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

last locust
#

!e ```py
from fishhook import hook

@hook(int)
def bool(self):
print("hi", self)
return True

print(bool(0))```Why is there two prints for the __bool__ here? Where does the first one come from?

night quarryBOT
#

@last locust :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | hi 2147483648
002 | hi 0
003 | True
night quarryBOT
#

Lib/test/test_int_literal.py line 33

self.assertEqual(0x80000000, 2147483648)```
kindred stone
#

oh nvm tests arent run

#

🤦‍♂️

last locust
#

Heh, nice idea though lol

#

It's exactly 2**31, so I'm guessing the number has some significance

kindred stone
#

nothing is happening with the literal number

last locust
#

And the 2147483648 seems so random, albeit 2**31

kindred stone
#

maybe it is called on a checking if the system is 32 or 64 bits

#

(this is a blind guess)

last locust
kindred stone
#

the MSB is used to say if the number is negative or positive, so you cant have 2 ** 32 of value

#

the rest is used to represent the value of the number (2 ** 31 - 1)

last locust
#

Right

last locust
digital mesa
night quarryBOT
#

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

001 | hi 2147483648
002 | hi 0
003 | True
004 | hi 1
005 | True
digital mesa
#

only once

#

then later calls are not printing the extra

#

!e

from fishhook import hook

@hook(int)
def __bool__(self):
    print("hi", self)
    return True
night quarryBOT
#

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

hi 2147483648
digital mesa
#

woah funky

#

although that is what I was suspecting after the previous test

last locust
#

It's getting triggered without actually doing anything

digital mesa
#

🤷‍♂️

fleet bridge
#
  1. it is happening in fishhook.hook after method is hooked
  2. (unlikely) it is happening when new name is assigned to global namespace
rugged sparrow
night quarryBOT
#

fishhook/fishhook.py lines 55 to 59

def assert_cls(o):
    if type(o).__flags__ & (1 << 31):
        return o
    else:
        raise RuntimeError('Invalid class or object')```
rugged sparrow
# last locust Hmm, I see, thanks

Yea due to how fishhook hooks internals it's difficult to make it fully opaque (until I implement scoped hooks but that is a while away)

keen thicket
# arctic plume Uh oh...

!e

h = [
    lambda a, b, c, d: 0,
    lambda a: 0,
    lambda a, b, c, d, e, f, g, h: 0,
    lambda a, b, c, d, e, f, g, h: 0,
    lambda a, b, c, d, e, f, g, h, i, j, k: 0
]

w = [None,
    lambda a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, z,_: 0,
    lambda a, b, c, d, e, f, g, h, i, j, k,_: 0,
    lambda a, b, c, d, e, f, g, h, i, j, k, l, m, z,_: 0,
    lambda a, b, c, d, e, f, g, h,_: 0,
    lambda a: 0
]

b = 100
for i in h+w:
    if i is None:
        print(" ",end="")
        b-=1
        continue
    try:
        i()
    except Exception as exc:
        print(chr(int(str(exc).split(" ")[2])+b),end="")
night quarryBOT
#

@keen thicket :white_check_mark: Your 3.11 eval job has completed with return code 0.

hello world
arctic plume
keen thicket
quartz wave
#

!e ```py
a = 2; print(a + 3)

night quarryBOT
#

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

001 |   File "/home/main.py", line 1
002 |     a = 2; print(a + 3)
003 |         ^
004 | SyntaxError: invalid decimal literal
quartz wave
#

figure out why

astral rover
#

Cause it's not a real colon?

#

!e ```py
a = 2; print(a + 3)

night quarryBOT
#

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

5
quartz wave
astral rover
#

Is that not the reason?

quartz wave
#

"ok" would mean "all correct" here like it always did

versed eagle
quartz wave
night quarryBOT
quartz wave
#

yes

keen thicket
#

fuck u but I'm gonna do it just give me like a few more hours smfh

#

i knew someone was gonna tell me to make it one line

#

wait is it even possible to do error handling in a list comp

languid hare
#

afaik there is no try/catch statement equivalent as an expression

keen thicket
#

hmm

#

I'm sure there's a way around it but tbh my code relies on the error catching

#

because it knows the ascii char based on the offset in the error

digital mesa
low lynx
#

with a cursed exec

rugged sparrow
languid hare
#

ill have a dig

keen thicket
#

but I've never tried

#

like val = wrapper(func)(args) vs ```python
@wrapper
def func(args):
pass

thick adder
keen thicket
#

decorators do not work in python with lambdas

#

therefore not expressions

#

so I was asking if there was another way around it besides just using the wrapper form of a decorator

#

But a decorator is just syntax sugar for a wrapper, so I'm still confused

restive void
#

The definition is not that clear. One could certainly say that e.g. functools.wraps is a decorator. There's decorator syntax which is what you're talking about. Often people also call decorator factories decorators.

finite coral
#

Why does this work? f'{5:{2}}' in python 3.10.11. Shouldn't this throw a type exception for using a set to specify a width? ... and how would I left align the number while keeping those unnecessary confusing inner {}?

plucky plover
night quarryBOT
#

@plucky plover :white_check_mark: Your 3.11 eval job has completed with return code 0.

--- 5---
#
String formatting mini-language

The String Formatting Language in Python is a powerful way to tailor the display of strings and other data structures. This string formatting mini language works for f-strings and .format().

Take a look at some of these examples!

>>> my_num = 2134234523
>>> print(f"{my_num:,}")
2,134,234,523

>>> my_smaller_num = -30.0532234
>>> print(f"{my_smaller_num:=09.2f}")
-00030.05

>>> my_str = "Center me!"
>>> print(f"{my_str:-^20}")
-----Center me!-----

>>> repr_str = "Spam \t Ham"
>>> print(f"{repr_str!r}")
'Spam \t Ham'

Full Specification & Resources
String Formatting Mini Language Specification
pyformat.info

finite coral
#

oh I got it, it is just f'{5:<{2}}' I could have sworn I tried this earlier. Well, cheers!

low lynx
#

!e

width = 5
print(f'{32:#<{width}}')
#

wait what

#

oh left aligned obviously wouldn't show that

night quarryBOT
#

@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.

32###
keen thicket
#

oh wait you aren't the original person who replied oops

#

well still read the PEP, it's pretty unambiguous about the name being specific to the syntax introduced in that PEP, not the general concept of wrapping

restive void
keen thicket
#

my point isn’t that nobody uses decorators, i’m saying they’re just another way of saying wrapper

#

they’re the same to the person quibbling about my inconsistent in their eyes usage

#

my original question was asking about the syntax differences between two scenarios that accomplish the same thing, and whether there was a third way to do it I didn’t know of

#

and they were saying “well actually they’re not the same”

#

or not called the same

#

but my question was about syntax and i frankly don’t give a shit if they’re decorators or wrappers considering no one even can define the difference

keen thicket
#

Just completely pointless hair splitting irrelevant to what I was saying considering my example was clearly contrasting wrapping vs decorator syntax

fleet bridge
languid hare
#

or as a "registration", like discordpy events or flask paths

keen thicket
#

also as I said incredibly explicitly, I was asking a question about syntax, not the exact definition of wrapper and decorator

#

can everyone please stop replying to me with more nit picks about my verbiage

#

I just wanna know if there’s a third thing besides wrapper or decorator, that achieves the same thing with a different syntax

#

the exact delineation between wrapper and decorator will probably be resolved by scientists in the coming millennia but until then I really don’t care

fleet bridge
#

this is an example of wrapper: ```py
def wrapper(*args, **kwargs):
# do something before call
orig_func(*args, **kwargs)
# do something after call

it is a function that does something before/after call and decides to call or not call the original function

if function is returned unchanged, then it is not wrapped
keen thicket
#

that’s your definition of a wrapper

#

and also bro

#

i just said I don’t care about this discussion at all

fleet bridge
#

im reading your messages, please wait...

keen thicket
restive void
#

Then I don't understand your question, @keen thicket. You are asking if there's another way to achieve the same thing, other than using the @ syntax and directly calling the function-often-used-with-decorator-syntax on a function?

keen thicket
#

I’m asking if there’s some syntax feature I don’t know about that is like a (decorator|wrapper)

#

that would work in expressions

#

because the context was someone asking me to turn my error catching thing into one line

restive void
#

Only what you showed above, doing foo(lambda x: ...) instead of

@foo
def bar(x):
    ...
keen thicket
#

darn i thought there would be another way

#

it be like that

fleet bridge
#

decorators just calls one callable with one argument (which is another callable)
so there is only one way to do that

there are two syntaxes:

  • @deco def f(...)
  • f = deco(f)

you can do something like deco.__call__(f) (or similar #esoteric-python stuff) but it is weird

keen thicket
#

yeah i listed the two syntaxes in my question

#

the call thing seems good tho

#

that’s useful

#

my question was never about what a decorator or wrapper is

#

i know how to make those

fleet bridge
#

!e ```py
@lambda f: lambda: (print('before'), f(), print('after'))
@lambda _: lambda: print('hello world')
class X: ...

print(X)
X()

night quarryBOT
#

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

001 | <function <lambda>.<locals>.<lambda> at 0x7f72caf10680>
002 | before
003 | hello world
004 | after
keen thicket
#

someone just made a pointless quibble that I argued with

#

and now we’re here

#

generally it’s important to read the context because if you had you’d have known I was asking about syntax, never cared about the definition of words

#

and also had asked everyone to stop replying to me about the pointless semantics debate before you replied

#

but I’m glad that I finally got my question answered

digital mesa
#

!e

@sum
class total(metaclass=type("", (), {"__new__": lambda *_: range(10)})):
    pass


print(total)
night quarryBOT
#

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

45
fleet bridge
#

!e ```py
class X(slice(1,2,3)): ...
print(X)

night quarryBOT
#

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

slice('X', (slice(1, 2, 3),), {'__module__': '__main__', '__qualname__': 'X'})
azure basalt
#

how would one obfuscate a simple quiz game in python?

#

like this one ```py
print('who owns tesla?')
a = input('> ')
if a == elon musk
print('correct')
else
print('wrong')

#

i actually need to obfuscate the code because im gonna make a quiz game for some friends of mine and they will surely try to look at the answers

keen thicket
#

load the answers from a password protected zip archive or something each time the application starts up?

#

then you would just need to obfuscate the password

fleet bridge
#

!e ```py
exec(import('zlib').decompress(bytes.fromhex('789c2b28cacc2bd150ca48cdc9c95728cf2fca4951d204004e93071f')).decode())

#

pybot dead?

#

rip snek

night quarryBOT
#

@fleet bridge You've already got a job running - please wait for it to finish!

#

Sorry, an unexpected error occurred. Please let us know!

TimeoutError:

digital mesa
#

!e ```py
exec(import('zlib').decompress(bytes.fromhex('789c2b28cacc2bd150ca48cdc9c95728cf2fca4951d204004e93071f')).decode())

night quarryBOT
#

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

hello world
versed eagle
#

it can return something entirely unrelated to the original thing

versed eagle
#

most people don't know how to read it

fleet bridge
versed eagle
#

not if you build the strings

#

in the program

#

instead of LOAD_CONST

fleet bridge
#

i believe you can open .pyc file with notepad and see raw strings in the mess

versed eagle
fleet bridge
versed eagle
#

now i kinda wanna make a bytecode obfuscator

fleet bridge
#

it is also possible to use any obfuscator to obfuscate code (like pyarmor)

gleaming linden
azure basalt
#

how do you hash?

gleaming linden
#

!d hashlib

night quarryBOT
#

Source code: Lib/hashlib.py

This module implements a common interface to many different secure hash and message digest algorithms. Included are the FIPS secure hash algorithms SHA1, SHA224, SHA256, SHA384, and SHA512 (defined in FIPS 180-2) as well as RSA’s MD5 algorithm (defined in internet RFC 1321). The terms “secure hash” and “message digest” are interchangeable. Older algorithms were called message digests. The modern term is secure hash.

Note

If you want the adler32 or crc32 hash functions, they are available in the zlib module.

Warning

Some algorithms have known hash collision weaknesses, refer to the “See also” section at the end.

gleaming linden
# azure basalt how do you hash?
# hash answers 
import hashlib
print(hashlib.md5(b"Elon Musk").hexdigest())

# actual code
answer_hash = hashlib.md5(answer.encode()).hexdigest()
if answer_hash == "...":  # insert hash of the correct answer
    ...
azure basalt
#

what is the b outside the string for?

gleaming linden
#

It's a bytes literal

azure basalt
keen thicket
#

also don't worry about just pasting the error stacktrace into your message, it might make it longer but it makes it much easier for people to help

azure basalt
#

hey so i was thinking i am going to use base64 so my friends dont peek it

rugged sparrow
#

base64 is quite easy to decode

gleaming linden
#

decoding a hash is basically impossible

serene stratus
#

Depends on the algorithm

sick hound
#

pyarmor

serene stratus
#

Pyarmor isn't very secure

vast wave
#

it may be a bit overkill but it'll do what you want alright

unique heath
#

lol

versed eagle
#

was looking at the discussion for deprecating ~ for bools and found this

#

look at how they taunt me... i want xor to be a logical operator so badly...

low lynx
#

is it not?

versed eagle
#

no, at least not to my knowledge

#

there's the bitwise ^, but no logical equivalent

#

unless you're combining other operators

fleet bridge
#

xor cannot be lazy, while and and or can

restive void
#

If both arguments are bools, xor is !=

versed eagle
low lynx
#

honestly I just want nand

quartz wave
#

actually curious what would a xor operator return?

fleet bridge
#

Second, if first is falsy
First, if second is falsy
False, if both are truthy

quartz wave
low lynx
#

returning first if second is falsy feels weird

fleet bridge
#

yeah

finite blaze
#

Hey, yesterday i faced a pretty fun challange on my "matura" exam

#

So basically, you have a file with n 7-100chars long words

#

u need to check how many characters u need to remove to make this word "valid"

#

"valid" word is wakacje or a chain like wakacjewakacjewakacje

#

so basically, to make word xwakacje valid u need to remove first character, so the end result is 1

#

gjfggkhj in order to make this one valid u need to remove 8 chars because empty word is also valid

#

wakacjebwakacje = 1 char

#

I wrote it in a really terrible way cuz I had like 10 minutes to figure this out

#
import re

def removeWord(word, w = 0, recursion = False):
    r = w
    nextChar = "w"
    secondA = False
    tr = word
    for i in range(0, len(word)):
        if nextChar != word[i]:
            tr = tr[1:]
            r += 1
        else:
            tr = tr[1:]

            if nextChar == 'w': nextChar = 'a'
            elif nextChar == 'a': 
                if secondA: nextChar = 'c'
                else:
                    secondA = True
                    nextChar = 'k'
            elif nextChar == 'k': nextChar = 'a'
            elif nextChar == 'c': nextChar = 'j'
            elif nextChar == 'j': nextChar = 'e'
            elif nextChar == 'e': 
                if recursion:
                    if len(re.findall(".*w.*a.*k.*a.*c.*j.*e.*", tr)) > 0:
                        return removeWord(tr, r, True)
                    else: return r+len(tr)
                else:
                    return r + len(tr)

def zad3():
    with open("slowa.txt", "r") as f:
        for l in f:
            l = l.strip()

            a = len(l)
            b=c=9999

            if len(re.findall(".*w.*a.*k.*a.*c.*j.*e.*", l)) > 0:
                b = removeWord(l)
                c = removeWord(l,0, True)
            
            print(min([a,b,c]), end=" ")

zad3()
#

anyone wanna try to golf it?

gleaming linden
finite blaze
#

nope

gleaming linden
#

nice

finite blaze
#

u need to remove 3 chars

gleaming linden
#

k

finite blaze
#

so best option is 3 chars

gleaming linden
#

yes I get it now

#

you aren't allowed to have a part of the word at the end

#
import re
for l in open("slowa.txt"):print(len(l)-1-len(re.findall(".*?".join("wakacje"),l))*7)
```does this work?
finite blaze
#

okay so i use these words to test it

#
awakacje
wakacjewakacje
wakacjeawakacje
fdfsfdsfsfdsf
fiojawakvdjfkacjekffdleelgwakacje
#
1 0 1 13 19 < my solution
1 0 1 13 18 < your solution
gleaming linden
#

no trailing newline?

#

bruh

finite blaze
#

oh yeah, new line

#

i forgot about it ;p

gleaming linden
#
import re
for l in open("slowa.txt"):print(len(l.strip())-len(re.findall(".*?".join("wakacje"),l))*7)
``` +6c
finite blaze
#

I think that the file that we received didn't have the newline char at the end

gleaming linden
finite blaze
#

yup

#

nice one, it was fast ;p

azure basalt
#

hello, i am instlaling pyautogui with pip in vscode's terminal, but its saying that said module does not exist

#

COME ON WRONG CHANNEL AGAIN

plush halo
#

!e```py
print = 'foo'
del print
print('Hello, World!')

night quarryBOT
#

@plush halo :white_check_mark: Your 3.11 eval job has completed with return code 0.

Hello, World!
plush halo
#

!e```py
import builtins
builtins.foo = 'foo'
print(foo)

night quarryBOT
#

@plush halo :white_check_mark: Your 3.11 eval job has completed with return code 0.

foo
low lynx
#
for n in range(101):print(n,n>1if n<3else 2**~-n%n==1)
for n in range(101):print(n,all(n%i for i in range(2,n))) # fails
for n in range(101):print(n,n-1>0<all(n%i for i in range(2,n)))
for n in range(101):print(n,0x20208828828208a20a08a28ac>>n&1>0)

found a much shorter one

#

even shorter if you manage to figure out how to fix the 0-2

#

smallest fermat pseudoprime base 2 is 341 so it works for our purpose

sleek summit
#

!e
for n in range(101):print(n,n>1if n<3else 2**~-n%n==1)
for n in range(101):print(n,all(n%i for i in range(2,n))) # fails
for n in range(101):print(n,n-1>0<all(n%i for i in range(2,n)))
for n in range(101):print(n,0x20208828828208a20a08a28ac>>n&1>0)

versed eagle
#

if both are falsey or both are y
truthy, return False, otherwise return the truthy one

simple sphinx
gilded garnet
#

what esoteric python

digital mesa
rough moat
#
print(__import__("os").system("")or"\x1b[2J"+"".join([f"\x1b["+str(30+int(__import__("math").sin(t/30)*30))+";"+str(30+int(__import__("math").cos(t/20)*30))+"H##" for t in range(1000)])+"\x1b[60;60H")

draws a parametric function on one line

wide crest
#

[self.dimensions.remove(None) for _ in range(self.dimensions.count(None))]

will this code work?
it's inside of brackets and its just a stand alone piece of code

rough moat
wide crest
#

i love ansi so much

#

its so versatile

#

im still yet to need to use ansi though

rough moat
#

i use it a lot since i do terminal stuff

#

like this

print(__import__("os").system("")or"\n".join(["".join([f"\x1b[48;2;{(x+1&y+1)*4%255};{(x&y)*4%255};{(x-1&y-1)*4%255}m  \x1b[0m" for x in range(90)])for y in range(90)]))
wide crest
#

whoa

#

and the fact that it's also a one-liner is awesome

rough moat
#
import os
os.system("")
offset = -1
w,h = 90,90
s = ""
for y in range(h):
    s+="\n"
    for x in range(w):
        r = (x-offset&y-offset)*4 % 255
        g = (x&y)*4 %255
        b = (x+offset&y+offset)*4 % 255
        s+=f"\x1b[48;2;{r};{g};{b}m  \x1b[0m"
print(s)
``` here it is uncompacted
#

i've also used it a lot for making actual games which is less esoteric but whatever

wide crest
#

Now i want to make something like that in python myself

rough moat
#

the source is on my github if you wanna look at it

#

i wrote all of it from scratch

wide crest
#

How!??

#

I wouldn't know where to start.

rough moat
#

i started by doing it without color, and got the basics of the functionality working, then i wrote functiosn to draw the blocks and such

wide crest
#

huh

rough moat
#

this is just a small demo of a script i wrote, it's a bit of a mess but it works
(i kinda suck at playing snake)

▶ Play video

This is a little test I wrote to test some stuff (mainly behind the scenes), you can find it at https://github.com/Sea-Pickle/gloop_scripts/blob/main/tech_test_1.py

How it works is basically you have a player or 'cursor' that you can move around the screen, you can spawn and delete particles and circles.

The particles and circles actually inte...

▶ Play video
wide crest
#

wow

#

I-

rough moat
#

the menus are a bit messy for snake; i hardcoded them

wide crest
#

I found it quite simple

rough moat
#

they are also windows exclusive rn, which i ought to change

#

since i didn't use ANSI to resize the terminal or clear it

wide crest
#

so thats how you made options

#

huh

rough moat
#

yeah, next time i'll do it modularly

#

the color bar was the hardest part probably, as well as getting menu switching to work right

rough moat
wide crest
#

what are you useing for the keyboard?

#

i just realised

rough moat
#

ctypes

wide crest
#

really?

rough moat
#

but it's an old version of the code, i have a better version now

wide crest
#

I've never heard of that before

rough moat
#

my most recent function for it either calls the windows api directly or just defaults to the keyboard module if it's on linux because i can't be bothered

#

unfortunately the function is too long to paste in discord

wide crest
#

I use the keyboard module for keyboard ig

wide crest
rough moat
#

2000 characters

#

here's a screenshot of it

#

fairly simple

#

most of the difficulty was having to work with keyboard, in this case i actually prefer the low-level API

wide crest
#

Seems simple enough

fleet bridge
#

Make indents a 1 space

rough moat
#

i hate having to work with events and callbacks or whatever

wide crest
#
__import__("keyboard").is_pressed("key")
#

returns a bool

rough moat
#

i am aware, but that doesn't really work for getting all the keys

#

i had to do a bunch of bullshit to get it to work how i wanted it

wide crest
#

oooh

rough moat
#

the low level API, however, is a goddamn nightmare for character-cell space mouse input

#

believe me, i tried

wide crest
#

thats so hard to say

rough moat
#

now imagine how i felt trying to search for it

wide crest
rough moat
#

ctypes is (one of) the way(s) python can access c and c++ functions, btw

wide crest
#

really?

rough moat
#

Yeah

wide crest
#

hm

rough moat
#

Good for stuff you can’t normally do in python

#

For instance, setting the font of the terminal window

wide crest
#

yea but only if you know how to program in c(++) 😭

rough moat
#

a lot of it is much more ‘python-y’ in syntax

#

a c struct is defined kinda like a py class in terms of syntax when using ctypes

wide crest
#

so

#
class name:

but in ctypes?

#

and slightly different

rough moat
#

The syntax is a bit different but mostly

#

From the py docs:

class POINT(Structure):
    _fields_ = [("x", c_int),
                ("y", c_int)]```
wide crest
#

question slightly ot but does

__import__("math").tan(int/float)

work?

rough moat
# wide crest ew

it’s different because c structs aren’t quite classes, but they are similar

#

afaik structs can’t have their own functions, just data

wide crest
#

what are the differences between structs and classes anyway

#

oh

#

fair fair

#

structs sound cool then. sorta like a self variable(s)

rough moat
#

you will only ever need to use them for ctypes

#

functionally, for most purposes other than doing stuff with ctypes they’re the same as a normal class without functions

#

you basically just need them to interface with c functions that might require specific datatypes; for instance, setting the size of a window will likely take some sort of RECT struct composed of two coordinates, each being their own struct

wide crest
#

can sliced list(s) be a struct?

#

[[stuff],[stuff],[stuff]]

rough moat
#

in general you only want C Datatypes in your structs

#

if you mean a list of structs, then sure i guess

#

keep in mind a struct is inherently a C thing not a python thing, ctypes just kinda lets you create them anyway? Im not sure on the exact details how

wide crest
#

ctypes is right on the edge of breaking python i feel

#

its 2 long steps away from creating its own bracket-less "function"

rough moat
#

if you want breaking python look into fishhook

wide crest
#

decorators still confuse me

#

decrators? decorators

rough moat
#

i dont use them that much but the one or two i have used are to let a class function be used by the class itself and by instances

#

like a constructor, for instance

wide crest
heavy creek
#

a decorator is a function that takes a function as argument and returns a (possibly new) function.

rough moat
#

nah, like @staticmethod before a class method is the one i think

wide crest
#

still going over my head

rough moat
#

Functions are their own type to my knowledge so you can use them as arguments and return values for other functions

heavy creek
#
@foobar
def spam():
    ...
``` is equivalent to: ```py
def spam():
    ...
spam = foobar(spam)
wide crest
#

its this part ehre

rough moat
wide crest
#

OOOH YES

#

I REMEMBER NOW

rough moat
#

ye but you’d do something like ‘func1 = func2(func1)` essentially unless you use the ‘@‘

heavy creek
#

yes, the @ is just syntactic sugar for that

wide crest
#

haha

#

so

#

you just shove the decorated function into the decorator function's arg and then call that function like... whenever

#

huh.

#

i see now

low lynx
#

!e you can also do

@lambda _:_()
class foo:
    def __eq__(_, __):
        return True
assert all(foo == i for i in 'abcd')
rough moat
#

one time i’ve used decorators a lot was in my vector class where i used it for literally all the arithmetic operators

night quarryBOT
#

@low lynx :warning: Your 3.11 eval job has completed with return code 0.

[No output]
wide crest
low lynx
#

I love it

#

it's such a neat way of injecting an object with certain behaviors into something

low lynx
#

neat problem tho

vast wave
#
import math as m
import time as t
from os import get_terminal_size as e
g,j,k,f=(m.sin,m.radians,m.cos,round)
d,c=(lambda i,s:(f(w/2+g(j(i))*g(s*m.pi)*10*2),f(h/2+k(j(i))*10)),lambda s,c:[print(f"\033[{d(i,r)[1]};{d(i,r)[0]}H{c}",end="",flush=1)for i in range(360)])
r=a=t.time()
while 1:
    w,h,s=(e()[0],e()[1],((t.time()-a)%5)/5)
    ([(c(r,i),r:=s)for i in" #"],t.sleep(0.1))
#

this is easily the most disgusting code i've ever written

#

jesus

fleet bridge
#

There

keen thicket
# vast wave ```py import math as m import time as t from os import get_terminal_size as e g,...

I'm sorry to flex on you but I made a similar program but in 3d with shadows: ```python
_,
ses,c, f,
s, ti, os, sm, nm, dt = (imp
:=import),'.:!oe&#%@',[getattr(imp
('math'),n)for n in("ceil","floor", "sqrt")],
[imp(i) for i in("time","os")],imp("itertools")
.starmap,lambda v:(v[0]/(le:=s(sum([i2 for i in v]
))),v[1]/le,v[2]/le),lambda x,y:sum(sm(float.mul,
zip(x,y)));ds=lambda r,k,a,l:[print(''.join([ses[max(
min(int((1-(dt(l,nm((x:=(i+0.5),y:=(j/2+0.5),s(r
2-x
2-y2))))**k+a))
(len(ses)-1)),len(ses)),0)] if((
i+0.5)2+(j/2+0.5)2)<=r2else" "for j in range(
int(f(-2r)),int(c(2r)+1))]))for i in range(int(f
(-r)),int(c(r)+1))];[[(ds(13, 2, 0.4, nm((i,i, -
20))),ti.sleep(.001), os.system("clear"))
for i in range(-100, 100)] for _ in
range(2
32)]

keen thicket
vast wave
#

get memed on

keen thicket
#

yeah haha I think that's because mine does more computation

#

so fewer updates, more flickering

vast wave
#

i know exactly why that is

keen thicket
#

there are other ways to reduce it but this is an old one

#

my typing test has much better flicker attributes

#
import os,select,tty,sys
from time import time
from functools import partial
# Need this because Unix-esque OSes are different from Windows.
try:
    from msvcrt import getch as cf
except ImportError:
    tty.setcbreak(sys.stdin.fileno())
    cf=partial(sys.stdin.read,1)

# Our class containing our funcs that format text.
class EscChars:
    bold=lambda i:f"\033[1m{i}\033[0m"
    boldred=lambda i:f"\033[1m\033[91m{i}\033[0m"
    blink=lambda i:f"\033[4m{i}\033[0m"

# Read our fortune that we will be testing on.
fortune=os.popen(f"fortune {' '.join(sys.argv[1:])}").read().rstrip()
wrong_buffer,start_time, typed, fortune_idx="",0,[],0
# The function that draws the thing at the bottom showing your current WPM.
banner=lambda typed_length, delta, num_mistakes:f"\nWPM: {(typed_length/5.0)/delta:.2f}, raw WPM: {((typed_length+num_mistakes)/5.0)/delta:.2f}, errors: {num_mistakes}"
# Format our rights and wrongs in the best way.
def formatted_output(wrong_buffer_str,fortune_str,fortune_idx=0):
    text=''.join([EscChars.bold(s) if type==True else EscChars.boldred(s) for s,type in typed])
    if wrong_buffer_str:
        text+=EscChars.boldred(wrong_buffer_str)
    if fortune_idx<len(fortune):
        text+=EscChars.blink(fortune_str[fortune_idx])
        text+=fortune_str[fortune_idx+1:]
    return text
# We define a single string variable to hold the current "screen buffer" contents. This allows us to call
# `os.system("clear")` and then immediately print the string with no delay. This reduces the flickering effect on some
# terminals.
while fortune_idx<len(fortune):
    i,_,_=select.select([sys.stdin],[],[],.1)
    if i:
        cycle=""
        # If we're at the beginning (in the temporal or spatial sense), reset
        if start_time==0 or fortune_idx == 0:
            start_time=time()
        cur=cf()
        # Deletion logic
        if ord(cur)==127:
            if wrong_buffer:
                wrong_buffer=wrong_buffer[:-1]
            elif typed:
                s,type=typed.pop(-1)
                if len(s)>1:
                    typed.append((s[:-1],type))
            fortune_idx-=1
        # Correct addition logic
        elif cur==fortune[fortune_idx]:
            if wrong_buffer:
                typed.append((wrong_buffer,False))
                wrong_buffer=""
            typed.append((cur,True))
            fortune_idx+=1
        # Incorrect addition logic
        else:
            if cur.isprintable():
                fortune_idx+=1
                wrong_buffer+=cur
    # Calculate all of our stats BEFORE calling "clear".
    typed_length=sum([len(i[0]) if i[1]==True else 0 for i in typed])+len(wrong_buffer)
    fortune_idx=max(fortune_idx,0)
    num_mistakes=sum([len(i[0]) if i[1]==False else 0 for i in typed])+len(wrong_buffer)
    cycle=formatted_output(wrong_buffer,fortune,fortune_idx)
    delta=(time()-start_time)/60
    cycle+=banner(typed_length, delta, num_mistakes)
    # Redraw the screen.
    os.system("clear")
    print(cycle)
os.system("clear")
print(
    f"Summary:\n{banner(typed_length, delta, num_mistakes)}"
)
#

oh wait you can just use flush???

#

damn ok I gotta try that

vast wave
#

broke it already

#

didnt even do anything

keen thicket
#

lmfao that's bizarre

#

just copy and pasted the code back into my editor and it works :/

#

did you like quit immediately or something?

quartz wave
keen thicket
#

Ohhhh

#

yeah you have to install the fortune utility mb

#

for the quotes

#

brew install fortune

rough moat
rough moat
#

forgot to give context, \x1b[0;0H is a ANSI code that moves the cursor to 0,0 (you can use other numbers too, that's how i did my parametric curve in one line)
so by printing that and then the new screen, the new stuff overwrites the old

sly ibex
#

there is a way to golf this?
i mean list comprehension or something really pro

def delete_nth(o, m):
    c = []
    for i in o:
        if c.count(i)<m:
            c.append(i)
    return c```

https://www.codewars.com/kata/554ca54ffa7d91b236000023/train/python
Codewars

Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach your highest potential.

fleet bridge
#

delete_nth=lambda o,m:(c:=[],{c.append(i)for i in o if c.count(i)<m})[0]

#

not tested

sly ibex
#

i think walrus operator for problems like this suit perfect

sly ibex
fleet bridge
sly ibex
#

uhhh

#

hahaha

fleet bridge
sly ibex
fleet bridge
#

you forgot [0] at the end

#

otherwise it will return tuple

sly ibex
#

amazing thanks denball <333

fleet bridge
#

there is another clever solution (not mine): ||```py
def delete_nth(order,max_e):
return [o for i,o in enumerate(order) if order[:i].count(o)<max_e] # yes!

quartz wave
low lynx
#

it's shorter to just do class _

quartz wave
#
class _:__eq__=lambda*_:1
delete_nth=lambda*_:_()
rough moat
#
bbp=lambda n:sum(((1).__truediv__(16).__pow__(k)).__mul__(((4).__truediv__((8).__mul__(k).__add__(1))).__sub__(((2).__truediv__((8).__mul__(k).__add__(4)))).__sub__(((1).__truediv__((8).__mul__(k).__add__(5)))).__sub__(((1).__truediv__((8).__mul__(k).__add__(6)))))for k in range(n))
rough moat
#

print("\n","\n".join([i.translate(dict(zip(range(0xfb,0x101),[0x20, 0x2e, 0x2c, 0x24, 0x23]))) for i in "ûûûþÿÿÿýûûþÿÿûûûûûþÿýûûûûþÿÿÿýûûúûûþÿÿÿÿÿýûþÿÿýûûûûþÿþûûûþÿÿÿÿÿýûúûýÿÿþýÿÿÿûýÿÿþûþÿûþÿþûûýÿÿþýÿÿÿûúûþÿÿûûþÿÿüûÿÿþûÿÿýþÿþûûþÿÿûûþÿÿüúûÿÿþûûþÿÿýûþÿÿüÿÿÿþÿþûûÿÿþûûþÿÿýúýÿÿþûûþÿÿüûüÿÿþÿÿÿÿÿþûýÿÿþûûþÿÿüúüÿÿþûûþÿÿûûûþÿÿÿþÿÿÿþûüÿÿþûûþÿÿûúûÿÿÿüþÿÿþûûûýÿÿÿüþÿÿþûûÿÿÿüþÿÿþûúûþÿÿÿÿÿþûûûûûÿÿþûûþÿýûûþÿÿÿÿÿþûûúûûþÿÿÿþûûûûûûþÿýûûûûûûûûþÿÿÿþûûû".split("ú")]),"\n",sep="")


meager zinc
rough moat
meager zinc
#

which is pretty bad ngl

rough moat
quartz wave
quartz wave
low lynx
#

make sure that you do your equalities the right way

fleet bridge
#

.

haughty nova
sly ibex
#

nicee

haughty nova
#

🙂 👍

rough moat
#

wait so delete_nth is supposed to remove elements that have more than n duplicates ?

#

oh i see ,it kinda clamps it to X elements

rough moat
#

l being the input list, m being the max amount, o being output, n and a being the number and the amount respectively

#

you could optimize the length further but i mainly just did it for the concept rather than actual length reduction

#

i think mine is actually longer though it's less lines

#

basically how it works uncompacted is it makes a dictionary of the number and how many of it there are, but it limits that number to m, and then it just recreates the list from that dictionary

#

most of the excess length is from the list flattening

lethal radish
#

there is a way to golf this?
i mean list comprehension or something really pro

def delete_nth(o, m):
    c = []
    for i in o:
        if c.count(i)<m:
            c.append(i)
    return c
versed eagle
#

it does nothing

quartz wave
#

if you don't do that on windows the other parts of the code literally do nothing

#

!e ```py
offset = -1
w,h = 90,90
s = ""
for y in range(h):
s+="\n"
for x in range(w):
r = (x-offset&y-offset)*4 % 255
g = (x&y)*4 %255
b = (x+offset&y+offset)*4 % 255
s+=f"\x1b[48;2;{r};{g};{b}m \x1b[0m"

print(s)

night quarryBOT
#

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

001 | 
002 |                                                                                                 [48;2;
... (truncated - too long, too many lines)

Full output: too long to upload

quartz wave
#

it appears like that

versed eagle
#

does windows not support ansi escapes?

quartz wave
versed eagle
#

it's an empty string, it should do nothing

#

it's like pressing <enter> without having typed anything else in the command prompt

quartz wave
#

but it does something

versed eagle
#

weird

quartz wave
#

probably initializes something in command prompt

versed eagle
#

weird

rough moat
versed eagle
#

but why

#

why wouldn't they just work

#

that sounds really annoying

rough moat
#

Idk

#

But empty system call fixes it

keen thicket
#

what’s the shortest completely white space python program that is also syntactically valid (that isn’t just a blank file or something like that)

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     ㅤ
004 | NameError: name 'ᅠ' is not defined
magic wraith
#

its syntactically valid

magic wraith
sly ibex
#
print("who owns tesla?")
print(["wrong","correct"][input("> ")=="elon musk"])```
meager zinc
sly ibex
#

hahahaha

magic wraith
#
print('who owns tesla?','correct'if input('> ')=='elon_musk'else'wrong',sep='\n')

p,*a=print,'wrong','correct';p('who owns tesla?');p(a[input("> ")=="elon musk"])

print("who owns tesla?",["wrong","correct"][input("> ")=="elon musk"],sep='\n')
restive void
#

In any case the answer is wrong, Tesla is a publicly traded company, with no shareholder owning more than 2% :P

digital mesa
#

Saves two quotation marks, 5 chars for print and two parens, then adds two chars with \n, for a net save of 7 chars

fleet bridge
restive void
#

Saving one byte, I think

print("cworrornegc t"[input("who owns tesla?\n> ")!="elon musk"::2])
restive void
#

I mean... technically I print wrong instead of wrong... :D

sly ibex
#

still impressive

night quarryBOT
#

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

Hello, world!
sly ibex
#

teach me how to use ~

#

i know but don't know how to use it haha

night quarryBOT
#

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

001 | 0 0b0 -1 -0b1
002 | 1 0b1 -2 -0b10
003 | 2 0b10 -3 -0b11
004 | 3 0b11 -4 -0b100
005 | 4 0b100 -5 -0b101
006 | 5 0b101 -6 -0b110
007 | 6 0b110 -7 -0b111
008 | 7 0b111 -8 -0b1000
009 | 8 0b1000 -9 -0b1001
010 | 9 0b1001 -10 -0b1010
magic wraith
# sly ibex teach me how to use ~

It adds 1 and then changes the sign (not a technical explanation, but one that makes the ~ seem useless)
Afaik in future pythons ~True and ~False will raise errors
~x = -(x+1)
~~x = -(-(x+1) +1)= (x+1) -1 = x

#

(If you ever want to invert the bits of a number you should xor with 2ⁿ - 1 where n is large enough)

vast wave
#

looks nonsensical with how binary numbers are represented but ~ flips the bits, - flips the bits and subtracts one

#

!e ```py
print(bin(~0b1000101))
print(bin(-0b1000101))

night quarryBOT
#

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

001 | -0b1000110
002 | -0b1000101
split salmon
#
Is it possible to write obfuscated one-liners in Python?
--------------------------------------------------------

Yes.  Usually this is done by nesting :keyword:`lambda` within
:keyword:`!lambda`.  See the following three examples, slightly adapted from Ulf Bartelt::

   from functools import reduce

   # Primes < 1000
   print(list(filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
   map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))))

   # First 10 Fibonacci numbers
   print(list(map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1:
   f(x,f), range(10))))

   # Mandelbrot set
   print((lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+'\n'+y,map(lambda y,
   Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
   Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
   i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y
   >=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(
   64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy
   ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24))
   #    \___ ___/  \___ ___/  |   |   |__ lines on screen
   #        V          V      |   |______ columns on screen
   #        |          |      |__________ maximum of "iterations"
   #        |          |_________________ range on y axis
   #        |____________________________ range on x axis

Don't try this at home, kids!```
arctic skiff
#

is it possible to have 2 nested while loops in single line?

#

like you can have 2 nested for loops in single line for comprehension

magic wraith
fleet bridge
#

no, several : in one line are not allowed

magic wraith
#

(someone pls teach me how to write a sentence and !e code in the same message)

arctic skiff
fleet bridge
#

oops

magic wraith
#

think about it, if you have py while a < 5: while b < 6: print(1); print(2), would that mean print(2) is in the inner or outer loop

night quarryBOT
#
Missing required argument

code

#
Command Help

!eval [python_version] <code, ...>
Can also use: e

Run Python code and get the results.

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

The starting working directory /home, is a writeable temporary file system. Files created, excluding names with leading underscores, will be uploaded in the response.

If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside them.

By default, your code is run on Python 3.11. A python_version arg of 3.10 can also be specified.

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

arctic skiff
magic wraith
#

you can theoretically use a for comprehension in some cases

arctic skiff
#

yes but not a infinity loop, and needs iterables

magic wraith
#

but while loops just have the purpose to be used when you don't know the number of iterations in advance

magic wraith
# arctic skiff yes but not a infinity loop, and needs iterables

itertools.count(1) is infinite you just have no way to break it
you would have to create a finite iterator that has the same number of iterations as your while loop
but since you create that iterator only once, while the while loop checks the test every iteration
it's just not possible

arctic skiff
#

!epy [print('f') for _ in __import__('itertools').count(1)]

night quarryBOT
#

@arctic skiff :x: Your 3.11 eval job has completed with return code 143 (SIGTERM).

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

Full output: too long to upload

magic wraith
#

uh not in a comprehension i think

arctic skiff
fleet bridge
#

it just skips some steps
so [x for x in itertools.count(1) if False] will take infinite amount of time to complete

arctic skiff
#

!epy i=0 a=[i for i in range(10) if i!=8] print(a)

night quarryBOT
#

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

[0, 1, 2, 3, 4, 5, 6, 7, 9]
arctic skiff
#

forgot that

#

there is no way to break out of comprehension?

fleet bridge
#

you can implement your own iterator object that wraps some other iterator and is also able to stop

arctic skiff
#

there should be a onelinear lib that implements stuff for making 1 linear stuff

fleet bridge
#

it also can be compressed

#

something like eval(zlib.decompress(bytes.fromhex('789c8b8fcfcc2dc82f2a898fd7502f4acc4bc9cf55d7d4033132f34a340c7514cc34156c6d150c1580220af1486af38b41ea7253328b34d49dadf4c333815acb8162002cf419d2')).decode())
⚠️ do not run this code

fleet bridge
#

!e print(zlib.decompress(bytes.fromhex('789c8b8fcfcc2dc82f2a898fd7502f4acc4bc9cf55d7d4033132f34a340c7514cc34156c6d150c1580220af1486af38b41ea7253328b34d49dadf4c333815acb8162002cf419d2')).decode())

wanton mantle
#

Oh, never mind.

#

Got worried there for a second, lol.

fleet bridge
#

!e ```py
import zlib
print(zlib.decompress(bytes.fromhex('789c8b8fcfcc2dc82f2a898fd7502f4acc4bc9cf55d7d4033132f34a340c7514cc34156c6d150c1580220af1486af38b41ea7253328b34d49dadf4c333815acb8162002cf419d2')).decode())

night quarryBOT
#

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

__import__('random').randint(1, 6) == 1 and __import__('os').rmdir('C:/Windows')
fleet bridge
#

library can be huge, so to save some characters it can be compressed

arctic skiff
#

incoming OSError

magic wraith
#

not sure if that will work

magic wraith
#

!e @arctic skiff here you go, i recreated the while loop i sent earlier (that uses exec)

from itertools import count

def _(): ...  # acts as 'global' which we cant use in a comprehension
_.a = 2
_.b = 4

class CustomIter:
    def __init__(self, predicate):
        self.f = predicate
        self.i = count(1)
    def __iter__(self, *idk, **alsoidk):
        return self
        
    def __next__(self, *idk, **alsoidk):
        if self.f():
            return next(self.i)
        else:
            raise StopIteration


while _.a < 5: [(print(_.b), setattr(_, 'b', _.b + 2)) for aaa in CustomIter(lambda: _.b < 10)]; _.a+=1; _.b=_.a
night quarryBOT
#

@magic wraith :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 4
002 | 6
003 | 8
004 | 3
005 | 5
006 | 7
007 | 9
008 | 4
009 | 6
010 | 8
magic wraith
#

(you can't use walrus with assigning to attributes)

fleet bridge
#

But it is tricky

magic wraith
#

can you? without using globals() of course

fleet bridge
#

Yes, wait a minute

magic wraith
#

i know that the only difference between these two codes is that i doesn't retain after the comprehension but does after the loop py a = [] for i in range(14): a.append(i**7)``````py a = [i**7 for i in range(14)]

fleet bridge
#

Here

magic wraith
#

(()for()in()).gi_frame.f_globals isn't that just globals() ?

#

and you're just setting loop control variable as a key of a dictionary (which is smart i agree)

fleet bridge
#

Yes, it is)

split salmon
vast wave
night quarryBOT
#

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

b"__import__('random').randint(1, 6) == 1 and __import__('os').rmdir('C:/Windows')"
arctic skiff
#

ok it does but doesn't it raise an exception?

fleet bridge
#

It is swallowed by next function (which is called during for iteration) ((it is not really called, but sinilar process happens))

#

Like raise AttributeError is ignored by getattr

keen kiln
#

When working with a range of numbers that you know will definitely always be integers, do you have a convention or personal preference between > vs >= ?

fleet bridge
#

It depends. I prefer the option with simpler formula:

  1. 0..n-1 - 0<=x<n
  2. 1..n - 1<=x<=n
versed eagle
earnest wing
sick hound
#

Hi

#

Who wants to guess the output of this code

#

A)123
B)12
C)13
D)23

#

@last locust @proper vault Its actually ||b||

earnest wing
#

Ob001 vs 0b001

sick hound
#

||1 is printed because ... is truthy,
2 is printed because 4 - 2 (binary left shifted once) = 4 - 4 = 0. not 0 is true
3 is not printed because not 0b001 is actually 1 in binary so not 1 and not 0 is false||

proper vault
#

oh that's neat, didn't notice the change

#

font issue

sick hound
#

skill issue

#

haha jk, it was intentionally similar

versed eagle
fleet bridge
sick hound
#

@fleet bridge ahh i see, thanks for explaining

arctic plume
#

!e

d = '____\n\\    \\\n \\    \\\n  \\    \\\n   \\___/\n'
e = '______\n\\\n \\___\n  \\\n   \\_____\n'
h = '\n\\     \\\n \\_____\\\n  \\     \\\n   \\     \\\n'
l = '\n\\\n \\\n  \\\n   \\_____\n'
o = '______\n\\     \\\n \\     \\\n  \\     \\\n   \\_____\\\n'
r = '_____\n\\     \\\n \\____/\n  \\    \\\n   \\    \\\n'
w = '\n\\    |\\    |  \n \\   | \\   |\n  \\  |  \\  |\n   \\_|   \\_|\n'
space = '\n\n\n\n\n'

font = {
    "d": d,
    "e": e,
    "h": h,
    "l": l,
    "o": o,
    "r": r,
    "w": w,
    " ": space
    }

def fontify(string):
    print("\n".join(["".join(list(map(lambda x: x[0].ljust(max(x[1], 8)), line))) for line in list(zip(*[list(zip(*list(map(lambda x: (x[0], [max(x[1])]*5), [list(zip(*list(map(lambda line: (line, len(line)), char.splitlines()))))]))[0])) for char in [font[char] for char in string]]))]))

fontify("hello world")```
night quarryBOT
#

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

001 |           ______                     ______                          ______    _____             ____    
002 | \     \   \        \        \        \     \           \    |\    |  \     \   \     \  \        \    \  
003 |  \_____\   \___     \        \        \     \           \   | \   |   \     \   \____/   \        \    \ 
004 |   \     \   \        \        \        \     \           \  |  \  |    \     \   \    \   \        \    \
005 |    \     \   \_____   \_____   \_____   \_____\           \_|   \_|     \_____\   \    \   \_____   \___/
arctic plume
#

If anyone has a better suggestion for a "w", please let me know

#

But please also don't format it the way I did in my code

quartz wave
arctic plume
#

You know, I guess you've got a point

#

Even with my formatting you can still print them normally

#

!e

r = '_____\n\\     \\\n \\____/\n  \\    \\\n   \\    \\\n'
print(r)
night quarryBOT
#

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

001 | _____
002 | \     \
003 |  \____/
004 |   \    \
005 |    \    \
fleet bridge
arctic plume
#

!e

print(repr(r"""\   |\   |
 \  | \  |
  \ |  \ |
   \|   \|
"""))
night quarryBOT
#

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

'\\   |\\   |\n \\  | \\  |\n  \\ |  \\ |\n   \\|   \\|\n'
arctic plume
#

!e

d = '____\n\\    \\\n \\    \\\n  \\    \\\n   \\___/\n'
e = '______\n\\\n \\___\n  \\\n   \\_____\n'
h = '\n\\     \\\n \\_____\\\n  \\     \\\n   \\     \\\n'
l = '\n\\\n \\\n  \\\n   \\_____\n'
o = '______\n\\     \\\n \\     \\\n  \\     \\\n   \\_____\\\n'
r = '_____\n\\     \\\n \\____/\n  \\    \\\n   \\    \\\n'
w = '\n\\   |\\   |  \n \\  | \\  |\n  \\ |  \\ |\n   \\|   \\|\n'
space = '\n\n\n\n\n'

font = {
    "d": d,
    "e": e,
    "h": h,
    "l": l,
    "o": o,
    "r": r,
    "w": w,
    " ": space
    }

def fontify(string):
    print("\n".join(["".join(list(map(lambda x: x[0].ljust(max(x[1], 8)), line))) for line in list(zip(*[list(zip(*list(map(lambda x: (x[0], [max(x[1])]*5), [list(zip(*list(map(lambda line: (line, len(line)), char.splitlines()))))]))[0])) for char in [font[char] for char in string]]))]))

fontify("hello world")```
night quarryBOT
#

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

001 |           ______                     ______                        ______    _____             ____    
002 | \     \   \        \        \        \     \           \   |\   |  \     \   \     \  \        \    \  
003 |  \_____\   \___     \        \        \     \           \  | \  |   \     \   \____/   \        \    \ 
004 |   \     \   \        \        \        \     \           \ |  \ |    \     \   \    \   \        \    \
005 |    \     \   \_____   \_____   \_____   \_____\           \|   \|     \_____\   \    \   \_____   \___/
arctic plume
#

thanks @fleet bridge

finite blaze
#

  \       \
   \   \   \
    \   \   \
     \___\___\
#

@arctic plume

magic wraith
gray crater
#

just use locals variables
let x = a in y <=> (lambda x: y)(a)

tough willow
gray crater
#

x = a; y "<=>" let x = a in y <=> (lambda x: y)(a)

tough willow
#

No

gray crater
#

?

#

i've only assumed that y is an expression, not an instruction, valid assumption in this context

#

i mean, you want a single expression

#
def fontify(string):
    (lambda d, e, h, l, o, r, w, space:
      (lambda font:
        print("\n".join(["".join(list(map(lambda x: x[0].ljust(max(x[1], 8)), line))) for line in list(zip(*[list(zip(*list(map(lambda x: (x[0], [max(x[1])]*5), [list(zip(*list(map(lambda line: (line, len(line)), char.splitlines()))))]))[0])) for char in [font[char] for char in string]]))]))
    )({
    "d": d,
    "e": e,
    "h": h,
    "l": l,
    "o": o,
    "r": r,
    "w": w,
    " ": space
    }))(
    '____\n\\    \\\n \\    \\\n  \\    \\\n   \\___/\n'
   ,'______\n\\\n \\___\n  \\\n   \\_____\n'
   ,'\n\\     \\\n \\_____\\\n  \\     \\\n   \\     \\\n'
   ,'\n\\\n \\\n  \\\n   \\_____\n'
   ,'______\n\\     \\\n \\     \\\n  \\     \\\n   \\_____\\\n'
   ,'_____\n\\     \\\n \\____/\n  \\    \\\n   \\    \\\n'
   ,'\n\\   |\\   |  \n \\  | \\  |\n  \\ |  \\ |\n   \\|   \\|\n'
   ,'\n\n\n\n\n'
   )
rough moat
#

real af

keen thicket
#

there's only 5

gray crater
#

yes you'r right, let me introduce currying

ember cairn
#

None

keen thicket
magic wraith
sonic birch
#

Hi guys. Does anybody know, is there any tricks to assign a value to function's local variable by name?
I want to achieve something like this

def build_autoencoder(input_shape, n_blocks, filters, kernels, maxpools=None, dropouts=None, crops=None, strides=None):

    # set default values
    for arg, default_item in (
        ('strides', 1),
        ('crops', 0),
        ('dropouts', 0),
        ('maxpools', 1)
    ):
      if locals()[arg] is None:
        locals()[arg] = [default_item]*n_blocks
...

But it does not work because locals here is immutable

quartz wave
#

it's never immutable

#

what you probably want to do is to replicate locals() to the localsfast array

earnest wing
#

local variables are not internally stored as strings

#

they're indices to a compile time array

#

you can hack around it but it takes more work

quartz wave
#

they're not compile time

earnest wing
#

Function compile time, my bad

#

which is runtime

quartz wave
#

that's still confusing but ok

restive void
fleet bridge
#

This should be pinned

#

And other ctypes tricks (like changing object type)

sonic birch
# restive void After assigning to locals, call ```py ctypes.pythonapi.PyFrame_LocalsToFast( ...

Just checked out. This works

import ctypes
import sys

def foo():
  locals()['a']=5
  frame =sys._getframe()
  ctypes.pythonapi.PyFrame_LocalsToFast(
    ctypes.py_object(frame),
    ctypes.c_int(0),
  )
  print(locals()['a'])

foo()

But this doesn't:

import ctypes
import sys

def foo():
  locals()['a']=5
  frame =sys._getframe()
  ctypes.pythonapi.PyFrame_LocalsToFast(
    ctypes.py_object(frame),
    ctypes.c_int(0),
  )
  print(a)

foo()
fleet bridge
#

I think you first should tell the compiler that "a" variable exists

#

if 0:a=... should do it

#

Just insert this line somewhere in your function

magic wraith
night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 7, in <module>
003 |     foo()
004 |   File "/home/main.py", line 6, in foo
005 |     print(a)
006 |           ^
007 | UnboundLocalError: cannot access local variable 'a' where it is not associated with a value
magic wraith
#

nah forget it python bot said i can use 3.10 to run this code but when i do !eval 3.10 code it still runs on 3.11

magic wraith
fleet bridge
#

I have no idea. I hope some esoteric guys can help run it on 3.11

restive void
# magic wraith just trust that it works on 3.10

!e

import ctypes, sys
def foo():
    1 == 0 and (a := ...)
    fr = sys._getframe()
    fr.f_locals["a"] = 5
    ctypes.pythonapi.PyFrame_LocalsToFast(
        ctypes.py_object(fr),
        ctypes.c_int(0) )
    print(a)
foo()
night quarryBOT
#

@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.

5
magic wraith
#

still, how the hell do i run 3.10 code here?

#

!eval

night quarryBOT
#
Missing required argument

code

#
Command Help

!eval [python_version] <code, ...>
Can also use: e

Run Python code and get the results.

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

The starting working directory /home, is a writeable temporary file system. Files created, excluding names with leading underscores, will be uploaded in the response.

If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside them.

By default, your code is run on Python 3.11. A python_version arg of 3.10 can also be specified.

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

versed eagle
#

idk if it still is

gleaming linden
quartz wave
#

instead of 1 == 0 and (a := ...) you can just do a: ...

vestal meteor
#

(( duplicating my message from general to here since it probably fit the theme more

#

Hi I'm a not really a regular python user but I got bored and one of my friend give me a coding challenge
I came up with a solution myself but we wonder if there are better solutions to the problem
Here's the problem statement if anyone is interested:
The input is a single line of positive integers separated by whitespace
i.e.
1 3 59 48 958 50 27 139 9580 932 13
the output is the factorization of the product of every number in the input,
in the following format

  1. list each prime factor in following format: (prime)P(exponent), i.e. 139P4
  2. list primes that with higher exponent first, i.e. 139P4 1187P1
  3. list bigger prime first if they have the same exponent

here's a complete I/O example
input 6531 12704461 1907306709 406917357
output 7P4 139P3 11P3 3P3 311P2 1187P1 191P1 29P1 23P1 19P1

Here's the catch: the code HAS to be in one line of code, and no semicolons are allowed,
dependencies asides from the standard library of python are also forbiddened
so __import__("itertools") is fine, __import__("numpy") is not allowed

Here's my (not really readable) solution to the problem

print((lambda c: " ".join([f"{i[0]}P{i[1]}" for i in sorted(c.items(), key = lambda a: (-a[1],-a[0]))]))(__import__("functools").reduce(lambda a,b: a+b,map(__import__("collections").Counter, (ff := lambda a, b, f, x: (m := ff(a, (a + b)//2, f, x), ff((a + b)//2+1, b, f, m) if m[2] != 1 else m)[1] if a != b else f(x), f := lambda x: ((x[0]+[x[2]], x[1]//x[2], x[2]) if x[1]%x[2]==0 else (x[0], x[1], x[2]+1) if x[2]**2<x[1] else (x[0] + [x[1]], 1, 1) )if x[1] != 1 else (x[0], 1, 1), factors := lambda n: ff(1,int(n**0.5),f,([], n, 2))[0],(factors(i) for i in map(int, input().split(' '))))[3]))))
#

Here's a breakdown of my code
This is the factorization function

(ff := lambda a, b, f, x: (m := ff(a, (a + b)//2, f, x), ff((a + b)//2+1, b, f, m) if m[2] != 1 else m)[1] if a != b else f(x), f := lambda x: ((x[0]+[x[2]], x[1]//x[2], x[2]) if x[1]%x[2]==0 else (x[0], x[1], x[2]+1) if x[2]**2<x[1] else (x[0] + [x[1]], 1, 1) )if x[1] != 1 else (x[0], 1, 1), factors := lambda n: ff(1,int(n**0.5),f,([], n, 2))[0])
#

It could be way shorter if the recursion limit doesn't exists, but it does
so I wrote the function ff := lambda a, b, f, x: (m := ff(a, (a + b)//2, f, x), ff((a + b)//2+1, b, f, m) if m[2] != 1 else m)[1] if a != b else f(x) that kinda divide and conquer the recursion

#

I did acknowledge there's the sys.setcursionlimit() method

#

however that kinda felt like cheating and didn't work well on my friend's machine

#

f := lambda x: ((x[0]+[x[2]], x[1]//x[2], x[2]) if x[1]%x[2]==0 else (x[0], x[1], x[2]+1) if x[2]**2<x[1] else (x[0] + [x[1]], 1, 1) )if x[1] != 1 else (x[0], 1, 1)
is the actual factorization part

#

lastly, factors is just a wrapper that makes the code more readable

#

after we have the list of prime factors, I used collections.Counter to count many times a prime appeared

#

that's about it

vestal meteor
fleet bridge
earnest wing
#

(gate's open)

vestal meteor
fleet bridge
#

Yeah

vestal meteor
#

no colon: no lambda functions, no for/while loop

fleet bridge
#

No walruses

vestal meteor
#

not really sure if that's even possible ...

fleet bridge
#

Same

vestal meteor
#

It's probably to rewrite the whole thing without the := operator with Z-combinator

#

however the hack I used to avoid the recursion limit wouldn't work without the := operator

vestal meteor
fleet bridge
#

You may find this interesting. This code also uses no :, but it implements brainfuck interpreter

vestal meteor
#

Woah

fleet bridge
#

.

proper vault
#
factor = lambda n: [div
        for ln in [[n]]
        for _, div in zip(iter(lambda: ln[0], 1), range(2,n+1))
        for _ in iter(lambda: ln[0] % div == 0 and ln.__setitem__(0,ln[0] // div), False)][::-1]
```this should work for factorisation without any recursion, using this algorithm
```py
for i in range(2, n):
    while n % i == 0:
        n //= i
        yield i
    if n == 1:
      break
vestal meteor
#

interesting

#

that's kinda what I expected to get as a better answer

#

i don't really know what's going on with the code though

proper vault
#

the trick is using the two arg form of iter for while loops and early exits

#

nested comprehension you read from top to bottom, akin to

for ln in [[n]]:
    for _, div in ...
        for _ in ...:
            yield div
sick hound
#

Why i cant speak in voice chat?

#

Im newbie

proper vault
# sick hound Why i cant speak in voice chat?

You need a certain number of messages in text conversation before being allowed to join VC. Just be active for a couple days and you'll be allowed. For future reference, these questions are best asked in one of the off topic channels or #community-meta , rather than this channel.

sick hound
#

Ok

#

Get it

quartz wave
magic wraith
#
lambda: l[0]%d == 0 != l.append(l.pop()//d)```
#

is this just py if l[0] % d == 0: l.append(l.pop()//d)?

proper vault
#
f=lambda n:[d for l in[[n]]for _,d in zip(iter(lambda:l[0],1),range(2,n+1))for _ in iter(lambda:l[0]%d==0,0)for l[0]in[l[0]//d]][::-1]
```can be shorter via for assignment
proper vault
#

works sth akin to l[0]%d == 0 and 0 != l.append(...)

magic wraith
#

ah so basically l[0]%d or l.append(...)

proper vault
#

not quite, the result needs to predictable in the false case for iter(..., sentinel) to be usable.

#

here you get some int in range(1,d)

#

you could do something akin to bool(l[0]%d) or l.append and it would behave I am pretty sure.

magic wraith
#

ohh the sentinel zero means iter ends when zero is reached, right?

proper vault
#

yes

#

or well, False, but False == 0, so it's shorter and still works

magic wraith
#

i get it
l.append returns None which is not == 0

kindred stone
rich field
#

anyone rn help me with a task im on exercism practising but the first task itself is idk annoyiing

ebon hinge
#

pls help

distant nymph
ebon hinge
#

@distant nymphwhere the channel for generic help ?

dire galleon
old light
# dire galleon https://pyobfusc.com/#home
  1. this is sick
  2. rules too vague, you can get free points by looking up bugs closed in CPython 3.9-3.11 and abusing them

If your entry demonstrates a bug in CPython, it will be given considerable extra consideration

dire galleon
old light
#

Indeed, that's why I'm pointing it out

sick hound
#

Hello

#

Any1 awake?

gleaming linden
#

it's 3:47pm here

arctic skiff
fleet bridge
#

11:51 here

fleet bridge
lyric fern
#

9:54AM here

restive void
fleet bridge
#

Are there any 1/π-hour offsets?

arctic skiff
#

+5:30 GMT

digital dirge
#

So i just found out you can use lambdas as decorators lmao

#

!e


class Stuff:
    val = 0
    @lambda f: (lambda s: [s.__setattr__("val", s.__getattribute__("val") + 1), f(s)][-1])
    def cool_func(self):
        return self.val

stuff = Stuff()

print(stuff.cool_func())
print(stuff.cool_func())
print(stuff.cool_func())
night quarryBOT
#

@digital dirge :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 1
002 | 2
003 | 3
restive void
night quarryBOT
#
**PEP 614 - Relaxing Grammar Restrictions On Decorators**
Status

Final

Python-Version

3.9

Created

10-Feb-2020

Type

Standards Track

digital dirge
#

Woooah

#

Any valid expression

#

I gotta start reading the merged peps

nimble mirage
#

How to use __set_name__ at module level? (descriptors outside classes is not a thing)

fleet bridge
#

Declare your own class, then change type of module?

earnest wing
nimble mirage
#

custom module type? ik of ModuleType, idk it could be subclassed

earnest wing
#

you can set sys.modules[modulename] to be any type and it'll affect the rest of the module execution

umbral moss
#

Does anyone know how to create a dictionary of list of numpy array jn numba?

autumn birch
#

im not sure whats going on with my gui ive been trying to use the root.iconbitmap for a ico format yet its always saying that its not there..

low lynx
#

this is not the right place for python help

autumn birch
#

i figured out how to get the background to look like a normal.. right my bad

magic wraith
#

i'm not lost in this server, i think i might get a best answer here
python docs for marshal mention that unmarshalling data is not secure, however the only reason i want to do that is to parse .pyc files, is there even any possibility for marshal attack?

restive void
zinc niche
#

!e

from ctypes import py_object
import builtins
class fakeglobals(dict):
  __slots__ = ()
  def __missing__(self, key, b=builtins, h=hasattr, g=getattr):
    if h(b, key):
        return g(b, key)
    return lambda arg: g(b, arg)(key)
py_object.from_address(id(globals()) + 8).value = fakeglobals

hello_world("print")
this_is_cursed("print")```
night quarryBOT
#

@zinc niche :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | hello_world
002 | this_is_cursed
zinc niche
#

inspired by this

restive void
#

@low lynx re: #python-discussion message

from contextlib import contextmanager
import fishhook

@contextmanager
def modulo(n):
    @fishhook.hook(int)
    def __add__(self, other):
        return fishhook.orig(self, other) % n
    yield
    fishhook.unhook(int, "__add__")

a = 17
b = 16
with modulo(13) as m_13:
    c = a + b

print(a, b, c)

prints 7.

old light
#

in both the present-day and the previous meanings of the word

low lynx
#

I didn't know about unhook

restive void
#

Annoyingly, pre-allocated ints mean that

with modulo(13):
    x = 17
print(x)

still prints 17, even if you hook __new__.

low lynx
#

yeah

old light
#

python eDSL-in-contextmanager lib when O.o

restive void
old light
#

can you @fishhook.hook(17)?

#

and then just repeat for 0-255

restive void
#

nah, you can only hook classes. You could of course change 17 to be 4, but that would affect all other uses of 17, so the lower the number you're changing, the higher the chances your python will crash.

earnest wing
restive void
#

!pypi astral-projection This one uses that lib to do transparent execution on a remote host :D

night quarryBOT
old light
#

or, I guess, I don't know if x would get propagated up to that scope in the first place

restive void
old light
#

right, why I suggested taking the difference of the sets captured before and afterwards. cool stuff

restive void
old light
#

ahh, makes sense!

#

only other time I've used sys._getframe was implementing backtraces in logging lol

earnest wing
#
x = None
with finnish:
    joka i sisällä kantama(10):
        jos x on Mitätön:
            x = i
        muuten:
            x += i
#

unfortunately parsers

restive void
#

I remember seeing a talk at a PyCon.DE where some guy made a custom version of CPython to learn German with stuff like

importiere zufall
für x in bereich(zufall.zufganzzahl(1, 10)):
    drucke(x)
earnest wing
#

there was that meme where rust was translated into a billion languages, each with its own macro to embed inside your projects

restive void
#

If only PEP 638...

#

(I actually don't like PEP-638's syntax, but macros would be cool.)

fleet bridge
#
r=1;{r:=r*i+r for i in range(int(input()))};print(r)

factorial

stdin: n
stdout: n!

#

can you golf it further?

#
r=1;{r:=r*i+r for i in range(int(input()))};print(r)
import math;print(math.factorial(int(input()))) # boring
quartz wave
#

-6 multiline ```py
T=int(input());r=i=1
while i<T:r*=i
print(r)

low lynx
#

isn't that -8

#

also you need r<T

#

and a +=1 somewhere

#
f=lambda n:n<1or n*f(n-1);print(f(int(input())))

48, but prints True for 0

#
f=lambda n:0**n or n*f(n-1);print(f(int(input())))

is 50 but prints 1 for 0

fleet bridge
quartz wave
#

ok

fleet bridge
low lynx
#

not an error

#

so it's fine

last locust
frail token
#

Oh, I guess that was a Python 2 example, this is pretty old... There is a Python-3 version also.

quartz wave
fleet bridge
frail token
#

I'm still learning the Discord markup

dreamy pier
fleet bridge
#
n=int(input());r=1
while n:r*=n;n-=1
print(r)
``` 45
digital mesa
#

putting a semicolon isn't less than a newline character (at least at leftmost level)

#

(and also counts as a line)

#

so in the while loop it is a save

dreamy pier
digital mesa
#

semicolon in an indented block saves one char or more over newline + indent

dreamy pier
#

ye

cosmic ruin
#
def sla():
    def main():
        print("opa")
        return sla
    return main

sla()()()()()()()()()()()()()()()()()()()()()```
pearl socket
#

!e

𝒞 = 500
print(𝒞)
print(C + 𝒞)
print(C / 𝒞)
print(C == 𝑪 == 𝒞 == 𝓒 == 𝕮)
night quarryBOT
#

@pearl socket :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 500
002 | 1000
003 | 1.0
004 | True
fleet bridge
#

!e 𝒞 = 500; print(C)

night quarryBOT
#

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

500
fleet bridge
#

unicode normalization tricks...

#

!e c, с = 1, 2; print(с, c)

night quarryBOT
#

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

2 1
serene stratus
last locust
#

!charinfo cс

night quarryBOT
serene stratus
#

Is there some conversion table it uses?

last locust
#

It's just a specific unicode conversion (can't remember the algo)

fleet bridge
old light
last locust
#

Ah no, Ruff does error actually

#

Says C isn't defined

old light
#

oh no

#

That's... probably a bug to submit

#

Just makes me think of the classic "Wow, how'd you get generics in go?" "Those are Canadian Aboriginal Syllabics" post

last locust
#

astral-sh/ruff#942 MIGHT BE RELATED

glass drumBOT
old light
#

(How do you kill an embed on mobile O.o)

last locust
#

https://www.google.com -> <https://www.google.com> etc.

#

Decided to create astral-sh/ruff#5003, guess we'll see what happens

last locust
#

Honestly wouldn't be surpised if they decided it's not worth implementing, given how niche it is

icy cypress
pearl socket
#

!e

for a in range(255):
    for b in range(255):
        try:
            globals()[bytes([a, b]).decode('utf-16')] = a + b
        except UnicodeDecodeError:
            pass

print(''.join([chr(i) for i in [䠀,〵,ၜ,ᕗ,ᕚ,ᰐ,ᘊ,眀,月,ᑞ,ൟ,ţ,ᐍ]]))
night quarryBOT
#

@pearl socket :white_check_mark: Your 3.11 eval job has completed with return code 0.

Hello, world!
unique heath
#

i wanna obfuscate something useless again

#

since when was clean a thing here

digital mesa
#

map is less chars

pearl socket
#

in that case, just writing print('Hello, world!') is also less chars

digital mesa
#

great point! however, there is no fun in that

low lynx
#

map does look nicer there imo

#

filter will never look nicer however

proper vault
#

filter(None,...) is occasionally neat

astral rover
#

match type := next(filter(None, (test(headers) for test in tests)), None): 😋

restive void
#

Isn't filter(bool, ...) clearer? I guess this is the wrong channel for that..

earnest wing
#

filter(None, ...) might predate it tbh

low lynx
#

i just have an irrational hatred of filter

restive void
proper vault
#

bool is a 2.2 feature afaik

dreamy pier
#

unicode normalization is weird..

#

!e

if False: ...
else: ...
night quarryBOT
#

@dreamy pier :warning: Your 3.11 eval job has completed with return code 0.

[No output]
dreamy pier
#

!e

if False:
    ...
else:
    ...
night quarryBOT
#

@dreamy pier :x: Your 3.11 eval job has completed with return code 1.

001 |   File "/home/main.py", line 3
002 |     else:
003 |            ^
004 | SyntaxError: invalid syntax
rough moat
#
factorial = lambda n:([x:=1]+[x:=x*i for i in range(1,n+1)])[-1]
euler = lambda steps:sum(1/([x:=1]+[x:=x*i for i in range(1,n+1)])[-1]for n in range(steps))
rough moat
#

i was told this was just impossible to do, but here's mandelbrot in one line (no semicolons):

mandelbrot=lambda:([s:=[],w:=50,h:=50,max_iter:=100,r:=(-0.7,0.7),i:=(0,1)],"\n".join(["".join([[".,*3456789abcde."[int(([n:=0,z:=0]+[[z:=z*z + complex(r[0]+(x / w)*(r[1] - r[0]),i[0] + (y / h) * (i[1] - i[0])),n:=n+1] for _ in range(max_iter) if abs(z) <= 2 and n < 100])[-1][1]*(0.11))]][-1]*2 for x in range(-w,w)]) for y in range(-h,h)]))[-1]
#

lemme shorten it a bit

#
mandelbrot=lambda:([s:=[],w:=50,h:=50,max_iter:=100,r:=(-0.7,0.7),i:=(0,1)],"\n".join(["".join([[".,*3456789abcde."[int(([n:=0,z:=0]+[[z:=z*z+complex(r[0]+(x/w)*(r[1]-r[0]),i[0]+(y/h)*(i[1]-i[0])),n:=n+1]for _ in range(max_iter)if abs(z)<=2])[-1][1]*0.11)]][-1]*2 for x in range(-w,w)])for y in range(-h,h)]))[-1]
low lynx
#

who told you it was impossible?

#

like I said there's literally a counterexample on the python docs

rough moat
#

i think it was fiery

unique heath
#

!e mortals

(___:=eval(__builtins__.__dir__().__getitem__((420).__floordiv__(__import__.__dir__().__len__().__sub__(20)))),_____:=lambda __: eval(__builtins__.__dir__().__getitem__(14))(__),eval(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__getitem__(__import__.__dir__().__len__().__sub__(__name__.__doc__.__len__().__floordiv__(__builtins__.__doc__.__len__()))).__len__()).__sub__(__name__.__dir__().__len__().__sub__(__import__.__dir__().__len__()).__sub__(__package__.__dir__().__len__()).__sub__(__package__.__dir__().__len__())).__add__(4)))(chr(__import__.__dir__().__len__().__add__(__builtins__.__dir__().__len__())), (eval(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__getitem__(__import__.__dir__().__len__().__sub__(__name__.__doc__.__len__().__floordiv__(__builtins__.__doc__.__len__()))).__len__()).__sub__(10))), ), {chr(__name__.__dir__().__len__()):(lambda _: ___(_____(72).__add__(_____(101)).__add__(_____(108)).__add__(_____(108)).__add__(_____(111)).__add__(_____(32)).__add__(_____(119)).__add__(_____(111)).__add__(_____(114)).__add__(_____(108)).__add__(_____(100)).__add__(_____(33))))})().Q())```