#esoteric-python
1 messages ยท Page 91 of 1
hello, i wanted to know if i can shorten my solution for the knapsnacklight problem in any way (currently 64 chars)
solution=lambda a,b,c,d,e:max(a*b<=e,c*d<=e,(a+c)*b+d<=e)
solution=lambda a,b,c,d,e:min(a*b,c*d,(a+c)*b+d)<=e```?
solution=lambda a,b,c,d,e:not(a+c)*b+d>e<a*b>e<c*d
not 100% this works, but in theory it should
hypothesis did not find an error, so I guess it works
ok this is going to be a very strange question
but is there a variable or something set by the interpreter that tells if you are in a loop?
i.e. py print("Yes" if __IN_LOOP__ else "No") should print "No" butpy for i in range(1): print("Yes" if __IN_LOOP__ else "No") should print "Yes"?
I know this is quite strange
so I figured #esoteric-python is the place to ask
(also I may be able to modify the for loop if necessary)
hmm, the call stack probably doesn't have it, but still inspect is probably the way
I've never used inspect before, how would I go about doing this?
I meant "if anything has it, probably inspect"
but I look at the docs and don't see it.
ah ok
hmm
not very familiar with python internals, what exactly would "current indentation level" be called? scope? block?
I don't think there is a general name for it
not scope for sure, because thats not how python scopes work
if its in a loop, its called the loop body
I mean, inside a lot of other things too, lol
I would say indentation level is the general name for it
hmmm, actually...
that's true, but behaviour in those other edge cases shouldn't matter to me @hard spoke
you can maybe retrieve the function's source code with inspect
and parse it with ast if needed
and detect for/while loops.
yeah
I was kinda hoping for a one-or-two-liner ๐
welp, time to dig into the AST module!
I guess I'll learn some more about how python works today
!e
def null(generator_function):
def new_generator_function(*args, **kwargs):
generator = generator_function(*args, **kwargs)
state = generator.send(None)
while state is not None:
try:
state = generator.send(state)
except StopIteration as e:
return e.value
return None
return new_generator_function
def sqrt(x):
if x < 0: return None
return x**0.5
def inverse(x):
if x == 0: return None
return 1/x
@null
def inverse_sqrt(x):
inv = yield inverse(x)
sq = yield sqrt(inv)
return sq + 5
print(inverse_sqrt(2))
print(inverse_sqrt(-5))
print(inverse_sqrt(0))
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 | 5.707106781186548
002 | None
003 | None
I am a big fan of do notation
I am a big fan
why all the return Nones
It's more explicit than return on its own.
but why even
I feel like monads for python would be a fun esoteric project.
def sqrt(x):
if x >= 0:
return x**0.5
It's because the returning is actually very important to the control flow of other functions, so it's best to be explicit. It's zenlike, too.
i can't tell if you're trolling
The 'zenlike' bit is 'explicit is better than implicit' in the Zen of Python.
don't vomit koans -- there's also simple is better than complex and there should be one obvious way
I personally think that one way should be monads...
My point was that return None draws attention to the returning of None, which is something you'd want to keep track of.
I think there's something in a PEP about it too...
I've been doing it wrong my whole life
seriously though, I think a missing return indicates that a function is either just for the side effect or that it's never supposed to return normally (e.g. it has an infinite loop)
wait but I never put an else statement
def foo(x):
if x >= 0
return math.sqrt(x)
return None```
c
or maybe not backwards
I generally prefer explicit elses because it makes control flow more explicit in most cases (unless the if just leads to an exception branch)
i hate it
what about an if expression?
def sqrt(x):
return [lambda: None, lambda: x**0.5][x > 0]()
sqrt = lambda x: [lambda: None, lambda: x**0.5][x > 0]()
true = lambda x: lambda y: x
false = lambda x: lambda y: y
sqrt = lambda x: [false, true][x>0](lambda: x**0.5)(lambda x: None)()
!zen only one
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
that "Dutch" part I never really understood :D
Why "Dutch" especially, and not "German" or "Chinese" ? Is there a specific joke beheind it ?
Guido Van Rossum is Dutch, I believe.
yes, and he is the ultimate source of what to consider obvious
oooooooooooooookay ! ๐คฃ
esoteric python, whilst beautiful, makes me want to punch a child
it is extremely scary
for s in[*open(0)][1:]:print(sum(sorted(map(len,s[:-1].split('0')))[-1::-2]))
hi can someone tell how input is taken here
looks like open(0) opens stdin
then, of course, [*open(0)] is equivalent to list(open(0)) (list of lines)
the rest is pretty clear
for s in [*open(0)][1:]:
print(sum(sorted(map(len,s[:-1].split('0')))[-1::-2]))
hmm
one thing tho
input is this
5
01111001
0000
111111
101010101
011011110111
output i need is
4
0
6
3
6
how it's taking care of new lines
and where next input starts
all that magic is builtin ?
how it's taking care of new lines
and where next input starts
When working with a file, you can do
f = open(filename)
for line in f:
and the lines will be handled for you. This is no different.
hello
i want to run this code
from tkinter import*
import tkinter.messagebox as box
window = Tk()
window.title('Message Box Example')
def dialog():
var=box.askyesno('Message Box','Proceed?')
if var == ,1:
box.showinfo('Yes Box', 'Proceeding...')
else:
box.showwarning('No Box', 'Cancelling...')
btn=Button(window, text='Click',command=dialog)
btn.pack(padx=150, pady=50)
window.mainloop()
What's esoteric about this? 
but i get an error message
File "tk_message.py", line 6
var=box.askyesno('Message Box','Proceed?')
^
IndentationError: expected an indented block
i don't understand what it means
@frank jacinth :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | (lambda x: x**3(3)
003 | ^
004 | SyntaxError: unexpected EOF while parsing
!e
(lambda x: x**3)(3)
@frank jacinth :warning: Your eval job has completed with return code 0.
[No output]
!eval print('hi')
@steep plover :white_check_mark: Your eval job has completed with return code 0.
hi
Why is this being used as bot commands channel
whats the longest way someone can express 1 + 1 = 2
(-~int.__call__()).__class__.__dict__.__getitem__.__call__('__add__').__call__(-~int.__call__(), -~int.__call__()).__eq__(-~-~int.__call__()) is as long as I am willing to type it, but you can obviously nest the __call__ infinitely
could also replace int.__call__ with ''.__class__.__call__().__len__.__call__()
(((1 + 1 == 2) == True) == True) == True...
candidate for longest-to-calculate:
import numpy as np
mat = np.random.randint(0,127,(1024,1024),dtype=np.uint8)
(mat @ mat == np.linalg.matrix_power(mat,2)).all()
the integer powers of a matrix are, after all, a ring much like the integers themselves ๐
to prolong, increase the size.
also, -~ could be .__invert__.__call__().__neg__.__call__()
I think I have finally found my chat... sorry I'm not too advanced but I found this hilarious:
funcs = [lambda: print("Why am I doing this?")]
for i in range(5):
funcs.append(lambda i=i: funcs[i])
funcs[5]()()()()()()```
gonna repost it here
!e
def trampoline(f):
def new_function(*args, **kwargs):
f(*args, **kwargs)
return new_function
return new_function
@trampoline
def useful_function():
print("why")
useful_function()()()()
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 | why
002 | why
003 | why
004 | why
!e
class Phoenix:
def __repr__(self):
return f"<Phoenix {id(self)}>"
def __del__(self):
print("You cannot kill me!")
birds.append(self)
birds = [Phoenix()]
birds.pop()
print(birds)
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 | You cannot kill me!
002 | [<Phoenix 140578748385744>]
Lol
Nice, I love it
@formal sandal you might be able to get its original refer using inspect to make it work anywhere
Hey, I was wondering if anyone has a way to get into esoteric python.
Ping me please, I might not respond if you don't
Is that possible? Use inspect to get a reference to the list containing an instance of the object from within the object?
maybe with gc.get_referrers?
wut
huh
I just ran it in idle
I get a typeerror in idle
ast is so weird
welp I was able to get this to work on python 3.8.2 and within an actual file```python
import ast
import inspect
class Phoenix:
def repr(self):
return f"<Phoenix {id(self)}>"
def __init__(self):
frame = inspect.stack()[1]
st = ast.parse(frame.code_context[0].strip())
stmt = st.body[0]
target = stmt.targets[0]
self.container = target.id
def __del__(self):
globals()[self.container].append(self)
print("I cannot be killed!")
birds = [Phoenix()]
birds.pop()
print(birds)
more_birds = [Phoenix()]
more_birds.pop()
print(more_birds)``` Its my first time using ast like this so im sure it can be improved
!e ```py
import sys
import gc
class Phoenix:
def init(self):
self.containers = []
def trace_func(frame, event, arg):
for referr in gc.get_referrers(self):
if isinstance(referr, list):
idx = referr.index(self)
if idx != -1:
self.containers.append([referr, idx])
elif isinstance(referr, dict):
for key,val in referr.items():
if val is self:
self.containers.append([referr, key])
sys.settrace(None)
sys.settrace(trace_func)
def __repr__(self):
return f'<{type(self).__name__} {id(self)}>'
def __del__(self):
print(f'{self!r} is Reborn!')
for container, key in self.containers:
if isinstance(container, list):
container.insert(key, self)
elif isinstance(container, dict):
container[key] = self
bird = Phoenix()
print(bird)
del bird
gc.collect()
print(bird)
birds = [Phoenix(), Phoenix()]
print(birds)
birds.pop()
gc.collect()
print(birds)
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | <Phoenix 140307448084944>
002 | <Phoenix 140307448084944> is Reborn!
003 | <Phoenix 140307448084944>
004 | [<Phoenix 140307447980624>, <Phoenix 140307447654144>]
005 | <Phoenix 140307447654144> is Reborn!
006 | [<Phoenix 140307447980624>, <Phoenix 140307447654144>]
007 | <Phoenix 140307447980624> is Reborn!
gc.collect() is needed to ensure Phoenix.__del__ is called to restore the object
@formal sandal i may have gone a bit far ^
Make a hydra with it
!e python print(....__class__)
@midnight bane :white_check_mark: Your eval job has completed with return code 0.
<class 'ellipsis'>
its weird how ellipsis is an object
Pretty normal imo though the notation seems like magic
Is it only used as a special case for stuff like numpy and fastAPI?
or does it actually serve a purpose in the standard lib?
I believe it's also used for typing
:ok_hand: applied mute to @tribal moon until 2020-08-16 07:07 (9 minutes and 59 seconds) (reason: chars rule: sent 3466 characters in 5s).
!unmute 400096873978789888
:incoming_envelope: :ok_hand: pardoned infraction mute for @tribal moon.
Yeah I was dming modmail lol
Going a bit crazy there
Yea we get pinged on auto mod actions by @night quarry and log it so we can check it
I made a 2nd hello world script
don't wanna trigger the bot again
here's my IDLE pic
https://circuitpython.readthedocs.io/projects/adxl34x/en/latest/examples.html#motion-detection
how can i know what is the min Thershold and max thershold for motion detection??
thanks
Hmhm that's pretty simple to read actually
!e print(bytes([(True << (True ^ True << True) ^ True << (True << True ^ True << (True << True))), (True ^ True << (True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << (True << True) ^ True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << (True << True) ^ True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True ^ True << True ^ True << (True << True) ^ True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << (True << True) ^ True << (True ^ True << True) ^ True << (True ^ True << (True << True))), (True << (True ^ True << (True << True))), (True ^ True << True ^ True << (True << True) ^ True << (True << (True << True)) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True ^ True << True ^ True << (True << True) ^ True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << True ^ True << (True << (True << True)) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << (True << True) ^ True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << (True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True ^ True << (True ^ True << (True << True)))]).decode())
@brisk zenith :white_check_mark: Your eval job has completed with return code 0.
Hello, world!
i appreciate anybody who remembers when i made this a couple years back haha
i did! hang on
def true_shift(value):
code = ""
count = 0
if value == 0:
return
elif value == 1:
return 'True'
while value != 0:
if value % 2 == 1:
if count != 0:
code += "True << {} ^ ".format(true_shift(count))
else:
code += "True ^ "
count += 1
value >>= 1
return '({})'.format(code.strip(" ^ "))
while True:
print(true_shift(int(input("number: "))))
this is used to generate the code for a specific integer, so the code above uses this with the ASCII codes of the letters. code was written for 3.6 iirc
Neat.
Is that not 0?
it returns None ๐
Oh, I see.
i fucking love that
๐ณ how do you guys think this stuff up
i have no idea
Sometimes I start a new project, and it somehow gets an esoteric spin onto itself
lmao im mindblown by the stuff here
how did all that Trues and Falses turn into a Hello World 
well, True can be used as 1 in numeric contexts.
You can create a bytes object from a list of integers [0..255].
Then you can decode that bytes object into a str
huh makes sense. thanks for explaining your mysterious ways! ๐
interesting
I just had an idea, what if we use this to reconstruct the bytecode of a python script? 
That'd be a cool obfuscation method
hmm
that is very cool @brisk zenith,
if value % 2 == 1:
if count != 0:
code += "True << {} ^ ".format(true_shift(count))
else:
code += "True ^ "
I'm curious, did you derive that formula out yourself? What's the idea here
Using XOR to toggle the bits in an integer, I believe. You get a number e.g. 10000 by shifting 1 leftwards four places, then xor it with e.g. 1111 to get 11111.
yeah, i did figure that out myself, and @snow beacon has the right idea
to make the number 3 (binary 11) it must do (1 << 1) ^ 1
actually, better example
to make the number 4 (binary 100), it must do 1 << 2
but 2 can't be represented by a single True or anything
so we have to use the function recursively to find the representation that 2 should take
which is 1 << 1
so the final result for 4 is (1 << 2), or (1 << (1 << 1)) which is perfect
well why do you have the code.strip(" ^ ") part at the end then
Because with code += "True ^ " it would be possible for the code to end with ^ which is invalid
this is some really magical code
Hey @tribal moon!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
โข If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
โข If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
ye
About "fastest segfault": I've discovered a nice way ๐
import pygame
pygame.segfault()
this method does exactly what it says.
__import__('ctypes').string_at(0)
*iter(lambda:0,1),
that might give a segfault about OOM before crashing your computer
same with while 1:()
why would the loop segfault?
It's not storing the intermediate values...
why do you need a segfault function
If you're meaning why do we need one, it's because of the channel we're in. If you mean why pygame does, maybe to help people debug the memory of their programs.
I mean, is there a good reason to cause a segfault
i wonder if pygame's segfault function actually performs an access violation, or if it just sends a SIGSEGV signal to its own process.
volatile int p = *((int*)NULL) I guess
or something
I ran valgrind. Yep, it is dereferencing a pointer with the address 0x1.
valgrind python3.6 -c "import pygame; pygame.segfault()"
Also, why do I get so many errors when running valgrind on python?
so many invalid reads
weird that it goes for 0x1 and not 0x0. i guess it might be to differentiate it from an actual null pointer segfault or something
maybe
Mmhh the implementation is kinda janky
Is it dereferencing 0x0?
string_at(0) is doing the same thing right?
pretty much, yeah
oh, you don't even need a C extension.
!e
def f():
pass
f.__code__ = f.__code__.replace(co_consts=())
f()
@formal sandal :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
don't even need custom bytecode ๐
can you just explain to me how that one works ? I don't get it right now...
!e
import dis
def f():
pass
dis.dis(f)
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 | 4 0 LOAD_CONST 0 (None)
002 | 2 RETURN_VALUE
None is stored as a constant
so when you empty the list (tuple) of constants, it will get a segfault when trying to fetch the constant at index 0.
haha that's pretty smart
hmm, ok,nice !
Thanks for explaining
print(*[x%3//2*'Fizz'+x%5//4*'Buzz'or x+1 for x in range(100)])
I wanna make it shorter
Shortened by 1 char
[print(x%3//2*'Fizz'+x%5//4*'Buzz'or x+1) for x in range(100)]
Ah, very good
can we do 56
๐ค
!e
[print(x%3//2*'Fizz'+x%5//4*'Buzz'or x+1)for x in range(100)]
@modest sphinx :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 2
003 | Fizz
004 | 4
005 | Buzz
006 | Fizz
007 | 7
008 | 8
009 | Fizz
010 | Buzz
011 | 11
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/inupamoxej
!e
print(len("[print(x%3//2*'Fizz'+x%5//4*'Buzz'or x+1)for x in range(100)]"))
@modest sphinx :white_check_mark: Your eval job has completed with return code 0.
61
question what are you doing
Question is why the list comp: ```py
for x in range(100):print(x%3//2*'Fizz'+x%5//4*'Buzz'or x+1)
1 char shorter
!e ```py
print(len("for x in range(100):print(x%3//2*'Fizz'+x%5//4*'Buzz'or x+1)"))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
60
FizzBuzz as short as possible @young zealot
!e
for x in range(100):print(x%3//2*'Fizz'+x%5//4*'Buzz'or x+1)
@modest sphinx :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 2
003 | Fizz
004 | 4
005 | Buzz
006 | Fizz
007 | 7
008 | 8
009 | Fizz
010 | Buzz
011 | 11
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/oxukutuhog
Technically not smaller, but with a mini x ```py
for โ in range(100):print(โ%3//2*'Fizz'+โ%5//4*'Buzz'or โ+1)
Online unicode tables
@modest sphinx :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 2
003 | Fizz
004 | 4
005 | Buzz
006 | Fizz
007 | 7
008 | 8
009 | Fizz
010 | Buzz
011 | 11
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ehuqunejez
ofc
can we make code short
Already tried some things, it'll be pretty difficult to make it even shorter ๐
lets take it as a challenge
i saw somewhere it is possible in 56chars
also i saw fix errors type
I tried with recursion but that didn't work out, it's way too long: ```py
def f(โ):
print(โ%3//2*'Fizz'+โ%5//4*'Buzz'or โ+1)
if โ<99:f(โ+1)
f(0)
hahaha
Much better ```py
for ๐ซ in range(100):print(๐ซ%3//2*'Fizz'+๐ซ%5//4*'Buzz'or ๐ซ+1)
lol
technically
if we dont count the spaces
we make it shorter
๐
it is 56
Maybe we can use a PyPi package https://github.com/Paradoxis/Fizz-Buzz
@modest sphinx :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | ModuleNotFoundError: No module named 'fizzbuzz'
Local install only ofc
lol
but thts cheating
for ๐ซ in range(100):print(๐ซ%3//2*'Fizz'+๐ซ%5//4*'Buzz'or ๐ซ+1)
this is shortest
maybe the x one is shorter coz u know the pun
Maybe we should tackle something else
short code is directly proportional to less reaability
A while ago I made this tictactoe game: ```py
w=[0]16;a=[['']*3for _ in[0]*3];p=1;c=int;v={1:'X',-2:'O'};P=print;W={0:147,1:15,2:168,10:24,11:2578,12:26,20:348,21:35,22:376}
while not 3 in w:
for n in a:P(n)
n=c(input());a[c(n/10)][n%10]=v[p];n=list(str(W[n]));p=~p
for N in n:w[(abs(p)-1)*8+(c(N)-1)]+=1
P(f"{v[~p]} won")
Are you familiar with minimax?
It's an algorithm for perfect game playing
list(x) -> [*x] 
Or even *x,.
v could be ' OX ''OX'
...yeah, it could
wait hang on
no, you'd want just 'OX'
>>> 'OX'[1] # X
'X'
>>> 'OX'[-2] # O
'O'```
good point
P(*a,sep='\n') is one shorter than for n in a:P(n)
@sick hound will this work
fizz_buzz=lambda x:"fizz"*(x%3<1)+"buzz"*(x%5<1)or x
I have a version with all those shorter forms mentioned above somewhere
@sick hound Maximizing the minimum case?
In tic tac toe that would mean making sure you never lose
Ohh, that is actually a good one
Don't think I have that implemented, thanks ๐
But would it still print the board?
Yeah it does the exact same thing
Except it technically returns a bunch of None that get discarded
Oh, it doesn't, the more you know
*map(P,a), is even shorter :P
I think that's the point
if it didn't then it would be normal python and not esoteric python
A while ago I made this tictactoe game: ```py
w=[0]16;a=[['']*3for _ in[0]*3];p=1;c=int;v={1:'X',-2:'O'};P=print;W={0:147,1:15,2:168,10:24,11:2578,12:26,20:348,21:35,22:376}
while not 3 in w:
for n in a:P(n)
n=c(input());a[c(n/10)][n%10]=v[p];n=list(str(W[n]));p=~p
for N in n:w[(abs(p)-1)*8+(c(N)-1)]+=1
P(f"{v[~p]} won")
@sick hound plz have direction in the code lmao
there's a certain kind of pleasure in figuring out how an esoteric piece of code works
it's like a sadomasochistic puzzle
I won't kinkshame
Hey! I am writing a small script to fetch some values and set callbacks based on the time retrieved from the database column. The code is along the lines of ```
class Scheduler:
def init(self):
self.jobs = []
def add_job(self, job):
self.jobs.append(job)
def start(self):
for job in self.jobs:
job()
scheduler = Scheduler()
for i in range(3):
scheduler.add_job(lambda: print(i))
scheduler.start()
The problem is this code outputs: ```
2
2
2
How can I make the code output: ```
0
1
2
for i in range(3):
scheduler.add_job(lambda i=i: print(i))
Thanks @proper vault
```py
import functools
class Pausable:
def init(self, func):
self._gen = func
self._inst = None
def __call__(self, *args, **kwargs):
if self._inst is None:
self._inst = self._gen(*args, **kwargs)
return next(self._inst)
def __get__(self, instance, cls):
if instance is not None:
return functools.partial(self, instance) # "Freeze" the object instance as first argument (aka self)
return self
@Pausable
def d_act():
while True:
yield None
...
self.act = behavior if behavior is not None else d_act()
 ```py
import functools
class Pausable:
def __init__(self, func):
self._gen = func
self._inst = None
def __call__(self, *args, **kwargs):
if self._inst is None:
self._inst = self._gen(*args, **kwargs)
return next(self._inst)
def __get__(self, instance, cls):
if instance is not None:
return functools.partial(self, instance) # "Freeze" the object instance as first argument (aka self)
return self
...
self.act = behavior if behavior is not None else Pausable(lambda: (yield None) and (True, self.act()))
actually it doesn't work
why tho
shouldn't a = lambda: expr() and (cond(),a()) act as a while loop?
a = lambda: ((expr() and 0) or cond()) and a()
this is a do-while loop
!e
i = [0]
cond = lambda: i[0] < 5
expr = lambda: (print(i[0]), i.__setitem__(0, i[0]+1))
a = lambda: ((expr() and 0) or cond()) and a()
a()
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
@formal sandal so in my case :
well, uh, you can't put yield in a lambda
!e
act = lambda: ((yield None) and 0) and act()
@regal osprey :warning: Your eval job has completed with return code 0.
[No output]
huh?
yes i can
Lol
I see, you might be confused by generators
act is a function that returns a generator.
!e
import functools
class Pausable:
def __init__(self, func):
self._gen = func
self._inst = None
def __call__(self, *args, **kwargs):
if self._inst is None:
self._inst = self._gen(*args, **kwargs)
return next(self._inst)
def __get__(self, instance, cls):
if instance is not None:
return functools.partial(self, instance) # "Freeze" the object instance as first argument (aka self)
return self
act = Pausable(lambda: ((yield None) and 0) and act())
If you want to yield everything from a generator, you need to use yield from
nah i know @formal sandal, i just forgot that pausable class
oh
!e
import functools
class Pausable:
def __init__(self, func):
self._gen = func
self._inst = None
def __call__(self, *args, **kwargs):
if self._inst is None:
self._inst = self._gen(*args, **kwargs)
return next(self._inst)
def __get__(self, instance, cls):
if instance is not None:
return functools.partial(self, instance) # "Freeze" the object instance as first argument (aka self)
return self
act = Pausable(lambda: (((yield None) and 0) or True) and act()
for i in range(5):
act()
@regal osprey :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 21, in <module>
003 | File "<string>", line 12, in __call__
004 | StopIteration
hm...
i had found this WHILE = lambda:e() and (f(),WHILE()) on this website http://p-nand-q.com/python/lambda.html @formal sandal, you got any idea why it seems not to work with the (yield None). normally it shouldn't matter wether or not this is a generator, while is while
!e
import functools
class Pausable:
def __init__(self, func):
self._gen = func
self._inst = None
def __call__(self, *args, **kwargs):
if self._inst is None:
self._inst = self._gen(*args, **kwargs)
return next(self._inst)
def __get__(self, instance, cls):
if instance is not None:
return functools.partial(self, instance) # "Freeze" the object instance as first argument (aka self)
return self
@Pausable
def act():
yield None
act()
for i in range(5):
act()
@regal osprey :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 24, in <module>
003 | File "<string>", line 12, in __call__
004 | File "<string>", line 22, in act
005 | File "<string>", line 12, in __call__
006 | ValueError: generator already executing
hmm....
@regal osprey it's because it's a generator
that's only designed for when the function isn't a generator
it's actually recursion and not a proper loop
functions that contain yield don't actually do anything when you call them, they just construct a generator object and return that
yeah ik but i can't seem to find a way to do recursion with a generator
you need to use yield from
tried
act = Pausable(lambda: (((yield None) and 0) or True) and (yield from act())```
so as i was saying :

def act():
while True:
yield None
for i in range(5):
print(next(act))

act = lambda: (((yield 1) and 0) or True) and (yield from act())
gen = act()
for i in range(5):
print(next(gen))
oh wait even worse :
!e
act = (lambda: (((yield 1) and 0) or True) and (yield from act()))()
for i in range(5):
print(next(act))
@regal osprey :x: Your eval job has completed with return code 1.
001 | 1
002 | Traceback (most recent call last):
003 | File "<string>", line 3, in <module>
004 | File "<string>", line 1, in <lambda>
005 | TypeError: 'generator' object is not callable
ok nvm
i'd need Pausable for that
ah, @stark fable, look at what we made.... nightmares in packs of 6
!e
act = (gen := lambda: (((yield None) and 0) or True) and (yield from gen()))()
[print(next(act)) for i in range(5)]
@regal osprey :white_check_mark: Your eval job has completed with return code 0.
001 | None
002 | None
003 | None
004 | None
005 | None
lmao
!e
[print(next((gen := lambda: (((yield 1) and 0) or True) and (yield from gen()))())) for i in range(5)]
@regal osprey :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 1
003 | 1
004 | 1
005 | 1
oh my
With a codeblock it would be even more perfect :P
[print(next((gen := lambda: (((yield 1) and 0) or True) and (yield from gen()))())) for i in range(5)]
mhm, looking juicy
this is the new zen of python
i can't even imagine it with more complex paterns than just returning 1 x times
var1 = False
var2 = True
var3 = True
state1, state2, state3 = "๐ฉ" if var1, var2, var3 else "๐ฅ"
# state1 = "๐ฉ" if var1 else "๐ฅ"
# state2 = "๐ฉ" if var2 else "๐ฅ"
# state3 = "๐ฉ" if var3 else "๐ฅ"
``` I wish this was possible.. or am I doing something wrong here?
it's then-expression if condition else else-expression
what are you trying to do?
also, this is not a help channel
@sick hound ```py
state1, state2, state3 = ("๐ฅ๐ฉ"[var] for var in (var1, var2, var3))
Thank you
more esoteric
state1,state2,state3=map("๐ฅ๐ฉ".__getitem__,(var1, var2, var3))
๐ค
Migrated from #internals-and-peps
!e
import re
def ensnake(attrmapping):
class _SnakeCaseProxy:
def __getattr__(self, attr: str):
try:
return getattr(attrmapping, attr)
except AttributeError:
snake_case_attr = attr
camel_case_attr = re.sub(r"_(.)", lambda m: m[1].upper(), snake_case_attr)
return getattr(attrmapping, camel_case_attr)
_SnakeCaseProxy.__name__ = _SnakeCaseProxy.__qualname__ =\
f"_SnakeCaseProxy<{getattr(attrmapping, '__name__', repr(attrmapping))}>"
return _SnakeCaseProxy()
###
import logging
class IReallyLoveJava:
def helloWorld(self):
return "C#"
javaLover = IReallyLoveJava()
java_lover = ensnake(javaLover)
snake_logging = ensnake(logging)
print(java_lover.hello_world())
print(snake_logging.get_logger())
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 | C#
002 | <RootLogger root (WARNING)>
Use list unpacking
vars = [False, True, True]
state1, state2, state3 = ["๐ฉ" if i else "๐ฅ" for i in vars]```
oh it's already solved ๐ค
That's really cool fix
what kind of arcitechture is being used with this protocol?(Python-Socketio)
https://python-socketio.readthedocs.io/en/latest/intro.html
https://socket.io/ uses websockets internally IIRC
@proper vault can u explain..i didnt understand ur answer...
The second line is a fun way to write y = x
x = 5
from __main__ import x as y
print(x, y)
What if the current file isn't main?
Challenge: implement FizzBuzz using at most 5 vowels. (Using exec or eval is cheating!)
def f(n): #1
(n - 100
and #2
(print( #3
n%3//2*'Fizz'+ #4
n%5//4*'Buzz'+ #5
str(n+1)*(n%5//4==0==n%3//2)
)
,f(n+1)))
f(0)
```loops are overrated
actually,
def f(n): #1
if n - 100 != 0: #2
print( #3
n%3//2*'Fizz'+ #4
n%5//4*'Buzz'+ #5
str(n+1)*(n%5//4==0==n%3//2)
)
f(n+1)
f(0)
``` is much cleaner
str(n+1)*(n%5//4==0==n%3//2)
How is that clean ? ๐
I mean, it is pretty obvious in purpose, even if a bit chaotic
it has this cool almost symetry
it's clever, sure
I'd have put a bit more parentheses, though, if I didn't know every character counted here ^^
Challenge: implement FizzBuzz using at most 5 vowels. (Using
execorevalis cheating!)
@formal sandal I'm thinking of using some different character encoding, but that may not be valid ahahah
Well, at least 3 vowel are necessary for def and return
def fjzzbvzz(n):
return(n%3<1)*("F"+chr(105)+"zz")+(n%5<1)*("B"+chr(117)+"zz")or str(n)
a function version of fizzbuzz is possible with 4 vowels
[print((n%3<1)*("F"+chr(105)+"zz")+(n%5<1)*("B"+chr(117)+"zz")or str(n))for n in range(100)]
6 vowels
uhh, doesn't work properly for some reason fixed
Does this one work?
def fjzzbvzz(n):
return(n%3<1)*("F"+chr(105)+"zz")+(n%5<1)*("B"+chr(117)+"zz")or str(n)
yes
Awesome that you solved the chr(105) things. I was thinking about doing the same
!e
_=[print((n%3<1)*("F"+chr(105)+"zz")+(n%5<1)*("B"+chr(117)+"zz") + str(n)*((n%5>0)*(n%3>0)))for n in range(1,101)]
now it works
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 2
003 | Fizz
004 | 4
005 | Buzz
006 | Fizz
007 | 7
008 | 8
009 | Fizz
010 | Buzz
011 | 11
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/culafiguga
Well, one obvious improvement
!e
r=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
_=[print((n%3<1)*("F"+chr(105)+"zz")+(n%5<1)*("B"+chr(117)+"zz") + str(n)*((n%5>0)*(n%3>0)))for n in r]
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 2
003 | Fizz
004 | 4
005 | Buzz
006 | Fizz
007 | 7
008 | 8
009 | Fizz
010 | Buzz
011 | 11
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ugayogofux
๐
!e
_=[print((n%3<1)*("F"+chr(105)+"zz")+(n%5<1)*("B"+chr(117)+"zz") + str(n)*((n%5>0)*(n%3>0)))for m in '\1\2\3\4\5\6\7\10\11\12\13\14\15\16\17\20\21\22\23\24\25\26\27\30\31\32\33\34\35\36\37\40\41\42\43\44\45\46\47\50\51\52\53\54\55\56\57\60\61\62\63\64\65\66\67\70\71\72\73\74\75\76\77\100\101\102\103\104\105\106\107\110\111\112\113\114\115\116\117\120\121\122\123\124\125\126\127\130\131\132\133\134\135\136\137\140\141\142\143\144' if (n:=ord(m))]
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 2
003 | Fizz
004 | 4
005 | Buzz
006 | Fizz
007 | 7
008 | 8
009 | Fizz
010 | Buzz
011 | 11
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/kujilubuxi
[yes, I don't count y as a vowel]
oh shit, there are a and e in hex
fixed*
unfortunately, ord adds one vowel
so maybe just go with a list
This modified version of @proper vault solution is only 3 vovels:
def f(n): #1
if n - 100 != 0: #2
print( #3
n%3//2*('F'+chr(105)+'zz')+
n%5//4*('B'+chr(117)+'zz')+
str(n+1)*(n%5//4==0==n%3//2)
)
f(n+1)
f(0)
I accidentally pasted his/her original answer instad
I suppose that print will always be necessary
Yeah. maybe we can remove the def as well
huh?
Not sure
!e
def f(n): #1
n<100 and (
print( #3
n%3//2*('F'+chr(105)+'zz')+
n%5//4*('B'+chr(117)+'zz')+
str(n+1)*(n%5//4==0==n%3//2)
),
f(n+1)
)
f(0)
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 2
003 | Fizz
004 | 4
005 | Buzz
006 | Fizz
007 | 7
008 | 8
009 | Fizz
010 | Buzz
011 | 11
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/gipehahiqu
got rid of the if, but and has a vowel as well : - (
I don't think there's a python keyword without vowels
That's just too bad
no, there isn't
This is another 3 vowel solution
!e
r = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
[print(n % 3//2*('F'+chr(105)+'zz')+n % 5//4*('B'+chr(117)+'zz') + str(n+1)*(n % 5//4 == 0 == n % 3//2)) for n in r]
@slate wasp :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 2
003 | Fizz
004 | 4
005 | Buzz
006 | Fizz
007 | 7
008 | 8
009 | Fizz
010 | Buzz
011 | 11
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/icatopupib
I'm not sure if we can get much lower than 3 @formal sandal
Considering python's vowel keywords
One vowel: python print('1\n2\nF\151zz\n4\nB\165zz\nF\151zz\n7\n8\nF\151zz\nB\165zz\n11\nF\151zz\n13\n14\nF\151zzB\165zz\n16\n17\nF\151zz\n19\nB\165zz\nF\151zz\n22\n23\nF\151zz\nB\165zz\n26\nF\151zz\n28\n29\nF\151zzB\165zz\n31\n32\nF\151zz\n34\nB\165zz\nF\151zz\n37\n38\nF\151zz\nB\165zz\n41\nF\151zz\n43\n44\nF\151zzB\165zz\n46\n47\nF\151zz\n49\nB\165zz\nF\151zz\n52\n53\nF\151zz\nB\165zz\n56\nF\151zz\n58\n59\nF\151zzB\165zz\n61\n62\nF\151zz\n64\nB\165zz\nF\151zz\n67\n68\nF\151zz\nB\165zz\n71\nF\151zz\n73\n74\nF\151zzB\165zz\n76\n77\nF\151zz\n79\nB\165zz\nF\151zz\n82\n83\nF\151zz\nB\165zz\n86\nF\151zz\n88\n89\nF\151zzB\165zz\n91\n92\nF\151zz\n94\nB\165zz\nF\151zz\n97\n98\nF\151zz\nB\165zz\n')
!e ```py
a = 1
aแ = 2
aแ แ = 3
print(a, aแ , aแ แ )
@sick hound :white_check_mark: Your eval job has completed with return code 0.
1 2 3
Unicode as? 
Haha
!charinfo a aแ aแ แ
You are not allowed to use that command here. Please use the #bot-commands channel instead.
Same character that makes this message unquoteable:
hello โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโworld!
Zero length continuation character
U+180B is the unicode hex value of the character Mongolian Free Variation Selector One (FVS1). Char U+180B, Encodings, HTML Entitys:แ ,แ , UTF-8 (hex), UTF-16 (hex), UTF-32 (hex)
Ah, so the whole token is a + the zero space char(s), gotcha
I think that has a lot of obfuscation potential
That make sense actually
at least visually
This is beautiful: ```py
_แ =[0]16;_แ แ =[['']*3for _ in[0]*3];_แ แ แ =1;_แ แ แ =int;_แ แ แ ='OX';_แ แ แ =print;_แ แ แ ={0:147,1:15,2:168,10:24,11:2578,12:26,20:348,21:35,22:376}
while not 3in _แ :
*map(_แ แ แ ,_แ แ ),;_แ แ แ =_แ แ แ (input());_แ แ [_แ แ แ (_แ แ แ /10)][_แ แ แ %10]=_แ แ แ [_แ แ แ ];_แ แ แ =*str(_แ แ แ [_แ แ แ ]),;_แ แ แ =~_แ แ แ
for _แ แ แ in _แ แ แ :_แ [(abs(_แ แ แ )-1)*8+(_แ แ แ (_แ แ แ )-1)]+=1
_แ แ แ (f"{_แ แ แ [~_แ แ แ ]} won")

!e ```py
_แ =[0]16;_แ แ =[['']*3for _ in[0]*3];_แ แ แ =1;_แ แ แ =int;_แ แ แ ='OX';_แ แ แ =print;_แ แ แ ={0:147,1:15,2:168,10:24,11:2578,12:26,20:348,21:35,22:376}
while not 3in _แ :
*map(_แ แ แ ,_แ แ ),;_แ แ แ =_แ แ แ (input());_แ แ [_แ แ แ (_แ แ แ /10)][_แ แ แ %10]=_แ แ แ [_แ แ แ ];_แ แ แ =*str(_แ แ แ [_แ แ แ ]),;_แ แ แ =~_แ แ แ
for _แ แ แ in _แ แ แ :_แ [(abs(_แ แ แ )-1)*8+(_แ แ แ (_แ แ แ )-1)]+=1
_แ แ แ (f"{_แ แ แ [~_แ แ แ ]} won")
@slate wasp :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | TypeError: 'dict' object is not callable
i fear no man, but that thing as a beginner it scares me..
!charinfo a aแ aแ แ
\u0061 : LATIN SMALL LETTER A - a
\u0020 : SPACE -
\u0061 : LATIN SMALL LETTER A - a
\u180b : MONGOLIAN FREE VARIATION SELECTOR ONE - แ
\u0020 : SPACE -
\u0061 : LATIN SMALL LETTER A - a
\u180b : MONGOLIAN FREE VARIATION SELECTOR ONE - แ
\u180b : MONGOLIAN FREE VARIATION SELECTOR ONE - แ
\u0061\u0020\u0061\u180b\u0020\u0061\u180b\u180b
Unicode smh
Mongolian free variation selector one?
@slate wasp Weird, it works in my VSC
!e
_แ =[0]*16;_แ แ =[['*']*3for _ in[0]*3];_แ แ แ =1;_แ แ แ =int;_แ แ แ ='OX';_แ แ แ =print;_แ แ แ ={0:147,1:15,2:168,10:24,11:2578,12:26,20:348,21:35,22:376}
while not 3in _แ :
*map(_แ แ แ ,_แ แ ),;_แ แ แ =_แ แ แ (input());_แ แ [_แ แ แ (_แ แ แ /10)][_แ แ แ %10]=_แ แ แ [_แ แ แ ];_แ แ แ =*str(_แ แ แ [_แ แ แ ]),;_แ แ แ =~_แ แ แ
for _แ แ แ in _แ แ แ :_แ [(abs(_แ แ แ )-1)*8+(_แ แ แ (_แ แ แ )-1)]+=1
_แ แ แ (f"{_แ แ แ [~_แ แ แ ]} won")
?!
Doesn't seems to work in my terminal either
Really strange
It is really the same code
But VSC autopep8 formats it slightly different
Either way, that game is just madness
It looks like a much of hieroglyphs, but works like a charm
Haha ๐
Input it as matrix coordinates
with sheer willpower- yeah that
ah
got a bug
['X', 'X', 'O']
['O', 'O', 'X']
['X', '*', 'O']
21
['X', 'X', 'O']
['O', 'O', 'X']
['X', 'X', 'O']
2
O won
>>>
need draw condition
@sick hound
Ooo, right
does anyone have a idea how can i write this in dict comprehension?
for j in liste:
data[j] = etรผt(data[j])
data = {item: func(item) for item in some_list}?
Yeah, it is pretty good as is IMO
oh wait, right, it's using data[j] as the argument
data.update({item: func(data[item]) for item in some_list}) should be it, but I do agree that it's fine as it is and should probably be kept that way
thanks bro it works fine
!e
import pprint
import json
import re
TOKEN_RE = r"\s*" + "|".join([
r"(?P<LPAR>\()",
r"(?P<RPAR>\))",
r"(?P<INTEGER>\d+)",
r"(?P<NAME>[a-zA-Z][-_a-zA-Z0-9]*)",
r'(?P<STRING>"(?=[^"]|\\.)*")'
])
s = """
(sequence
(move 1 2)
(repeat
(move 23 4) 3)
(repeat
(shoot) 2)
(parallel
(repeat (shoot) 3)
(repeat (move 8 9) 2)))
"""
stack = []
current_sexpr = []
for m in re.finditer(TOKEN_RE, s):
tokens = {k: v for (k, v) in m.groupdict().items() if v is not None}
name, content = tokens.popitem()
if name == "LPAR":
stack.append(current_sexpr)
current_sexpr = []
elif name == "RPAR":
stack[-1].append(current_sexpr)
current_sexpr = stack.pop()
elif name == "INTEGER":
expr = int(content)
current_sexpr.append(expr)
elif name == "STRING":
expr = json.loads(content)
current_sexpr.append(expr)
else:
expr = "$" + content
current_sexpr.append(expr)
pprint.pprint(current_sexpr)
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 | [['$sequence',
002 | ['$move', 1, 2],
003 | ['$repeat', ['$move', 23, 4], 3],
004 | ['$repeat', ['$shoot'], 2],
005 | ['$parallel', ['$repeat', ['$shoot'], 3], ['$repeat', ['$move', 8, 9], 2]]]]
let's golf it
datecard=lambda n:[[28,30,n],[31]][n<31]
is there a way to make this shorter?
datecard=lambda n:n//31*[28,30,n]or[31]
thanks guys, appreciate it
So esoteric python is python with all readability out the window?
Well, I'd say this https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpriseEdition qualifies as esoteric-Java, so I'd say a code can be readable but still esoteric. Basically, it's code that you shouldn't actually use in production ๐
I remember FizzBuzzEnterprizeEdition ๐
It would almost be hard to make something like that in python
Java breeds that kind of code, but python is a lot shorter to write
I wrote a generateor for fizzbuzz, but I feel it get's worse than that ```python
class Fizzgen():
def init(self, n):
self.n = n
self.last = 0
def __next__(self):
return self.next()
def check(self, x):
return self.last % x
def next(self):
if self.last == self.n:
raise StopIteration
self.last += 1
ret = self.last
if self.check(3):
ret = 'Fizz'
if self.check(5):
ret = 'Buzz'
if self.check(3):
ret = 'FizzBuzz'
return ret
g = Fizzgen(100)
while True:
try:
print(next(g))
except StopIteration:
break
Forgot to obfuscate all of it ๐
@hard spoke I would argue that all Java is esoteric
I support that theory
heh, and I thought it was just me who felt like Java programming is a massive pain after using it for more than a year
I used it for a day before uninstalling it
found this on reddit (similar idea, different language):
i did this with meta classes
class FizzBuzzMeta(type):
def __call__(cls, n):
return ' '.join(''.join(word for word, value in cls.__annotations__.items() if i % value == 0) or str(i) for i in range(1, n + 1))
class FizzBuzz(metaclass=FizzBuzzMeta):
Fizz: 3
Buzz: 5
print(FizzBuzz(15))
I was wondering about a legit use of a meta class. I just learned about them
typing uses metaclasses to allow subscriptable types, I believe. Like, List[int] isn't possible with a normal class.
it's fun to define things quickly:
In [2]: class FooBarBaz(metaclass=FizzBuzzMeta):
...: Foo: 3
...: Bar: 4
...: Baz: 7
...:
In [3]: print(FooBarBaz(21))
1 2 Foo Bar 5 Foo Baz Bar Foo 10 11 FooBar 13 Baz Foo Bar 17 Foo 19 Bar FooBaz
!e
def accumulate(label: str, modulo: int):
def decorator(f):
def new_fn(x):
n, acc = f(x)
return (n, label + acc if n % modulo == 0 else acc)
return new_fn
return decorator
def seal(f):
def new_fn(x):
n, acc = f(x)
return acc or str(n)
return new_fn
@seal
@accumulate("Fizz", 3)
@accumulate("Buzz", 5)
@accumulate("Bar", 2)
@accumulate("Hello", 4)
def fizz_buzz_bar_hello(n):
return (n, "")
for i in range(1, 101):
print(fizz_buzz_bar_hello(i), end=" ")
print()
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
1 Bar Fizz BarHello Buzz FizzBar 7 BarHello Fizz BuzzBar 11 FizzBarHello 13 Bar FizzBuzz BarHello 17 FizzBar 19 BuzzBarHello Fizz Bar 23 FizzBarHello Buzz Bar Fizz BarHello 29 FizzBuzzBar 31 BarHello Fizz Bar Buzz FizzBarHello 37 Bar Fizz BuzzBarHello 41 FizzBar 43 BarHello FizzBuzz Bar 47 FizzBarHello 49 BuzzBar Fizz BarHello 53 FizzBar Buzz BarHello Fizz Bar 59 FizzBuzzBarHello 61 Bar Fizz BarHello Buzz FizzBar 67 BarHello Fizz BuzzBar 71 FizzBarHello 73 Bar FizzBuzz BarHello 77 FizzBar 79 BuzzBarHello Fizz Bar 83 FizzBarHello Buzz Bar Fizz BarHello 89 FizzBuzzBar 91 BarHello Fizz Bar Buzz FizzBarHello 97 Bar Fizz BuzzBarHello
well, a metaclass solution is better, of course
@cursive pine You can also look at this: https://gist.github.com/decorator-factory/b2fd85ef8248c9230835461c1ec24597, here I use both metaclasses and metametaclasses.
In [8]: class MaybeInt(SumType):
...: Just.of(int)
...: Nothing.of(())
...:
In [9]: x = MaybeInt.Just(42)
In [10]: x
Out[10]: 42
In [11]: type(x)
Out[11]: embellished('Just', <class 'int'>)
In [12]: y = MaybeInt.Nothing(())
In [13]: y
Out[13]: ()
In [14]: type(y)
Out[14]: embellished('Nothing', ())
found this on reddit (similar idea, different language):
!e
import asyncio
async def sort(iterable):
output = []
await asyncio.gather(
*(sort_one(item, output) for item in iterable)
)
return output
async def sort_one(item, output):
await asyncio.sleep(item/10)
output.append(item)
async def main():
my_list = [5, 2, 6, 1, 8, 9, 3, 4, 7]
print(await sort(my_list))
asyncio.run(main())
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
[1, 2, 3, 4, 5, 6, 7, 8, 9]
ah, the sleep sort?
lol
saw that but in JS on r/shittyprogramming yesterday
from operator import truediv,mul,add,sub; from functools import reduce
calc = {('d',op.__name__[0])[op.__name__!='truediv']:lambda *args:reduce(lambda x,y: op(x,y),args) for op in [truediv,mul,add,sub]}
print(calc[input('d,m,a,s: ')](*map(int,input('nums (space separated): ').split())))
Was trying to make a calculator
With dictionaries + lambda
But when you pick an operation (d for division) and type in numbers, it subtracts them for some reason
To debug, this is what I did
from operator import truediv,mul,add,sub; from functools import reduce
calc = {('d',op.__name__[0])[op.__name__!='truediv']:lambda *args:reduce(lambda x,y: op(x,y),args) for op in [truediv,mul,add,sub]}
for name, func in calc.items():
print(name, func(1, 2, 3))
d -4
m -4
a -4
s -4
And this is what I got
Anyone know how to fix this?
Let me try making a clean version of this and see if it works there
!e
from operator import truediv, mul, sub, add
from functools import reduce
operation_dict = dict()
operations = [truediv, mul, sub, add]
for operation in operations:
operation_dict[('d', operation.__name__[0])[operation.__name__ != 'truediv']] = lambda *args: reduce(lambda x, y: operation(x, y), args)
for name, func in operation_dict.items():
print(name, func(1, 2, 3))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | d 6
002 | m 6
003 | s 6
004 | a 6
It doesn't work in normal code either. Hm
It's adding for all of the inputs this time
!e
from operator import truediv, mul, sub, add
from functools import reduce
operation_dict = dict()
operations = [mul, sub, add, truediv]
for operation in operations:
func = lambda *args: reduce(lambda x, y: operation(x, y), args)
print(operation.__name__, func(1, 2, 3))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | mul 6
002 | sub -4
003 | add 6
004 | truediv 0.16666666666666666
This outputs it fine
Hm
Wait
No way
Ok, somehow got it working
!e
from operator import truediv,mul,sub,add;from functools import reduce;a=input();b=map(int,input().split())
print(reduce(lambda x, y: {('d',op.__name__[0])[op.__name__!='truediv']: op for op in [truediv,mul,sub,add]}[a](x,y), b))
@sick hound :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | EOFError: EOF when reading a line
Ah, can't input here
from operator import truediv,mul,sub,add;from functools import reduce;a=input();b=map(int,input().split())
print(reduce(lambda x, y: {('d',op.__name__[0])[op.__name__!='truediv']: op for op in [truediv,mul,sub,add]}[a](x,y), b))
2 line calculator that supports division, multiplication, subtraction and addition on any number of arguments
First line is the operation's starting character, for example, m for multiplication, a for addition and so on
2nd line is any number of arguments
Still wondering why the old code didn't work
for the same reason that this happens ```py
funcs = [lambda: x for x in range(5)]
funcs0
4```
Holy
I was just trying to find a way to fix the thing as @stark fable mentioned
I see
I never knew about this
Is this a book? @hard spoke
nope, just a small site
you can fix it with funcs = [lambda x=x: x for x in range(5)]
Yeah, thanks, just also figured it out
oh wow, that's an interesting one
yep, default arguments are evaluated when the function is created and then they're stored on the function object
yeah. I've never actually seen default arguments on lambdas before ๐
>>> (lambda x=4: x).__defaults__
(4,)```
still prefer functools.partial though
yeah but :<functools.partial is 17 characters
default arguments in lambdas are used to avoid the closure gotcha
!e
fns = []
for i in range(5):
fns.append(lambda x: x + i)
for fn in fns:
print(fn(100))
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 | 104
002 | 104
003 | 104
004 | 104
005 | 104
!e
fns = []
for i in range(5):
fns.append(lambda x, i=i: x + i)
for fn in fns:
print(fn(100))
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 | 100
002 | 101
003 | 102
004 | 103
005 | 104
^ solution
Can you put conditionals in lambdas?
you can use if expression a if cond else b
ohh so list comprehension not a general if statement?
you cannot put a statement into a lambda, but that is not comprehension
I meant the same format as conditionals in a list comprehension
Ok sorry I meant PEP 308: Conditional Expressions ๐
Could you give an example? One way you can do it is
(if statement is false, if statement is true)[condition]
This is more like the C++ approach
that is the terser option
Yeah
but you cannot use it for recursion and things with side effects
Yeah, and python ternary equivalent is: (x, 50)[x > 50]
and the sane way to do that is min(50, x)
x ? y : z -> y if x else z
(y, z)[x] isn't quite "equivalent"
it's similar but try putting a call to print in one of them and you'll notice it always executes
i'm pretty sure ?: doesn't do that
it doesn't
!e python x = 100;print([a if a % 3 == 1 or a % 5 == 1 else 'FizzBuzz' if not a % 15 else 'Fizz' if not a % 3 else 'Buzz' for a in range(x)])
@cursive pine :white_check_mark: Your eval job has completed with return code 0.
['FizzBuzz', 1, 'Buzz', 'Fizz', 4, 'Buzz', 6, 7, 'Buzz', 'Fizz', 10, 11, 'Fizz', 13, 'Buzz', 'FizzBuzz', 16, 'Buzz', 'Fizz', 19, 'Buzz', 21, 22, 'Buzz', 'Fizz', 25, 26, 'Fizz', 28, 'Buzz', 'FizzBuzz', 31, 'Buzz', 'Fizz', 34, 'Buzz', 36, 37, 'Buzz', 'Fizz', 40, 41, 'Fizz', 43, 'Buzz', 'FizzBuzz', 46, 'Buzz', 'Fizz', 49, 'Buzz', 51, 52, 'Buzz', 'Fizz', 55, 56, 'Fizz', 58, 'Buzz', 'FizzBuzz', 61, 'Buzz', 'Fizz', 64, 'Buzz', 66, 67, 'Buzz', 'Fizz', 70, 71, 'Fizz', 73, 'Buzz', 'FizzBuzz', 76, 'Buzz', 'Fizz', 79, 'Buzz', 81, 82, 'Buzz', 'Fizz', 85, 86, 'Fizz', 88, 'Buzz', 'FizzBuzz', 91, 'Buzz', 'Fizz', 94, 'Buzz', 96, 97, 'Buzz', 'Fizz']
it somewhat works
Wait that's super broken
Itโs only good for assignment and stuff
@sick hound Yeah, I figured that out the hard way. I thought you could run functions like this. There was an error in my code and I spent around an hour trying to fix it. Ended up finding out that python ternary operators execute both expressions
do note that that is not a ternary. It is literally just a tuple that you index into with a boolean value
python ternary operators execute the condition and then only one expression
(y, z)[x] is not a ternary operator
it's indexing a tuple
Ah, so, (0, 1)[True] will return 1?
Oh wait, True is 1
So it indexes it
I see, makes sense
What does ? do?
Thatโs C/C++
ohh lol
๐
ok how does or work when saying python [a if not a % 3 or a % 5 else 'Yay' for a in range(x)]
[(a if ((not a % 3) or a % 5) else 'Yay') for a in range(x)]
not has a higher priority than or
Python's parser is even smarter than I realised
!e ```python
print(*[a if not a % 3 or not a % 5 else 'Yay' for a in range(100)][1:])
@cursive pine :white_check_mark: Your eval job has completed with return code 0.
Yay Yay 3 Yay 5 6 Yay Yay 9 10 Yay 12 Yay Yay 15 Yay Yay 18 Yay 20 21 Yay Yay 24 25 Yay 27 Yay Yay 30 Yay Yay 33 Yay 35 36 Yay Yay 39 40 Yay 42 Yay Yay 45 Yay Yay 48 Yay 50 51 Yay Yay 54 55 Yay 57 Yay Yay 60 Yay Yay 63 Yay 65 66 Yay Yay 69 70 Yay 72 Yay Yay 75 Yay Yay 78 Yay 80 81 Yay Yay 84 85 Yay 87 Yay Yay 90 Yay Yay 93 Yay 95 96 Yay Yay 99
That is the exact oppisite of what I want
But if I remove the nots it gives me
!e python print(*[a if a % 3 or a % 5 else 'Yay' for a in range(100)][1:])
@cursive pine :white_check_mark: Your eval job has completed with return code 0.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 Yay 16 17 18 19 20 21 22 23 24 25 26 27 28 29 Yay 31 32 33 34 35 36 37 38 39 40 41 42 43 44 Yay 46 47 48 49 50 51 52 53 54 55 56 57 58 59 Yay 61 62 63 64 65 66 67 68 69 70 71 72 73 74 Yay 76 77 78 79 80 81 82 83 84 85 86 87 88 89 Yay 91 92 93 94 95 96 97 98 99
Which I'm confused by
anything nonzero is true
yes up top. But anything 0 should be true on the bottom right? It seems the or is working like an and
Wait an And works fine there it makes it work. I'm so confused
a if a % 3 or a % 5 else 'Yay' is equivalent to a if ((a % 3 != 0) or (a % 5 != 0)) else 'Yay'
!e py print(*[a if a % 3 and a % 5 else 'Yay' for a in range(100)][1:])
@stark fable :white_check_mark: Your eval job has completed with return code 0.
1 2 Yay 4 Yay Yay 7 8 Yay Yay 11 Yay 13 14 Yay 16 17 Yay 19 Yay Yay 22 23 Yay Yay 26 Yay 28 29 Yay 31 32 Yay 34 Yay Yay 37 38 Yay Yay 41 Yay 43 44 Yay 46 47 Yay 49 Yay Yay 52 53 Yay Yay 56 Yay 58 59 Yay 61 62 Yay 64 Yay Yay 67 68 Yay Yay 71 Yay 73 74 Yay 76 77 Yay 79 Yay Yay 82 83 Yay Yay 86 Yay 88 89 Yay 91 92 Yay 94 Yay Yay 97 98 Yay
Slotting that in this works now
!e python print(*[a if a % 3 and a % 5 else 'FizzBuzz' if not a % 15 else 'Fizz' if a % 3 else 'Buzz' for a in range(100)][1:])
@cursive pine :white_check_mark: Your eval job has completed with return code 0.
1 2 Buzz 4 Fizz Buzz 7 8 Buzz Fizz 11 Buzz 13 14 FizzBuzz 16 17 Buzz 19 Fizz Buzz 22 23 Buzz Fizz 26 Buzz 28 29 FizzBuzz 31 32 Buzz 34 Fizz Buzz 37 38 Buzz Fizz 41 Buzz 43 44 FizzBuzz 46 47 Buzz 49 Fizz Buzz 52 53 Buzz Fizz 56 Buzz 58 59 FizzBuzz 61 62 Buzz 64 Fizz Buzz 67 68 Buzz Fizz 71 Buzz 73 74 FizzBuzz 76 77 Buzz 79 Fizz Buzz 82 83 Buzz Fizz 86 Buzz 88 89 FizzBuzz 91 92 Buzz 94 Fizz Buzz 97 98 Buzz
i think you got it the wrong way round
fizz and buzz are backwords lol
Missing a not
print(*[a if a % 3 and a % 5 else 'FizzBuzz' if not a % 15 else 'Fizz' if not a % 3 else 'Buzz' for a in range(100)][1:])
Done
I found this one online, but have no clue how it works
["Fizz"*(1-x%3)+"Buzz"*(1-x%5)or str(x)for x in range(1,100)]```
now how does that or there work?
@sick hound That explains why my Or statement was not working but And did. Thx
@sick hound that's not specific to list comprehensions
@cursive pine no it doesn't
your or wasn't working because not (not x or not y) is not x or y, it's x and y
ok
always
>>> False or 4
4```
it literally never casts one of the values to a bool and gives you that
if the first value is true it gives you the first value, otherwise it gives you the second value
>>> dis.dis('x or y')
1 0 LOAD_NAME 0 (x)
2 JUMP_IF_TRUE_OR_POP 6
4 LOAD_NAME 1 (y)
>> 6 RETURN_VALUE```
load x, if x is true then jump to RETURN_VALUE and return that, otherwise pop it, load y, and return that
tiny recursive descent calculator, supports + - * / % () and whitespace py import operator z={a:getattr(operator,b)for a,b in zip("+-*/%",["add","sub","mul","truediv","mod"])} b=lambda i:i<len(s) def o(o,n): def p(i): l,i=n(i) if b(i)and s[i]in o:r,j=p(i+1);return int(z[s[i]](l,r)),j return l,i return p def a(i): a="" while b(i)and"/"<s[i]<":":a+=s[i];i+=1 return int(a),i def g(i): if s[i]=="(":x,j=t(i+1);return x,j+1 return a(i) t=o("+-",o("*/%",g)) s=input().replace(" ","") print(t(0)[0])
could probably be a lot shorter with shunting yard though
whats esoteric?
oh
What do you guys think of this? https://www.youtube.com/watch?v=sbIzdpQdaYs
"Teeing up Python: Code Golf
[EuroPython 2017 - Talk - 2017-07-12 - PyCharm Room]
[Rimini, Italy]
Code golfing is an interesting heuristic dedicated to minimizing the overall length of code to produce the same functionality. The result doesnโt have to be incomprehensible, and...
can @night quarry !e command import modules?
Was just experimenting on python so there's no actual use for this, but I was wondering if there's a way to call dictionaries who have lambdas/functions as their key
This is all I was able to think of
d = {
lambda x: x < 15: 'a',
lambda x: 30 > x > 15: 'b',
lambda x: x > 30: 'c',
}
for func, string in d.items():
print(string if func(70) else '')
[val for func, val in d.items() if func(70)] is pretty similar, but makes a list of all matches.
!e
print("test")
@steady cape :white_check_mark: Your eval job has completed with return code 0.
test
coolรถ
something like
import itertools,collections
# recipe from itertools docs
def consume(iterator, n=None):
"Advance the iterator n-steps ahead. If n is None, consume entirely."
# Use functions that consume iterators at C speed.
if n is None:
# feed the entire iterator into a zero-length deque
collections.deque(iterator, maxlen=0)
else:
# advance to the empty slice starting at position n
next(itertools.islice(iterator, n, n), None)
consume(1 for func, val in d.items() if func(70))
would be as fast (or a bit faster) without creating a list of results.
prob not the right channel but:
var = [(i.name, i.id) for i in ctx.guild.members]
# gives
[('Buster', 272699141358878720), ('Coppen', 444901560544264212), ('Testing Bot', 730739952391946252)]
How can I join this list of tuples?
I tried: ```py
print([' '.join(t) for t in var])
gives
TypeError: sequence item 1: expected str instance, int found
you want a list of strings?
var = [(i.name, str(i.id)) for i in ctx.guild.members]
if they were strings, it would just work
In the end I want the result to be like
Buster - 272699141358878720
Coppen - 444901560544264212
...
right
Yes
m_list = []
for member in ctx.guild.members:
m_list.append(f"{member.name} - {member.id}")
is what I had before
or is what I have
cool
[f'{i.name} - {i.id}' for i in ctx.guild.members]
This works
var = [(i.name, '-', str(i.id)) for i in ctx.guild.members]
res = [' '.join(t) for t in var]
print('\n'.join(res))
[f'{i.name} - {i.id}' for i in ctx.guild.members]
@proper vault Yeah this is the most logical and best choice, thought I'd try it another way
apparently not the answer for everything haha
Golf - lowest score wins right
Code Golf - fewest characters to get the solution wins
If you want to try out golfing they've got some fun challenges at https://www.codingame.com
@proud glade
ohkk
And there's also a whole Stack Exchange dedicated to the art https://codegolf.stackexchange.com
But most of the stuff there goes way over my head.
ohll
And there's also a whole Stack Exchange dedicated to the art https://codegolf.stackexchange.com
@river idol Just threw up in my mouth at some of the threads on there
Yeah, people have written whole programming languages just for golfing ๐
that's lame IMO
"hey look, it takes 1 character in this language, I've put so much creative effort into that"
there's a golfing-focused derivative of python called "pyth" that takes an integer input, calulates the prime factors of said input, then prints it out as a list, with just one character.
P
i think the input and output is done implicitly at the start and end of the program and P is just the factorising function
That kinda breaks the challenge lol
using unicode identifiers, one symbol is probably enough to encode the common codegolf programs
the only way to beat that is to design a language for each codegolf problem, in which case you can solve them in 0 symbols ๐
yup, code golf is more interesting in general-purpose languages anyways
!e
int = str
print(isinstance('test', int))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
True
!e
float = str
print(isinstance(3.4, float))
print(isinstance('3.4', float))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | False
002 | True
Hello, I have a question.
If we have 'something.py' in our 'dir' directory we can import it with import dir.something. My question is that how can I import it, if the filename starts with a dot ('.') for example 'dir/.something.py' . If I'm using the wrong channel, tell me.
Have a good day.
I have a problem in my code and I want to ask several questions.
X = "abcdefgฤhฤฑijklmnoรถprsลtuรผvyzw"
#User must put a number between 1-10.
zeka = input("Zeka seviyenizi 1-10 arasฤฑ bir sayฤฑ ile tanฤฑmlayฤฑnฤฑz:")
if zeka <= int(3):
print(X[-9]+X[4]+X[15]+X[10]+X[15]+" "+X[-9]+X[16]+X[19]+X[-6]+X[15]+X[-6]+
X[15]+" "+X[15]+X[4]+" "+X[1]+X[-6]+X[15]+X[3]+X[0]+X[15]+
" "+X[3]+X[0]+X[8]+X[0]+" "+X[10]+X[-3]+X[10]+X[-9]+X[10]+X[15])
#I want to put >3 but <6 how can I do that?
elif zeka >(3):
print(X[12]+X[4]+X[15]+X[3]+X[10]+X[15]+X[10]+" "+X[1]+X[10]+X[19]+X[0]
+X[3]+X[0]+X[8]+X[0]+" "+X[6]+X[4]+X[13]+X[10]+X[-8]+X[-7]
+X[10]+X[19])
#Here is the error when I test the error;
if zeka <= int(3):
TypeError: '<=' not supported between instances of 'str' and 'int'```
Thanks for help! <3
Btw I am new python programmer so I don't know too much.
Maybe other channels would be better place to look for help. This channel is about making code as atrociously as possible.
I'd argue it's beautiful, not atrocious
Oh thanks for info dude.
though I understand your view ๐
I am fetishizing the code.
And also which channel I may ask for help?
!e
int, str = str, int
print(isinstance(10, str))
print(isinstance("10", str))
@twilit grotto :white_check_mark: Your eval job has completed with return code 0.
001 | True
002 | False
@fringe shell check out __import__
@static holly I did check it out. I learned that when using import xyz it is done with the __import__. But still ,if I want to use it, I need to something like that __import__('dir..something') to do it, which, by the way tries to import dir. for some reason. So I tried from dir import .something setup with __import__ , here is what I did : __import__('dir', globals(), locals(), ['.something']), but sadly it tried to import dir..something anyways. So still no solution.
And something interesting I noticed: if I try __import__('dir..something') it will say that there isn't a dir. directory, but if I rename dir to dir. it will say that there isn't a dir directory. Weird
how can i override serializer = AttendanceSerializer(y) this method anyone have idea?
that calls __call__, which calls __new__ and __init__
I am pretty sure __call__ is for a call on the instance of the class
And when you do Class() it calls __new__
Yeah ^
New is for when the class is created
Init is when it's initialized
And call is for when you actually call the instance
!e
import random
def rnd():
return random.randint(0,2)
for i in range(0,5):
lst = ["float", "int", "str"]
statement = "{}={}".format(lst[rnd()],lst[rnd()])
exec(statement)
print("float={}".format(float))
print("int={}".format(int))
print("str={}".format(str), "{}".format(statement))
@alpine flower :white_check_mark: Your eval job has completed with return code 0.
001 | float=<class 'float'>
002 | int=<class 'int'>
003 | str=<class 'int'> str=int
004 | float=<class 'float'>
005 | int=<class 'int'>
006 | str=<class 'int'> str=int
007 | float=<class 'int'>
008 | int=<class 'int'>
009 | str=<class 'int'> float=str
010 | float=<class 'int'>
011 | int=<class 'int'>
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ebewidofep
@alpine flower Shell game? ๐
Shell game to make debugging harder
!e
import asyncio
# Library code:
async def run(generator, afn):
try:
resp = None
while True:
query = generator.send(resp)
resp = await afn(query)
except StopIteration as e:
return e.value
# Third-party API that provides some sort of filesystem
def xpath(coll, path):
acc = coll
for key in path:
acc = acc[key]
return acc
DATABASE = {"$index": [("folder", "scripts"),("file", "hello_world"),("file", "aaa"),],"$store": {"scripts": {"$index": [("file", "a.py"),("file", "b.py"),],"$store": {"a.py": "# a.py","b.py": "# b.py",},},"hello_world": "HELLO!!!","aaa": "bbb"},}
async def api(path):
await asyncio.sleep(len(path) * 0.05 + 0.05)
try:
data = ("ok", xpath(DATABASE, path))
except KeyError:
data = ("error", path)
# print(f"got {data}")
await asyncio.sleep(0.05)
return data
# Application logic (walking the tree):
def walk(root, callback):
(status, nodes) = yield (root + ["$index"])
for (node_type, name) in nodes:
if node_type == "file":
yield from callback(root + ["$store", name])
if node_type == "folder":
yield from walk(root + ["$store", name], callback)
def recursive_walker():
files = []
def add_file(path):
data = yield path
print(f"path:{path} -> data:{data}")
files.append( (path, data) )
yield from walk([], callback=add_file)
return files
# Running the app:
async def main():
import pprint
files = await run(recursive_walker(), api)
pprint.pprint(files)
asyncio.run(main())
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 | path:['$store', 'scripts', '$store', 'a.py'] -> data:('ok', '# a.py')
002 | path:['$store', 'scripts', '$store', 'b.py'] -> data:('ok', '# b.py')
003 | path:['$store', 'hello_world'] -> data:('ok', 'HELLO!!!')
004 | path:['$store', 'aaa'] -> data:('ok', 'bbb')
005 | [(['$store', 'scripts', '$store', 'a.py'], ('ok', '# a.py')),
006 | (['$store', 'scripts', '$store', 'b.py'], ('ok', '# b.py')),
007 | (['$store', 'hello_world'], ('ok', 'HELLO!!!')),
008 | (['$store', 'aaa'], ('ok', 'bbb'))]
Inversion of control using generators! 
I think it's called dependency inversion or something like that
My business logic (walking the file tree) does not depend on the API, but can still perform powerful operation. That is, the request can depend on the API response.
This also allows for interactive development: you can pretend to be the API and interactively respond to your app's requests.
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
the code works in rafea.py but doesn't in another.py
idk why
i'm using python version 3.7.9 and i'm using Windows 10 1909 if that matters
sorry abt the variable names
lmao, i just realized i should put this in #python-discussion
sorry you lot
@half sigil add a __init__.py file to your main dir
then it will be marked as a package
not sure if you ended up getting this answered in #python-discussion
Can anyone make a code smaller than this but it shud wrk the same
b=lambda a,m:max({1:x}.get(a*x%m,1) for x in range(m))
it shud return the mod inverse of 2 numbers
(Ping me)
b=lambda a,m:max({1:x}.get(a*x%m,1)for x in range(m))``` @sick hound :P
aside from that i don't really know how to make it shorter, it's already pretty short
Yeah lol
@sick hound wdym mod inverse?
i might not be any help cuz i don't even know what mod inverse is
lmao
According to google, it's a number y such that (x*y)%m = 1, for a given input x and a modulo m.
It's the multiplicative inverse in the ring of remainders under division by m :P
There's a short version that unfortunately raises an exception when the answer is one:python b=lambda a,m:pow(a,-1,m)
!e print(pow(1,-1,5))
...?
@stark fable :white_check_mark: Your eval job has completed with return code 0.
1
Oh, I guess it just raises it when the two numbers are coprime.
Aren't coprime? I don't know my modulo very well.
!e
print(pow(3, -1, 2))
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
1
!e python print(pow(4,-1,2))
@snow beacon :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | ValueError: base is not invertible for the given modulus
There we go.
alternatively you could write that as pow(0,-1,2)
Well, 4 % 2 == 0, and there's no such c that (4 * c) % 2 == 1
But to avoid changing the behaviour there, it should return 1.
oh, hm, right
Importing math for gcd is expensive, and it doesn't even give you the condition cheaply.
try/except is a lot of characters because you can't do it in a lambda. And you need two returns.
If only there were an inline try/except.
def b(a,m):
try:return pow(a,-1,m)
except:return 1
this is 52 characters long
the last golfed version seems to be 53 characters long
Oh, that's good.
def b(a,m,x=1):
try:x=pow(a,-1,m)
finally:return x```
This is probably similar length.
it's exactly the same length
def b(a,m):
try:x=pow(a,-1,m)
except:x=1
return x```This is the same length too, I believe.
yep
def b(a,m,x=1):
try:x=pow(a,-1,m)
finally:return x```
@snow beacon Oh wow this is cool
but its not a 1 liner
Wow @stark fable With a slight modification its very short now
b=lambda a,m:pow(a,-1,m) if a%m else 1
!e
b=lambda a,m:pow(a,-1,m) if a%m else 1
print(b(300,232))
print(b(4,2))
@sick hound :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | File "<string>", line 1, in <lambda>
004 | ValueError: base is not invertible for the given modulus
It's whether they are co-prime, not whether one is a multiple of the other.
aah yes
Anyone a fan of functional programming?
I am :P
import math
sin = MyFunction(math.sin)
X = np.linspace(0,4*math.pi,10000)
Y1 = sin@(lambda x:x**2)@X
Y2 = (lambda x:x**2)@sin@X
plt.close()
plt.figure()
plt.plot(X,Y1)
plt.plot(X,Y2)
plt.show()
!eval ```python
from functools import reduce
from operator import add, mul
def compose(*functions):
return reduce(
lambda f, g: lambda x: g(f(x)),
functions,
lambda x: x,
)
def curry(function):
return lambda first: lambda *rest: function(first, *rest)
CtoF = compose(curry(mul)(9/5), curry(add)(32))
FtoC = compose(curry(add)(-32), curry(mul)(5/9))
print(f"{'ยฐC':>10}{'ยฐF':>10}")
for temp in range(-30, 50, 5):
print(f"{temp:>10}{CtoF(temp):>10}")
@river idol :white_check_mark: Your eval job has completed with return code 0.
001 | ยฐC ยฐF
002 | -30 -22.0
003 | -25 -13.0
004 | -20 -4.0
005 | -15 5.0
006 | -10 14.0
007 | -5 23.0
008 | 0 32.0
009 | 5 41.0
010 | 10 50.0
011 | 15 59.0
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/siziyohawu
ohh, interesting
https://paste.pythondiscord.com/goquhojuje.rb here's the definition of the wrapper
Do you like my curry function?
supports functional powers too: sin**4@x is sin(sin(sin(sin(x))))
Hmm, I want to find some more interesting higher-order functions to implement.
It probably should have been this instead:
def curry(function):
return lambda *rest: lambda last: function(*rest, last)
Then currys can be chained together with compose
Like compose(curry, curry, curry)(max)(1)(2)(3)(4)
Hey, would you guys know how to make that shorter?
lambda t:''.join('||'+f+'||'for f in t)
Mhh an f-string should already be shorter, wouldn't it?
lambda t:''.join(f'||{f}||'for f in t)```
lambda t:f'||{"||||".join(t)}||'
lambda t:''.join(f'||{f}||'for f in t)
smart Boi
have I hit #esoteric-python territory yet. ๐ I was just trying to do a simple pandas DF searchpython data_search = [data[data[x].str.contains(y, na=False, case=False)] for x in ('Title', 'description') for y in ('Covid', 'corona')]
nah, I can even read it
yaaa, me too, I came here yesterday, this is amazing
What have I stumbled upon?
also some pretty great python here try running this code:
from datetime import timedelta
print(timedelta(seconds=-1))
!eval
from datetime import timedelta
print(timedelta(seconds=-1))
@ivory parcel :white_check_mark: Your eval job has completed with return code 0.
-1 day, 23:59:59
there really need to be better ways to format time deltas
probably makes it easier to implement
@dense umbra Hey! I was in awe as well...this is a great community
It is, is't it?
currently coding up a program to check if the servers are online in my organization and having a rough time getting this auto email part working ๐ฆ
I expect there are a lot of other channels that can help with that on the server.
Functions with arbitrary numbers of arguments
Wrong way:
def my_sum(*args):
return sum(args)
Right way:
def my_sum_factory(n):
argslist = [f"v{i}" for i in range(n)]
s = f"""global _temp_fun
def _temp_fun({" = 0, ".join(argslist) + " = 0"}):
return {" + ".join(argslist)}"""
#print(s)
exec(s,globals(),locals())
return _temp_fun
my_sum = my_sum_factory(2**32-1)
really though, at n=2**14 it gets a RecursionError: maximum recursion depth exceeded during compilation on exec, and on higher n the Python interpreter crashes.
8192 arguments is perfectly fine, though.
you can press ctrl+k
What do you find annoying about tkinter, pls answer my question at #help-croissant
# a is not in namespace
(a:=6) + a # works
a(a:=print) # NameError, a does not get set
a = str
a(a:=int) # "<class 'int'>"
a() # 0
a = 6
a(a:=8) # TypeError, a does get set
```interesting that calls first resolve name, then evaluate arguments, then check whether the lhs is callable and call it
wonder if there is anything that resolves names not directly before acting upon their values.
huh, this seems := specific
I think of foo(bar) as an operation on foo. It makes sense that foo would need to be evaluated first.
!e ```py
(p:=print)(p)
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
<built-in function print>
!e ```py
(a:=[]).append(a)
print(a)
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
[[...]]
!e
a = (lambda: (a:=[]).append(a))()
print(a)
@fiery hare :white_check_mark: Your eval job has completed with return code 0.
None
!e py (lambda: (a:=[]).append(a))() print(a)
@rugged sparrow :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | NameError: name 'a' is not defined
wait is a placed in a local scope?
Well it is a function, scope and all
hmm, how would i be able to make this shorter?
def solution(a):e,w,n,s=map(a.count,"ewns");return(b==c)*(d==e)*11>len(a)
it needs to return true if e == w n == s and the length of a is shorter than 11
e==w<len(a)<11>n==s
ughhhh
