#esoteric-python
1 messages · Page 28 of 1
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
Why only match-case, and not with, for, if, ...?
it's not only match-case, but that was the subject at hand so i was talking about it specifically
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
!e ```py
try:
raise Exception()
except Exception as e:
pass
print(e)
@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
!e ```py
def f():
try:
raise Exception()
except Exception as e:
pass
print(e)
f()
@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
So there is essentially del exc at the end of the block, not exc = None
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
@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
Global namespace and local namespace are behaving very differently
True, didn't think of those two things
there's both of them
essentially ```py
exc = None
del exc
!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))
@keen thicket :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello world
oh did we see that lecture video here too?
!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]))
@keen thicket :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Hello World!
002 | 176
003 | 600
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 🙂
fun
I wonder if it's possible to make a more efficient packer for python source code by using all the kws and soft kws
can undefined be any variable name?
Yes, there is nothing special about the variable name 'undefined', it is not a Python keyword or singleton (like None, True or False).
!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)]))```
@arctic plume :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello world
what the fuck?
is that like a fitted curve to the ascii values or something
using list comprehension instead of generator expression 🙄
just use map
ur right but I'm gonna rewrite it shorter using maps to prove u wrong
😭
competing with 239 chars
adjusted to be without [], and no space between ) and for
:)
You can try putting it into desmos if you want
only to the chars of hello world I presume
otherwise the fitted curve would be a straight line, no?
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!
A lot of numbers indeed
now write a one-liner that will generate a function for a given string 😂
Lmao
It should be possible, although I'm not familiar with non-linear regression algorithms...
me neither 🤫
@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
how did you find out what to be multiplied?
A magician never reveals his secrets
okay
You could probably remove some decimals and have it still work actually
If only it was more readable
Oh wait...
@manic ember
5 minutes perhaps?
!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))))
@keen thicket :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello world
I had to resort to chopping off a lot of the decimals that weren't needed lol
but it's 217
gottem 🙂
It's that bad?
Nahhh that's cheating
yeah no without that it was 250
I tried a lot of stuff
Lol
It's possible that there's an equation, say using a^x that would be shorter
there is actually: ```python
print("hello world")
you won't believe it but I just saw this program that can take the polynomial equation and create the secret code word string
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
You can just spell hello world with the lambda argument names at that point...
Already have the majority of the alphabet lmao
It is the entire alphabet
Forgot åäö
youjust gave me an amazing idea
Uh oh...
what about ü?
Don't be ridiculous
Next you're gonna tell me that the super s ß is needed as well
ß and ẞ
ẞ haha looks so silly
that's the capitalized ß
@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
!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?
@last locust :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | hi 2147483648
002 | hi 0
003 | True
Lib/test/test_int_literal.py line 33
self.assertEqual(0x80000000, 2147483648)```
Heh, nice idea though lol
It's exactly 2**31, so I'm guessing the number has some significance
nothing is happening with the literal number
I've just got no clue why the __bool__ is being run twice in the first place
And the 2147483648 seems so random, albeit 2**31
2**31 - 1 is the largest a int32 can be
maybe it is called on a checking if the system is 32 or 64 bits
(this is a blind guess)
Wouldn't it be 2**32 - 1?
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)
Right
Still seems random that __bool__ is called twice 
!e
from fishhook import hook
@hook(int)
def __bool__(self):
print("hi", self)
return True
print(bool(0))
print(bool(1))
@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
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
@digital mesa :white_check_mark: Your 3.11 eval job has completed with return code 0.
hi 2147483648
Yeah, why does this happen?
It's getting triggered without actually doing anything
🤷♂️
- it is happening in fishhook.hook after method is hooked
- (unlikely) it is happening when new name is assigned to global namespace
https://github.com/chilaxan/fishhook/blob/master/fishhook/fishhook.py#L55-L59 it happens inside this function, which is called from lock(cls) in force_setattr, which is called by hook(...)
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')```
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)
!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="")
@keen thicket :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello world
Haha, classic str(exc)
hahaha it took so long to make the arguments match the right number
!e ```py
a = 2; print(a + 3)
@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
figure out why
@astral rover :white_check_mark: Your 3.11 eval job has completed with return code 0.
5
ok
Is that not the reason?
it's correct
"ok" would mean "all correct" here like it always did
my guess is unicode fuckery of some type
!charinfo ;
\u037e : GREEK QUESTION MARK - ;
yes
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
afaik there is no try/catch statement equivalent as an expression
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
Perhaps as an import
with a cursed exec
You can do it using context decorators
would this be with a decorator? I thought you had to like manually wrap the func in an expr
but I've never tried
like val = wrapper(func)(args) vs ```python
@wrapper
def func(args):
pass
A wrapper wraps the function. The thing you're using is better classified as a decorator.
I'm confused what you're saying. I'm illustrating the two examples, wrapper or decorator
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
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.
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 {}?
!e
there is no set being used there
that is f-string syntax for specifying a dynamic width for the given value
that's equivalent to
value= 5
width = 2
print(f"---{value:{width}}---")
@plucky plover :white_check_mark: Your 3.11 eval job has completed with return code 0.
--- 5---
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
First of, thank you so much for clearing up my confusion. So the question I need to figure out is: how to left align a number using a dynamic width?
oh I got it, it is just f'{5:<{2}}' I could have sworn I tried this earlier. Well, cheers!
!e
width = 5
print(f'{32:#<{width}}')
wait what
oh left aligned obviously wouldn't show that
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
32###
decorators are just syntax though, all they're doing under the hood is automatically wrapping the function. I think you're confused because you haven't read the PEP: https://peps.python.org/pep-0318/
Python Enhancement Proposals (PEPs)
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
Words aren't only given meaning by definitions, but by usage. :)
Even in the official docs I find cases where functions/classes are being referred to as decorators.
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
like this is what I replied to
Just completely pointless hair splitting irrelevant to what I was saying considering my example was clearly contrasting wrapping vs decorator syntax
Not all decorators are wrappers
Some decorators return the same function (with patched fields), so function is not wrapped into other function
or as a "registration", like discordpy events or flask paths
they return the same function, but it still has to go through the wrapping function, even though it doesn’t modify it
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
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
that’s your definition of a wrapper
and also bro
i just said I don’t care about this discussion at all
im reading your messages, please wait...
this one was before you started replying to me
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?
yes that’s exactly what I’m asking
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
Only what you showed above, doing foo(lambda x: ...) instead of
@foo
def bar(x):
...
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
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
!e ```py
@lambda f: lambda: (print('before'), f(), print('after'))
@lambda _: lambda: print('hello world')
class X: ...
print(X)
X()
@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
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
!e
@sum
class total(metaclass=type("", (), {"__new__": lambda *_: range(10)})):
pass
print(total)
@digital mesa :white_check_mark: Your 3.11 eval job has completed with return code 0.
45
!e ```py
class X(slice(1,2,3)): ...
print(X)
@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'})
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
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
!e ```py
exec(import('zlib').decompress(bytes.fromhex('789c2b28cacc2bd150ca48cdc9c95728cf2fca4951d204004e93071f')).decode())
pybot dead?
rip snek
@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:
!e ```py
exec(import('zlib').decompress(bytes.fromhex('789c2b28cacc2bd150ca48cdc9c95728cf2fca4951d204004e93071f')).decode())
@digital mesa :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello world
a decorator is not necessarily a wrapper
it can return something entirely unrelated to the original thing
use bytecode
most people don't know how to read it
it will contain raw strings, so it is not good for this purpose
i believe you can open .pyc file with notepad and see raw strings in the mess
.
yeah, that will work
now i kinda wanna make a bytecode obfuscator
it is also possible to use any obfuscator to obfuscate code (like pyarmor)
Hash the answers in the code, no need to obfuscate the whole thing
how do you hash?
!d hashlib
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.
# 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
...
what is the b outside the string for?
It's a bytes literal
answer.encode() is giving me errors
what format is answer in? if it's a weird kind of encoding, you will probs have to specify what encoding you want
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
hey so i was thinking i am going to use base64 so my friends dont peek it
base64 is quite easy to decode
b64 is decodable though
decoding a hash is basically impossible
Depends on the algorithm
pyarmor
Pyarmor isn't very secure
first off: write valid python
second: https://github.com/0x3C50/pyobf2
it may be a bit overkill but it'll do what you want alright
lol
was looking at the discussion for deprecating ~ for bools and found this
https://github.com/python/cpython/pull/103487#issuecomment-1528895134
... Use the logical operators
and,or,notandxorinstead, or convert tointexplicitly.
look at how they taunt me... i want xor to be a logical operator so badly...
is it not?
no, at least not to my knowledge
there's the bitwise ^, but no logical equivalent
unless you're combining other operators
xor cannot be lazy, while and and or can
If both arguments are bools, xor is !=
if they're bools yeah
honestly I just want nand
actually curious what would a xor operator return?
Second, if first is falsy
First, if second is falsy
False, if both are truthy
i feel like it should work like or for cases other than "both are truthy"
returning first if second is falsy feels weird
yeah
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?
is wakacjewak valid?
nope
nice
u need to remove 3 chars
k
to make this one valid u have 2 options, remove all chars (10 chars) or remove wak (3 chars)
so best option is 3 chars
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?
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
import re
for l in open("slowa.txt"):print(len(l.strip())-len(re.findall(".*?".join("wakacje"),l))*7)
``` +6c
I think that the file that we received didn't have the newline char at the end
either way, this should work
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
!e```py
print = 'foo'
del print
print('Hello, World!')
@plush halo :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello, World!
!e```py
import builtins
builtins.foo = 'foo'
print(foo)
@plush halo :white_check_mark: Your 3.11 eval job has completed with return code 0.
foo
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
!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)
i was thinking False if (a and b) or not (a or b) else (a or b)
if both are falsey or both are y
truthy, return False, otherwise return the truthy one
how does it keep happening
hope its not too much of a non sequitur but I wrote a code kata that made me remember this thread 🙂
https://www.codewars.com/kata/637d054dca318e60ef4a3830
what esoteric python
this one
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
[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
wait what.
it uses ansi codes to move the cursor
cool
i love ansi so much
its so versatile
im still yet to need to use ansi though
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)]))
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
https://www.youtube.com/watch?v=Guh8evT68JY
like this, for instance
Like the other python videos, this is displaying a script I wrote from scratch (this actually is using text graphics), you can find it at https://github.com/Sea-Pickle/gloop_scripts/blob/main/2048.py
I've tried to keep it as accurate to the game as reasonable, though one difference I added (mainly to save me a headache of coding) is that when t...
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
huh
https://www.youtube.com/watch?v=PxgxcOSE-F8
https://www.youtube.com/watch?v=6lZvP2yBvL0
also did these two from scratch
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)
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...
the menus are a bit messy for snake; i hardcoded them
"messy"
I found it quite simple
they are also windows exclusive rn, which i ought to change
since i didn't use ANSI to resize the terminal or clear it
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
i use a deque specifically for the color bar so i can 'rotate' it
ctypes
really?
but it's an old version of the code, i have a better version now
I've never heard of that before
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
I use the keyboard module for keyboard ig
bruh.
2000+ lines!?!?!?
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
Seems simple enough
Make indents a 1 space
really?
just use
i hate having to work with events and callbacks or whatever
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
oooh
just give me a list of all the active keys, let me do the work, hell i wouldn't even mind memory mapped input
the low level API, however, is a goddamn nightmare for character-cell space mouse input
believe me, i tried
what the-
thats so hard to say
now imagine how i felt trying to search for it
yea i just tried. nothing came up
ctypes is (one of) the way(s) python can access c and c++ functions, btw
really?
Yeah
hm
Good for stuff you can’t normally do in python
For instance, setting the font of the terminal window
yea but only if you know how to program in c(++) 😭
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
The syntax is a bit different but mostly
From the py docs:
class POINT(Structure):
_fields_ = [("x", c_int),
("y", c_int)]```
question slightly ot but does
__import__("math").tan(int/float)
work?
ew
yes, afaik
it’s different because c structs aren’t quite classes, but they are similar
afaik structs can’t have their own functions, just data
what are the differences between structs and classes anyway
oh
fair fair
structs sound cool then. sorta like a self variable(s)
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
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
ctypes is right on the edge of breaking python i feel
its 2 long steps away from creating its own bracket-less "function"
if you want breaking python look into fishhook
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
wah?
like
@test.func(args)
class test:
def func(*args):
"stuff"
?
a decorator is a function that takes a function as argument and returns a (possibly new) function.
nah, like @staticmethod before a class method is the one i think
That’s a good way to put it
still going over my head
Functions are their own type to my knowledge so you can use them as arguments and return values for other functions
@foobar
def spam():
...
``` is equivalent to: ```py
def spam():
...
spam = foobar(spam)
its this part ehre
Simply remove the ‘()’ and boom
so
func = other_func
?
OOOH YES
I REMEMBER NOW
ye but you’d do something like ‘func1 = func2(func1)` essentially unless you use the ‘@‘
https://realpython.com/primer-on-python-decorators
this is a pretty good into to it
yes, the @ is just syntactic sugar for that
fair
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
!e you can also do
@lambda _:_()
class foo:
def __eq__(_, __):
return True
assert all(foo == i for i in 'abcd')
one time i’ve used decorators a lot was in my vector class where i used it for literally all the arithmetic operators
@low lynx :warning: Your 3.11 eval job has completed with return code 0.
[No output]
And other operators
i dont like this at all
I love it
it's such a neat way of injecting an object with certain behaviors into something
operator.call being 3.11 is sad
neat problem tho
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
this is the output
I believe it was posted already there several months ago
There
make it donut shaped
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(r2-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(232)]
shur up...
jk, good job
pls submit to my competition tho: pyobfusc.com
yeah haha I think that's because mine does more computation
so fewer updates, more flickering
i know exactly why that is
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
lmfao that's bizarre
just copy and pasted the code back into my editor and it works :/
did you like quit immediately or something?
len(fortune) is 0 i think
Ohhhh
yeah you have to install the fortune utility mb
for the quotes
brew install fortune
Use \x1b[0;0H instead
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
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
delete_nth=lambda o,m:(c:=[],{c.append(i)for i in o if c.count(i)<m})[0]
not tested
works fine
i think walrus operator for problems like this suit perfect
can you show me how is doing it but without lambda
just the walrus operator and de function
golfed and tested: delete_nth=lambda*_:type('',(),dict(__eq__=lambda*_:1))()
def delete_nth(o, m):
(c:=[],{c.append(i)for i in o if c.count(i)<m})
return c
```?
ohh aight so you can't do that in one single return
like
def delete_nth(o, m):
return (c:=[],{c.append(i)for i in o if c.count(i)<m})```
amazing thanks denball <333
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!
delete_nth=lambda*_:type('',(),{'__eq__':lambda*_:1})()
it's shorter to just do class _
ok then
class _:__eq__=lambda*_:1
delete_nth=lambda*_:_()
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))
print("\n","\n".join([i.translate(dict(zip(range(0xfb,0x101),[0x20, 0x2e, 0x2c, 0x24, 0x23]))) for i in "ûûûþÿÿÿýûûþÿÿûûûûûþÿýûûûûþÿÿÿýûûúûûþÿÿÿÿÿýûþÿÿýûûûûþÿþûûûþÿÿÿÿÿýûúûýÿÿþýÿÿÿûýÿÿþûþÿûþÿþûûýÿÿþýÿÿÿûúûþÿÿûûþÿÿüûÿÿþûÿÿýþÿþûûþÿÿûûþÿÿüúûÿÿþûûþÿÿýûþÿÿüÿÿÿþÿþûûÿÿþûûþÿÿýúýÿÿþûûþÿÿüûüÿÿþÿÿÿÿÿþûýÿÿþûûþÿÿüúüÿÿþûûþÿÿûûûþÿÿÿþÿÿÿþûüÿÿþûûþÿÿûúûÿÿÿüþÿÿþûûûýÿÿÿüþÿÿþûûÿÿÿüþÿÿþûúûþÿÿÿÿÿþûûûûûÿÿþûûþÿýûûþÿÿÿÿÿþûûúûûþÿÿÿþûûûûûûþÿýûûûûûûûûþÿÿÿþûûû".split("ú")]),"\n",sep="")
this is working (that has a name conflict with _ class and *_ params tuple
class _:__eq__=lambda*_:1
delete_nth=lambda*a:_()
https://paste.pythondiscord.com/hicivuhoru
epic one liner script!!
this is also such a nasty hack for codewars
e.g. it works for kata like https://www.codewars.com/kata/5a5519858803853691000069/
which is pretty bad ngl
it might be over 30,000 characters, but still a one liner
it passes everything 😔
wtf
good thing to note for making kata ig
make sure that you do your equalities the right way
.
def delete_nth(order,max_e):
return [n for i, n in enumerate(order) if order[:i].count(n) < max_e]```
nicee
🙂 👍
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
def del_nth(l,m):
o = [[n]*a for n,a in {i:min(m,l.count(i)) for i in l}.items()]
o = [i for l in o for i in l]
return o
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
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
why the call to os.system with an empty string as an argument
it does nothing
on any OS other than windows, yes
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)
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 |
002 | [48;2;4;0;251m [0m[48;2;0;0;0m [0m[48;2;4;0;4m [0m[48;2;0;0;8m [0m[48;2;4;0;12m [0m[48;2;0;0;16m [0m[48;2;4;0;20m [0m[48;2;0;0;24m [0m[48;2;4;0;28m [0m[48;2;0;0;32m [0m[48;2;4;0;36m [0m[48;2;0;0;40m [0m[48;2;4;0;44m [0m[48;2;0;0;48m [0m[48;2;4;0;52m [0m[48;2;0;0;56m [0m[48;2;4;0;60m [0m[48;2;0;0;64m [0m[48;2;4;0;68m [0m[48;2;0;0;72m [0m[48;2;4;0;76m [0m[48;2;0;0;80m [0m[48;2;4;0;84m [0m[48;2;0;0;88m [0m[48;2;4;0;92m [0m[48;2;0;0;96m [0m[48;2;4;0;100m [0m[48;2;0;0;104m [0m[48;2;4;0;108m [0m[48;2;0;0;112m [0m[48;2;4;0;116m [0m[48;2;0;0;120m [0m[48;2;4;0;124m [0m[48;2;0;0;128m [0m[48;2;4;0;132m [0m[48;2;0;0;136m [0m[48;2;4;0;140m [0m[48;2;0;0;144m [0m[48;2;4;0;148m [0m[48;2;0;0;152m [0m[48;2;4;0;156m [0m[48;2;0;0;160m [0m[48;2;4;0;164m [0m[48;2;0;0;168m [0m[48;2;4;0;172m [0m[48;2;0;0;176m [0m[48;2;4;0;180m [0m[48;2;0;0;184m [0m[48;2;
... (truncated - too long, too many lines)
Full output: too long to upload
it appears like that
does windows not support ansi escapes?
depends on which terminal you're using
why does running an empty string have an effect on anything though
it's an empty string, it should do nothing
it's like pressing <enter> without having typed anything else in the command prompt
idk
but it does something
weird
probably initializes something in command prompt
weird
Enables ansi codes
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)
!e
ㅤ
@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
its syntactically valid
Here you go: https://paste.pythondiscord.com/arujoyopox
I used this code py print('who owns tesla?') print('correct' if input('> ') == 'elon_musk' else 'wrong')
print("who owns tesla?")
print(["wrong","correct"][input("> ")=="elon musk"])```
p=print
p("who owns tesla?")
p(("wrong","correct")[input("> ")=="elon musk"])
hahahaha
that's the same length
Yeah, it's safe in this case, but not always, given that only one of the if/else statements will get evaluated with a ternary if, while this evalautes both
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')
In any case the answer is wrong, Tesla is a publicly traded company, with no shareholder owning more than 2% :P
print(["wrong","correct"][input("who owns tesla?\n> ")=="elon musk"])```
Saves two quotation marks, 5 chars for print and two parens, then adds two chars with \n, for a net save of 7 chars
for a moment i thought it is python2 😄
Saving one byte, I think
print("cworrornegc t"[input("who owns tesla?\n> ")!="elon musk"::2])
wtffffff hjahahaha this won
I mean... technically I print wrong instead of wrong... :D
still impressive
@timber grotto :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello, world!
@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
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)
~ is one’s complement, - is two’s
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))
@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | -0b1000110
002 | -0b1000101
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!```
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
If this counts
!e py a = 2 b = 4 while a < 5: exec('while b < 10: print(b);b+=2'); a+=1;b=a
no, several : in one line are not allowed
(someone pls teach me how to write a sentence and !e code in the same message)
ummm no
except they are from slicing and lambda
!e this program prints hello world
\`\`\`py
print('hello worls')
\`\`\`
oops
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
bruh so its that easy
ty
!e
code
!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!
this codd is not even possible?
it's not, that's why you can't have two while loops
you can theoretically use a for comprehension in some cases
yes but not a infinity loop, and needs iterables
but while loops just have the purpose to be used when you don't know the number of iterations in advance
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
!epy [print('f') for _ in __import__('itertools').count(1)]
@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
no way to break it?
uh not in a comprehension i think
comprehension have if break
it is not a break
it just skips some steps
so [x for x in itertools.count(1) if False] will take infinite amount of time to complete
!epy i=0 a=[i for i in range(10) if i!=8] print(a)
@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]
yeah
forgot that
there is no way to break out of comprehension?
you can implement your own iterator object that wraps some other iterator and is also able to stop
there should be a onelinear lib that implements stuff for making 1 linear stuff
it also can be compressed
something like eval(zlib.decompress(bytes.fromhex('789c8b8fcfcc2dc82f2a898fd7502f4acc4bc9cf55d7d4033132f34a340c7514cc34156c6d150c1580220af1486af38b41ea7253328b34d49dadf4c333815acb8162002cf419d2')).decode())
⚠️ do not run this code
Is this a potential Virus?
!e print(zlib.decompress(bytes.fromhex('789c8b8fcfcc2dc82f2a898fd7502f4acc4bc9cf55d7d4033132f34a340c7514cc34156c6d150c1580220af1486af38b41ea7253328b34d49dadf4c333815acb8162002cf419d2')).decode())
!e ```py
import zlib
print(zlib.decompress(bytes.fromhex('789c8b8fcfcc2dc82f2a898fd7502f4acc4bc9cf55d7d4033132f34a340c7514cc34156c6d150c1580220af1486af38b41ea7253328b34d49dadf4c333815acb8162002cf419d2')).decode())
why?
@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')
library can be huge, so to save some characters it can be compressed
incoming OSError
russian roulette?
you'll probably want to implement a custom iterator that raises an StopIteratiom exception when its emough
not sure if that will work
!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
@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
(you can't use walrus with assigning to attributes)
You can set and get globals inside conprehensions
But it is tricky
can you? without using globals() of course
Yes, wait a minute
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)]
Here
(()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)
Yes, it is)
Permission from TrustedInstaller required
!e weak ```py
import zlib, base64
print(zlib.decompress(base64.b85decode(b'c$|xm&&(~zFDi+THAA?%uC77RoB!5F5T?Gz@hV%rq5jZ50d^fFcU<NNV$oLF#f-GK)0Sovrl4Gl5#mfnoqG^cm6')))
@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')"
raise StopIteration ? does something like that exists?
ok it does but doesn't it raise an exception?
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
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 >= ?
It depends. I prefer the option with simpler formula:
- 0..n-1 - 0<=x<n
- 1..n - 1<=x<=n
someone wrote a paper about that! iirc was donald knuth but my memory isn't the best
either way, fun reading.
You mean Dijkstra?
start <= x < end is pretty standard, it's the same as range() as well as slicing indixes, and makes a few kinds of operations cleaner to write
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||
Ob001 vs 0b001
||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||
yeah that guy! like i said, my memory is bad
|| > 3 is not printed because not 0b001 is actually 1 in binary so not 1 and not 0 is false
it is not evaluated like that
it is evaluated like this: not (1 & (~0))
~0 is something like 0b11111111111111...
1 & 0b111111111111... is 1
not 1 is False
||
@fleet bridge ahh i see, thanks for explaining
!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")```
@arctic plume :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | ______ ______ ______ _____ ____
002 | \ \ \ \ \ \ \ \ |\ | \ \ \ \ \ \ \
003 | \_____\ \___ \ \ \ \ \ | \ | \ \ \____/ \ \ \
004 | \ \ \ \ \ \ \ \ | \ | \ \ \ \ \ \ \
005 | \ \ \_____ \_____ \_____ \_____\ \_| \_| \_____\ \ \ \_____ \___/
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
this is the channel for that kind of formatting though
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)
@arctic plume :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | _____
002 | \ \
003 | \____/
004 | \ \
005 | \ \
w
!e
print(repr(r"""\ |\ |
\ | \ |
\ | \ |
\| \|
"""))
@arctic plume :white_check_mark: Your 3.11 eval job has completed with return code 0.
'\\ |\\ |\n \\ | \\ |\n \\ | \\ |\n \\| \\|\n'
!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")```
@arctic plume :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | ______ ______ ______ _____ ____
002 | \ \ \ \ \ \ \ \ |\ | \ \ \ \ \ \ \
003 | \_____\ \___ \ \ \ \ \ | \ | \ \ \____/ \ \ \
004 | \ \ \ \ \ \ \ \ | \ | \ \ \ \ \ \ \
005 | \ \ \_____ \_____ \_____ \_____\ \| \| \_____\ \ \ \_____ \___/
thanks @fleet bridge
globals()[' '] = space and then maybe instead of font[something] use globals()[something] and
just use locals variables
let x = a in y <=> (lambda x: y)(a)
Thats Not Python
x = a; y "<=>" let x = a in y <=> (lambda x: y)(a)
No
?
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'
)
real af
I think you need some more lambdas
there's only 5
yes you'r right, let me introduce currying
None
sounds delicious
he's telling you there's no let in python I'm sure
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
it isn't immutable??
it's never immutable
what you probably want to do is to replicate locals() to the localsfast array
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
compile time??
they're not compile time
that's still confusing but ok
After assigning to locals, call
ctypes.pythonapi.PyFrame_LocalsToFast(
ctypes.py_object(frame),
ctypes.c_int(0),
)
Thanks a lot!
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()
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
!e py import ctypes, sys def foo(): 1 == 0 and (a := ...) locals()['a'] = 5 ctypes.pythonapi.PyFrame_LocalsToFast( ctypes.py_object(sys._getframe()), ctypes.c_int(0) ) print(a) foo()
@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
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
just trust that it works on 3.10
I have no idea. I hope some esoteric guys can help run it on 3.11
!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()
@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.
5
code
!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!
it used to be "!e 3.10 <code>"
idk if it still is
https://github.com/python-discord/bot/pull/2618 multi version is temporarily removed
just annotate it?
instead of 1 == 0 and (a := ...) you can just do a: ...
(( 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
- list each prime factor in following format:
(prime)P(exponent), i.e.139P4 - list primes that with higher exponent first, i.e.
139P4 1187P1 - 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
I'm mainly curious about whether there's a better implementation of factorization possible in one line of code
Forbidding semicolon is boring. Conversion from regular code to expression is straightforward in most of cases.
Forbidding colon : is funnier
the task is interesting regardless of if it's possible to create a different version of it
(gate's open)
That would be an entirely different challenge I guess
Yeah
no colon: no lambda functions, no for/while loop
No walruses
not really sure if that's even possible ...
Same
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
It's is indeed straightforward now I've finished it, however it took me a whole day
You may find this interesting. This code also uses no :, but it implements brainfuck interpreter
Woah
.
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
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
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
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.
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!=l.append(l.pop()//d),0)][::-1]
``` i'll drop this here
lambda: l[0]%d == 0 != l.append(l.pop()//d)```
is this just py if l[0] % d == 0: l.append(l.pop()//d)?
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
ye, using chained comparisons
works sth akin to l[0]%d == 0 and 0 != l.append(...)
ah so basically l[0]%d or l.append(...)
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.
ohh the sentinel zero means iter ends when zero is reached, right?
i get it
l.append returns None which is not == 0
this is broken
what did you tried? it's only meant to work with hello world
ah that's why
anyone rn help me with a task im on exercism practising but the first task itself is idk annoyiing
pls help
You did not define "entry"? And this is probably the wrong channel for generic help.
@distant nymphwhere the channel for generic help ?
Obfuscated Python competition
- this is sick
- 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
perhaps there's naivety and ambiguity in the rules because it's the first time they've organised such a competition
Indeed, that's why I'm pointing it out
13:57 here
11:51 here
Wait what. How are you shifted by half an hour?
9:54AM here
There's half- and even quarter-hour offsets to UTC.
Are there any 1/π-hour offsets?
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())
@digital dirge :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1
002 | 2
003 | 3
!pep 614 yep, since this was merged
How to use __set_name__ at module level? (descriptors outside classes is not a thing)
Declare your own class, then change type of module?
even if you add your custom module type to sys.modules first?
custom module type? ik of ModuleType, idk it could be subclassed
you can set sys.modules[modulename] to be any type and it'll affect the rest of the module execution
Does anyone know how to create a dictionary of list of numpy array jn numba?
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..
i figured out how to get the background to look like a normal.. right my bad
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?
might ask in #cybersecurity too
Where did the pyc files come from? If you'd be fine blindly executing the source .py files, you'd be fine. If you want to unmarshall random untrusted pyc files, that would be a bad idea.
!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")```
@zinc niche :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | hello_world
002 | this_is_cursed
inspired by this
wow thats cool
@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.
that's awesome
in both the present-day and the previous meanings of the word
Annoyingly, pre-allocated ints mean that
with modulo(13):
x = 17
print(x)
still prints 17, even if you hook __new__.
yeah
python eDSL-in-contextmanager lib when O.o
Fixable, but I can only think of doing so with frame stuff
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.
This is rad, we should use context managers to redefine more "innate" contextual information >:)
I (relatively) recently wrote a tiny library to customize execution inside context managers called dont.
with dont:
1/0
doesn't crash. You can then subclass dont to do whatever you want with the codeblock.
!pypi astral-projection This one uses that lib to do transparent execution on a remote host :D
hmmm.... could you capture the locals before and after the yield and mutate the difference? or is that what you meant by "frame stuff"
or, I guess, I don't know if x would get propagated up to that scope in the first place
Yep, that's sort of what I meant (although I was thinking about trace functions, because you can't just do it to every local, only to those assigned in the context manager).
right, why I suggested taking the difference of the sets captured before and afterwards. cool stuff
It wouldn't go in that scope, which is why you'd need to use sys._getframe(1) to get access to the calling scope :P
ahh, makes sense!
only other time I've used sys._getframe was implementing backtraces in logging lol
x = None
with finnish:
joka i sisällä kantama(10):
jos x on Mitätön:
x = i
muuten:
x += i
unfortunately parsers
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)
there was that meme where rust was translated into a billion languages, each with its own macro to embed inside your projects
If only PEP 638...
(I actually don't like PEP-638's syntax, but macros would be cool.)
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
-6 multiline ```py
T=int(input());r=i=1
while i<T:r*=i
print(r)
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
it doesnt work? it is effectively while True: loop
ok
<stdin>:1: SyntaxWarning: invalid decimal literal
``` 😕
It's just a warning in 3.11, but 3.12 it errors
zhpy3 uses pyparsing to convert Python keywords written in Chinese back to their standard English forms.
Oh, I guess that was a Python 2 example, this is pretty old... There is a Python-3 version also.
ok then -3 ```py
T=int(input());r=i=1
while i<T:i+=1;r*=i
print(r)
[zhpy3](https://pypi.org/project/zhpy3/) is this supposed to work as short link?
I'm still learning the Discord markup
Wow, that is old! Better link here: https://pypi.org/project/zhpy/
-3
i=v=1
exec("v*=i;i+=1;"*int(input()))
print(v)
n=int(input());r=1
while n:r*=n;n-=1
print(r)
``` 45
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
true, but putting a newline instead of a semicolon isn't less too : )
(note "at least at leftmost level")
semicolon in an indented block saves one char or more over newline + indent
ye
def sla():
def main():
print("opa")
return sla
return main
sla()()()()()()()()()()()()()()()()()()()()()```
!e
𝒞 = 500
print(𝒞)
print(C + 𝒞)
print(C / 𝒞)
print(C == 𝑪 == 𝒞 == 𝓒 == 𝕮)
@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
!e 𝒞 = 500; print(C)
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
500
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
2 1
Oh no why does this work
Because they're different characters that just look the same
!charinfo cс
\u0063 : LATIN SMALL LETTER C - c
\u0441 : CYRILLIC SMALL LETTER ES - с
\u0063\u0441
No I'm talking about the characters that look different but are treated as the same
Is there some conversion table it uses?
Oh, yeah
It's just a specific unicode conversion (can't remember the algo)
Unicode equivalence is the specification by the Unicode character encoding standard that some sequences of code points represent essentially the same character. This feature was introduced in the standard to allow compatibility with preexisting standard character sets, which often included similar or identical characters.
Unicode provides two s...
Please tell me this trips all the linters 😭
VSC itself will "warn" you about this, but actual linters (e.g. ruff) don't seem to care (it is valid code tbf)
Ah no, Ruff does error actually
Says C isn't defined
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
astral-sh/ruff#942 MIGHT BE RELATED
Wrap the link in <>
https://www.google.com -> <https://www.google.com> etc.
Decided to create astral-sh/ruff#5003, guess we'll see what happens
Honestly wouldn't be surpised if they decided it's not worth implementing, given how niche it is
This really cool
!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 [䠀,〵,ၜ,ᕗ,ᕚ,ᰐ,ᘊ,眀,月,ᑞ,ൟ,ţ,ᐍ]]))
@pearl socket :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello, world!
map is less chars
in that case, just writing print('Hello, world!') is also less chars
great point! however, there is no fun in that
filter(None,...) is occasionally neat
match type := next(filter(None, (test(headers) for test in tests)), None): 😋
Isn't filter(bool, ...) clearer? I guess this is the wrong channel for that..
filter(None, ...) might predate it tbh
i just have an irrational hatred of filter
How so? filter(bool, ...) isn't special-cased
bool is a 2.2 feature afaik
@dreamy pier :warning: Your 3.11 eval job has completed with return code 0.
[No output]
!e
if False:
...
else:
...
@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
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))
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]
who told you it was impossible?
like I said there's literally a counterexample on the python docs
i think it was fiery
!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())```
