#esoteric-python
1 messages · Page 88 of 1
@grave rover did you have a switch implementation by any chance
Uhhh
I vaguely remember one
I think it was a collab between me and Laura?
a, b, c = 1, 2, 3
with switch(a, b, c):
with case(lambda a, b, c: a < b < c):
print('ayy 0')
with switch(b, a, c):
with case(2, 1, 3):
print('nested switch!')
with case(1, 2, 3):
print('this wont be printed')
with case(1, 2, 3):
print('ayy 1')
with case(lambda a, b, c: b == 2):
print('holy shit a nested case!')
switch_break()
with case(1, 2, 3):
print('ayy 2')
I can't recall if this handled nested switch statements properly though
@brazen geyser
there was a better one iirc
i thought it mightve been yours
it was really pretty, much cleaner
maybe im trippin
I mean I wrote a bytecode transformer for doing this stuff
But that required an importhook to work globally
You mostly solved it with using a custom exception
I think I might be able to do the same with this one
Gonna need a custom contextmanager tho
ok maybe i was thinking of your suggestion to use with for the switch
i liked my version with the decorators and metaclass
That one is cute as well.
But metaclasses, frankly, frighten me more than they really should.
meta classes really arnt that bad tbh
they seem scary but once you actually make one its not too bad
hello
I'm trying to find the stupidest solution to:
"Print the word 'super' from string 'My dog is the most super duper boy'. Use string indexing."
currently I have
string='My dog is the most super duper boy'
super=string.find('super')
print(string[super:super+len('super')])
but that's not nearly convoluted enough
string = 'My dog is the most super duper boy'
print(f'{string[string.find("super"):]:.{len("super")}}'
```is a bit more convoluted, but it is more a question of how much dead code are you willing to add
true
you can do something like
string.__class__.__dict__.__getitem__.__call__('find').__call__(string, 'super')
```and a similar things with the `__getitem__`
I like that, compact yet complex
hmm
for value in reversed(vars(__import__("builtins")).copy().values()):
try:
assert isinstance(value, type)
value()
except RuntimeError:
for word in "My dog is the most super duper boy".split():
if value.__name__ == word:
print(word)
except:
pass
maybe something like this?
that is clever
what
I don't even
doesn't work for me in a jupyter notebook :/
but whatever it is, I love it
what would be the equivalent of
string.__class__.__dict__.__getitem__.__call__('find').__call__(string, 'super')
but to get the len() of 'super'?
replace that 'find' with 'len' and make that last call __call__('super')
ah ok
I tried replacing the find, but not the other bit
hm, I still get KeyError: 'len'
ah right, you have to do __len__
ok I think I have it
down to a single, perfect line of code
print('My dog is the most super duper boy'['My dog is the most super duper boy'.__class__.__dict__.__getitem__.__call__('find').__call__(string, 'super'):'My dog is the most super duper boy'.__class__.__dict__.__getitem__.__call__('find').__call__(string, 'super')+sum(not out not in out for out in 'super')])
hey guys
You could assemble the slice using slice.
so i made an exe to automate some of my work, but my coworkers wanna use it too but they are on mac
is there a way i can bundle it all up into an app for them?
i dont wanan make them go into the terminal and install the libraries and stuff
This isn't the channel.
@uneven sun #❓|how-to-get-help
is slice different between c++ and python>? isnt that a negative thing to do?
when you put a derived object into a base object
im newish to python so im just asking cause i saw you guys discussing it
This is the channel for doing terrible things to Python.
string = 'My dog is the most super duper boy'
string = [string[i:].startswith("super") for i in range(len(string))]
print(''.join("super"*i for i in string))
foo[a : b : c] = foo[slice(a, b, c)]
What is the most weirdest way to write b if the user enters a number but a otherwise? I have this but I think I can make it better```py
x = (lambda: input)()
if isinstance(x, int):
pass
else:
x = x((3 * '>') + ' ')
try:
x = int(x) ** 2
except:
print('a')
if isinstance(x, int):
print('b')
Actually I gtg so I'll check replies later
lambda x: print("ab"[all(47<ord(k)<58 for k in x)])
This is a cute way to do it.
I know isinstance might be shorter compared to the genexp, but I like the ord.
Y’all ever use the programming language “whitespace”?
It falls under python gore
white space is an abomination cos if you use like c or c++ or somthing then you can write 2 completely different programs in the same file, one in the whitespace and another in c++
Is it Python gore? It's not Python.
Is Java Python gore?
well, it's something gore
but i don't see how this esoteric language is related to python at all
It's still a cool language, and I didn't realise it was made by Edwin Brady. Speaking of whitespace, what sort of programs can we write without using any?
No lambdas with arguments, no def blocks, and almost none of the keywords.
Semicolons will be helpful.
You can recurse with plain lambdas, as well as evaluate ternary conditions (as long as you use the right characters as padding—x if y else z can be converted to [x][0]if[y][0]else[z][0])
Input & output are fine, and you can easily push and pop values off a stack defined in the same scope.
Python with no whitespace is probably Turing-complete.
You can also exec("your$program§".replace("$",chr(32)).replace("§",chr(10)))
exec would be cheating tho
lambda*args:...
Or lambda*,a,b,c:... and maybe lambda/,a,b,c:...
factorial=lambda*b:(lambda*a:a[0](a[0]))(lambda*a:lambda*b:(lambda*c:lambda*d:a[0](a[0])(b[0]-1)(c[0])(c[0](d[0])))if[b[0]][0]else[lambda*a:lambda*a:a[0]][0])(b[0])(lambda*b:lambda*a:a[0](b[0](lambda*a:lambda*a:a[0])(b[0](lambda*a:lambda*b:a[0])(lambda*a:lambda*b:lambda*c:a[0](b[0])(b[0](c[0]))))(lambda*a:lambda*a:a[0]))(lambda*a:lambda*c:b[0](lambda*a:lambda*a:a[0])(a[0])(a[0](c[0]))))(lambda*a:a[0](lambda*a:a[0])(lambda*a:a[0]))(lambda*a:lambda*b:a[0])(lambda*a:a[0]+1)(0)```
python with no whitespace is definitely turing complete if you assume there's no recursion limit since you can use the lambda calculus ^
you code like a sith
What would be the dunder equivalent of converting a string to integer? E.g int("1").
For floats it’s float.__int()__ but doesn’t appear to be this for strings
I think __int__ is for numeric operations.
Like, if two objects don't define __add__, you can still add them if they have __int__ or something
Init signature: int(self, /, *args, **kwargs)
Docstring:
int([x]) -> integer
int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments
are given. If x is a number, return x.__int__(). For floating point
numbers, this truncates towards zero.
***If x is not a number or if base is given, then x must be a string***,
bytes, or bytearray instance representing an integer literal in the
given base. The literal can be preceded by '+' or '-' and be surrounded
by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
Base 0 means to interpret the base from the string as an integer literal.
```int on strings is a special case
That doesn’t answer my question of how it actually works though? Ik strings are a ‘special case’, that’s why I’m asking. Does it maybe use int.frombytes or something?
I expect the int constructor just runs its own C code to parse strings.
Ah, thank you
https://github.com/python/cpython/blob/master/Objects/longobject.c#L2507 I think for strings it is this
ah yes, but most of the internals it uses are in the from string
anyone tried/used this library? https://github.com/ajalt/fuckitpy
That library has this channel's implicit seal of approval, along with forbiddenfruit and that website for making code into a one-liner.
Haha, that's so good
factorial=lambda*b:(lambda*a:a[0](a[0]))(lambda*a:lambda*b:(lambda*c:lambda*d:a[0](a[0])(b[0]-1)(c[0])(c[0](d[0])))if[b[0]][0]else[lambda*a:lambda*a:a[0]][0])(b[0])(lambda*b:lambda*a:a[0](b[0](lambda*a:lambda*a:a[0])(b[0](lambda*a:lambda*b:a[0])(lambda*a:lambda*b:lambda*c:a[0](b[0])(b[0](c[0]))))(lambda*a:lambda*a:a[0]))(lambda*a:lambda*c:b[0](lambda*a:lambda*a:a[0])(a[0])(a[0](c[0]))))(lambda*a:a[0](lambda*a:a[0])(lambda*a:a[0]))(lambda*a:lambda*b:a[0])(lambda*a:a[0]+1)(0)```
Can someone explain to me how this works?
Here is a funny challange:
Python gives syntax warnings if you use a tuple in assert's test case
>>> assert (x, y)
<stdin>:1: SyntaxWarning: assertion is always true, perhaps remove parentheses?
but there are some specific cases where this warning is omitted. Who wants to guess one of these weird cases (with the explanation)?
(assert's test should be a tuple and it should have at least 1 element)
!e
assert (1, 2)
@formal sandal :warning: Your eval job has completed with return code 0.
[No output]
actually the good part is the explanation
!e
import dis
def f():
assert (1, 2)
dis.dis(f)
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 | 3 0 LOAD_CONST 1 ((1, 2))
002 | 2 POP_JUMP_IF_TRUE 8
003 | 4 LOAD_GLOBAL 0 (AssertionError)
004 | 6 RAISE_VARARGS 1
005 | >> 8 LOAD_CONST 0 (None)
006 | 10 RETURN_VALUE
!e
import dis
def g():
assert (x, y)
dis.dis(g)
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 | <string>:3: SyntaxWarning: assertion is always true, perhaps remove parentheses?
002 | 3 0 LOAD_GLOBAL 0 (x)
003 | 2 LOAD_GLOBAL 1 (y)
004 | 4 BUILD_TUPLE 2
005 | 6 POP_JUMP_IF_TRUE 12
006 | 8 LOAD_GLOBAL 2 (AssertionError)
007 | 10 RAISE_VARARGS 1
008 | >> 12 LOAD_CONST 0 (None)
009 | 14 RETURN_VALUE
Maybe it has something to do with BUILD_TUPLE instruction
Because in the first case, it's just loading some constant
Maybe it has something to do with
BUILD_TUPLEinstruction
@formal sandal yep
!e
assert ([],)
@proper vault :white_check_mark: Your eval job has completed with return code 0.
<string>:1: SyntaxWarning: assertion is always true, perhaps remove parentheses?
SyntaxWarning are only generated at compile time, right, so I guess it has to do something with that?
yep
So if the tuple can be constructed at compile time and stored as a constant, it will not raise the warning
!e
def a():
assert (a,)
@proper vault :white_check_mark: Your eval job has completed with return code 0.
<string>:2: SyntaxWarning: assertion is always true, perhaps remove parentheses?
so it just checks for BUILD_TUPLE, rather than checking the type in LOAD_CONST, probably because it is non-trivial to figure out if it is the value of LOAD_CONST is exactly the value passed into the assert
Pretty close
I doubt this is possible, but maybe: can i catch a NameError and replace it with something? so x + 5 gets replaced with something() + 5. all of the exception hooks ive seen dont allow you to return, so i doubt its possible :(
you mean it would retroactively use a different value for the name?
so something like
try:
print(some_name_that_is_not_defined * 3)
except NameError as e:
e.use_instead(9)
```would print 27?
not real code
pretty sure this is not reasonably possible, AFAIK only LISP dialects are capable of this level of self correction
ah okay
i might try modifying the ast, that feels messy though
id rather do it pure python
i might try modifying the ast, that feels messy though
@gentle pagoda actually it is kind a easy, I once write project calledpepallowwhich would re-write some names and suppresses the original errors (it is a very old piece of code, even older than the git date, just to show as an example)
Hello! Well am a novice in python. I have a project that demands me to create an app so I decided to go in for tic tac toe. Am at the level of making the buttons work now i.e the function I need to make the buttons work properly. Am using classes just to note. Need some help please.
this channel is not for that, sorry
<@&267629731250176001>
!ban 287734159546515456 spam
:x: User is already permanently banned (#7813).
ah
Do you want a generator expression?
(x + 1 for x in seq)
Here's an esoteric version.
(lambda: [(yield x + 1) for x in seq])
Won't work in 3.8
yield in lambda tf
yeah that's a thing
SyntaxError: 'yield' inside list comprehension
But then we're using generator expressions
That's the whole thing we're trying to avoid
Wait, and we can't use yield in generator expressions?
you can do
(lambda f, i: f(f, i))(lambda f, i: (yield from (lambda n: ((yield n+1), (yield from f(f, i)))if n is not None else (yield from []))(next(i, None))), iter(seq))
I also got ```python
import('itertools').chain(*[
(lambda i: (yield i))(i)
for i in range(3)
])
Wait
You're using a y-combinator
That works too
!e
seq = [1, 2, 3, 4, 5]
x = (lambda f, i: f(f, i))(lambda f, i: (yield from (lambda n: ((yield n+1), (yield from f(f, i)))if n is not None else (yield from []))(next(i, None))), iter(seq))
print([*x])
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
[2, 3, 4, 5, 6]
respect to people who are into esoteric python
Yield was prohibited in list comprehensions, since it does weird things - you get a generator not a list (exposing a sorta implementation detail), the result of send() is put in the list, then the list itself comes out of the StopIteration exception...
I feel like yield could work just fine
[(yield i) for i in range(3)] is just any part of a function
(yield i) gets evaluated to whatever send gives
and the result is the value of each send
the problem is that comprehensions are implemented as functions.
It doesn't really make sense IMO to use yield in list comp since we have gen expr anyway
What does esoteric mean exactly? Not sure i get what this channel is about
Golfing, Python VM languages, obfuscation, code gore and other general Python weirdness
Ok i dont know what any of those things are, just gonna read you guys
Golfing is making the code as short as possible for example
its basically python that is supposed to make you vomit when you see it, but also works
yeah, we just fuck around with python because it's fun
@thin trout Even then, us esoteric python users would like the feature
!e
__import__('itertools').chain(*[
(lambda i: (yield i))(i)
for i in range(3)
])
@hollow patrol :warning: Your eval job has completed with return code 0.
[No output]
But it's unrealistic
it doesn't make any freakin sense haha
That's the point of this channel
In esoteric Python, nothing ever has to make sense.
I mean, things here have a sense (most of the time)
!e
print(*__import__('itertools').chain(*[
(lambda i: (yield i))(i)
for i in range(3)
]))
@hollow patrol :white_check_mark: Your eval job has completed with return code 0.
0 1 2
and maybe
a lot of times it doesn't
I made a Python one-liner, it doesn't make sense.
!e
f=lambda x:[[y for j,y in enumerate(set(x))if(i>>j)&1]for i in range(2**len(set(x)))];print(f([10,9,1,10,9,1,1,1,10,9,7]))```
@minor palm :white_check_mark: Your eval job has completed with return code 0.
[[], [9], [10], [9, 10], [1], [9, 1], [10, 1], [9, 10, 1], [7], [9, 7], [10, 7], [9, 10, 7], [1, 7], [9, 1, 7], [10, 1, 7], [9, 10, 1, 7]]
I think it finds all subsets, though in a slightly odd way
Oh, I see. It might be better to use sets instead of lists.
I think that would be a syntax error.
There's also a logic error.
I made a Python one-liner, it doesn't make sense.
@hollow patrol it has a sense, its sense is to be in one line :P
huh
So TIL that .__call__ attributes have a .__call__ attribute that's just silly haha
indeed they do
well of course they do. that's what makes the () on the end of .__call__() work haha
it's like how .__str__ has a .__str__ attribute.
that's the power of descriptors which i'm yet to wrap my mind around.
!e
print.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__('Hello call!')```
@thin trout :white_check_mark: Your eval job has completed with return code 0.
Hello call!
That's so silly haha
but it makes sense though
__call__ is callable, which means it needs a __call__ method.
Yes, but my docstring scrapper doesn't like it haha
I wonder how that actually work, are the __call__ generated by the parser?
i think the additional __call__ methods are generated on the fly because of descriptor magic.
Yeah, if you want to call the __call__ you have to call its __call__? Haha
but when you actually call it, the internals don't need to refer to that extra __call__ method
!e
print(type(print.__call__))```
@thin trout :white_check_mark: Your eval job has completed with return code 0.
<class 'method-wrapper'>
Yeaaahh
>>> class A:
... def __str__(self): pass
...
>>> A.__str__
<function A.__str__ at 0x7fa3298480d0>
>>> A.__str__.__str__
<method-wrapper '__str__' of function object at 0x7fa3298480d0>
>>>
these method-wrappers won't have anything you're interested in for your docstring thing
!e
print(print.__call__ is print.__call__.__call__, print.__call__.__call__ is print.__call__.__call__.__call__)
@proper vault :white_check_mark: Your eval job has completed with return code 0.
False False
Yeah, I could ignore those
A dir() parameter to inshore the compiler-generated one's would be nice, though
they're not compiler generated, i believe they're generated by the descriptors at runtime or something
but yeah, i know what you mean.
Is there a dis madness to see how they are generated without looking at the source?
i doubt it since i reckon it's all transparent to the bytecode.
well, not transparent
but invisible
the bytecode probably doesn't have a clue whether they're user-defined or not.
you could use the types library to your advantage though.
!e ```py
from types import MethodWrapperType
class Example:
def str(self):
return "this is an example!"
e = Example()
once = e.str
twice = e.str.str
trice = e.str.str.str
print("once:", isinstance(once, MethodWrapperType))
print("twice:", isinstance(twice, MethodWrapperType))
print("thrice:", isinstance(thrice, MethodWrapperType))
@brisk zenith :x: Your eval job has completed with return code 1.
001 | once: False
002 | twice: True
003 | Traceback (most recent call last):
004 | File "<string>", line 14, in <module>
005 | NameError: name 'thrice' is not defined
fucking
trice!
!e ```py
from types import MethodWrapperType
class Example:
def str(self):
return "this is an example!"
e = Example()
once = e.str
twice = e.str.str
thrice = e.str.str.str
print("once:", isinstance(once, MethodWrapperType))
print("twice:", isinstance(twice, MethodWrapperType))
print("thrice:", isinstance(thrice, MethodWrapperType))
@brisk zenith :white_check_mark: Your eval job has completed with return code 0.
001 | once: False
002 | twice: True
003 | thrice: True
@thin trout if the attribute is an instance of this mystical MethodWrapperType then you should ignore it. there'll be other similar types to look out for too, but you'll just have to experiment to see what types from the types module you should or shouldn't include in your docstring scraper thing.
what is esoteric python
The abnormal or weird or unknown sides of the language
I think __call__ depends on its actual function
since when I used a while loop on it
or some sort of loop
!e
def f():
print(5)
for i in range(5000):
f = f.__call__
f() #throws a recursion error I believe
@hollow patrol :white_check_mark: Your eval job has completed with return code 0.
5
!e
def f():
print(5)
for i in range(105000):
f = f.__call__
f() #throws a recursion error I believe
@hollow patrol :white_check_mark: Your eval job has completed with return code 0.
5
!e
def f():
print(5)
for i in range(5000000):
f = f.__call__
f() #throws a recursion error I believe
@hollow patrol :warning: Your eval job timed out or ran out of memory.
[No output]
I thought it would throw an error
i think descriptor magic makes any amount of .__call__s stringed together just call the original function directly, without having to call each method in the chain
hello beatiful people here, i'm new here and i was wondering why some channels are named after chemical stuff
each name is quite different from the others and there are plenty to go around.
but this also isn't the right channel to ask server-related questions ^^
that sort of stuff is best over in #community-meta :)
idk, a few years by now.
!e
!eval [code]
Can also use: e
*Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code
block. Code can be re-evaluated by editing the original message within 10 seconds and
clicking the reaction that subsequently appears.
We've done our best to make this sandboxed, but do let us know if you manage to find an
issue with it!*
soo I'm editing a photoshop file using win32com.client
PS = win32com.client.Dispatch("Photoshop.Application")
and I used a page with some simple guides to do it so far but it doesn't tell me everything, does anyone know where I can find a full docs ofr this
not sure this is the channel for that, G-Unit
!e ```py
def my_function():
print("hi!")
exec(f"my_function{'.call' * 2991}()")
@midnight bane :white_check_mark: Your eval job has completed with return code 0.
hi!
!e ```py
def my_function():
print("hi!")
exec(f"my_function{'.call' * 2992}()")
@midnight bane :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 4, in <module>
003 | RecursionError: maximum recursion depth exceeded during compilation
That's from the fact that there's so many nested attribute calls.
Break it up into two lines.
!e ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
@stark fable :x: Your eval job has completed with return code 1.
001 | s_push: parser stack overflow
002 | MemoryError
yep
one more reason to use pypy, lol
Maybe it will be fixed in the new parser, though.
I guess it's a bit off topic, but maybe we can do something similar in Python?
https://github.com/Battelle/movfuscator
It's a C compiler for x86 architecture that produces machine code containing only mov instructions.
I don't know if Python has this sort of robust instuction (or 2-3 instructions)
Maybe our attempts at reimplementing stdlib in pure python weren't in vain!
(I mean, in a warped and crazy way of not in vain)
@formal sandal i think something like that could be quite doable with a very very limited set of bytecode instructions
i think something that converts bytecode made by cpython's standard compiler into the limited bytecode version would be a good first step, perhaps.
i imagine the movfuscator uses movs to change the program counter register for dealing with control flow, but i don't imagine anything in python bytecode can do that beyond the dedicated instructions
(i haven't actually looked at the movfuscator, but i'm just going by what my intuition thinks)
nums = [0,1,2,3,0,0,2,3,4,0,2,5,3,3,4,1,0]
converter = lambda x: [n for n,e in zip(x,map(lambda y:y%2==0,x)) if n and e]
print(converter(nums))
```is there a better/faster way than my 'converter' variable to get all numbers in a list that are even and not 0?
!e ```py
def m1():
nums = [0,1,2,3,0,0,2,3,4,0,2,5,3,3,4,1,0]
converter = lambda x: [n for n,e in zip(x,map(lambda y:y%2==0,x)) if n and e]
return converter(nums)
import timeit
print(timeit.timeit(m1))
@last locust :white_check_mark: Your eval job has completed with return code 0.
5.766138376668096
Ultimately trying to get it under 5secs, but every little helps
that seems overly complicated
that seems overly complicated
@edgy kelp Isn't that the whole channel purpose?
Wanted to use map, and adding the zip seemed the easiest way to implement that
converter = lambda x:[*filter(lambda n:n and n%2==0,x)]
``` @last locust this works
if you want to use map then you can just drop the zip and return the original value in the lambda
!e ```py
def m1():
nums = [0,1,2,3,0,0,2,3,4,0,2,5,3,3,4,1,0]
converter = lambda x: [*filter(lambda n:n and n%2==0,x)]
return converter(nums)
import timeit
print(timeit.timeit(m1))
@last locust :white_check_mark: Your eval job has completed with return code 0.
4.172575471922755
Nice 👍
Forgot about filter
And yea true @edgy kelp. Honestly just messing around with different methods
one more reason to use pypy, lol
@formal sandal or wait the new PEG parser :)
!e ```py
def m1():
nums = [0,1,2,3,0,0,2,3,4,0,2,5,3,3,4,1,0]
converter = lambda x:[n for n in x if n and n%2==0]
return converter(nums)
import timeit
print(timeit.timeit(m1))```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
2.4834218118339777
@last locust ^
ahh ok
Really like your filter one though
you want obscure? give me a moment.
converter = lambda x:[n for n in x if f'{(n if n else 1)/2}'[-1]=='0']```
@last locust ^
checks if the last digit of a float is 0 and replaces n with 1 if its falsy (0)
Is there some example of a list comprehension which is orders of magnitude more obscure than a composition of higher-order functions?
!e ```py
def m1():
nums = [0,1,2,3,0,0,2,3,4,0,2,5,3,3,4,1,0]
converter = lambda x:[n for n in x if f"{(n if n else 1)/2}"[-1]=="0"]
return converter(nums)
import timeit
print(timeit.timeit(m1))```
@last locust :warning: Your eval job timed out or ran out of memory.
[No output]
🤔
Pretty fast
Lmao it was way slow
It's about 13sec o-o
I'm confused
Same lol
!e
def m1():
nums = [0,1,2,3,0,0,2,3,4,0,2,5,3,3,4,1,0]
converter = lambda x:[n for n in x if f"{(n if n else 1)/2}"[-1]=="0"]
return converter(nums)
print(m1())
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
[2, 2, 4, 2, 4]
!e ```py
def m1():
nums = [0,1,2,3,0,0,2,3,4,0,2,5,3,3,4,1,0]
converter = lambda x: list(filter(range(2,max(x)+1,2).contains,x))
return converter(nums)
import timeit
print(timeit.timeit(m1))
not efficient, but funky.
hold on, lemme retry
!e ```py
def m1():
nums = [0,1,2,3,0,0,2,3,4,0,2,5,3,3,4,1,0]
converter = lambda x: list(filter(range(2,max(x)+1,2).contains,x))
return converter(nums)
import timeit
print(timeit.timeit(m1))
@brisk zenith :white_check_mark: Your eval job has completed with return code 0.
5.5626190751791
Nice
app
app.py
tenant1
__init__.py
blueprints.py
with open("tenant1/config.json) as file:
config = json.loads(file.load)
how do i let blueprints.py read the config variable
i've tried from tenant1 import config but it didn't work
just read the file again
thats inefficient
i imagine the movfuscator uses movs to change the program counter register for dealing with control flow, but i don't imagine anything in python bytecode can do that beyond the dedicated instructions
iirc what it actually does is it's a series of movs and then one unconditional jump back to the beginning of the program
well that's what's described in this paper at least https://drwho.virtadpt.net/files/mov.pdf
one unconditional jump to the beginning, stopping the program is done by reading from address 0
haha, that's how all of my programs stop too 🙃
I still want to learn how to make a function that maintains its parent's scope
Without any nonlocal, local, or global definitions
you'd have to modify the function's __code__ object in some way.
yeah but I'm not sure how
I can edit the co_code but the rest of the function won't line up
i'm poking around at it right now
by the way
i don't think co_code would be the first place i'd go for
if you manage to do this, you can complete my onelinifier for python
since allowing try-except loops in the parent scope would finish this
modifying stuff like co_names and attributes like that would be my first step
like, retain it
you already have parent's scope?
and you just want to write it into the current function?
I want to people to set variables in the parent scope from a lower scope
is this just the first parent?
the parent right above
okay cool
and I want it to work for nested parents
so you only have control of the parent, and arbitrary child
so essentially you want it to make everything inside it nonlocal automagically
or the inverse, where the child reaches up
yep
basically
w..which one is yep
everything is a nonlocal
ah
i think it would be reasonable to have it accessible via something like this: py def outer(): x = 1 @use_parent_scope def inner(): x = 3 return inner() outer()
that way the inner function's __code__ object can be modified every time it is created (since inner doesn't exist until it is defined at each outer call).
actually
naturally :D
but you don't have to worry about that
what do you want to use this for
for my one-lineifier
what one-lineifier
which one-lines Python 3.8 code
yes
it already works for the most part
with functions, for loops, while loops, if statements, classes, etc
even generators
while True:
for i in range(3):
print(i)
is converted to
(
(
do_while := (
lambda cond, c=0: (
(((yield c), (yield from do_while(cond, (c + 1)))) if cond() else None),
)
)
),
[
([(print(i), None)[(-1)] for i in range(3)], None)[(-1)]
for _ in do_while((lambda: True))
],
None,
)[(-1)]
i would probably say that it's probably easier to tweak the lambda calculus than muck around with the frame
so what
i still think you should just handle scoping manually
probably, and it would be easier
but using the parent scope would be isolated to one part of the code
and it would make the rest much cleaner
the python 2 onelineifier is basically just a lambda calculus-ified version of each bit of python syntax
x := 3 is much cleaner than d.__setitem__('x', 3)
not if it requires func object modifications
how dya intend to do try: except: blocks
with contextlib
ContextDecorators @quiet niche
I need it to implement every python variable thing
so instead of f(1, 2, 3, 4)
it's f({'x': 1, 'y': 2, 'a': 3, 'b': 4})
except it's merged with the original scope
and if the outer scope has a variable, this one won't see it
and etc
replace references to variables with instance variables of a big honking singleton 
regardless, i think python's lexical scoping rules make it essentially impossible without cheating in some form of source-code-rewriting
that's why we have to modify bytecode
if you're modifying bytecode you might as well just do source code rewriting in python directly and save yourself the trouble 
rebuilding functions from disassembled objects OTF is a wacky game
bytecode modifications are probably necessary, yes. you'll have to change co_varnames, co_freevars, and probably a couple more attributes for both the inner and outer functions' __code__ object, and then modify the bytecode itself to reflect those changes (but at least then you're not dealing with misaligned jump destinations, just directly swapping out LOAD instructions with other LOAD instructions with different indices for the different variable types)
I'm not sure how to do that though
well i'm not either to be honest haha
i've been comparing these attributes between functions with no scope sharing, and then the exact same thing with everything shared from the parent to the child through nonlocal
actually i bet pycell_set could do something
you probably roughly want cells
but down that path lies madness
I sort of want it to be implementation-independent
heh
heh
just wait until python 4 when we dont have language intrinsics anymore : ^ )
switch to ruby
imagine not being able to overwrite variable assignment 
I'm being serious 😆
generally though, how would I do it
also, can I yield in the higher function too?
you have (cross-platform, doesn't require cheating, doesnt require incredibly bytecode expertise), probably pick 2
if you want to modify bytecode, here is what you need:
by making everything nonlocal, it seems like the parent moves all of its co_varnames into its co_cellvars, and any variable name which is present in the parent's new co_cellvars is moved into the child's co_freevars, with the same variable names being removed from the child's co_varnames if present. i haven't checked what happens with co_names yet. i actually don't know what that contains, really.
then you just need to turn all of the LOAD_FAST calls in the bytecode into the equivalent LOAD_CLOSURE instructions, as well as probably some other similar changes that i'm yet to figure out.
bear in mind that bytecode is a cpython implementation detail.
oh well, I guess I'll stick with bytecode then
im excited for this in 3.9 https://www.python.org/dev/peps/pep-0554/
@brisk zenith how can I yield in the higher function?
yeah bytecode is cheat
cause itll prob let us mod the current interpreter
ah yes
!pep 554
good ol pep 554
but i want to implement multiple languages in my python
@hollow patrol can you give an example of what you're trying to do?
haha okay
i'm not too sure about how you'd do that, really.
same
oh fun, cpython isn't happy when you try to add more free variables to a closure.
yeah, lots of fun likely
well, on another topic, I made an iterator class and made its methods get added to every python object
for c, (before, current, after) in range(10).context(count = 2).enumerate():
print(c, '-', before, current, after)
Output
0 - 0 1 2
1 - 1 2 3
2 - 2 3 4
3 - 3 4 5
4 - 4 5 6
5 - 5 6 7
6 - 6 7 8
7 - 7 8 9
i believe adding more free variables to a function would require one of two things:
- overwriting the tuple's length value in memory using
ctypes. this would be likely to cause some sort of memory violation or buffer overflow somewhere along the line. - changing the
co_freevarspointer value in the struct to make it refer to the new appropriately-sized tuple. this could cause memory leaks and probably memory violations, as well as potential dangling references in the interpreter.
tl;dr: don't do. it bad.
that's true enough.
i'll consider working on that soon then, i'm tired.
have you ever seen a code object being constructed in python code? it's terrifying.
nope I haven't, but I believe you
that _patch_code function would come in handy for this.
As of Python 3.8, CodeType now has a replace() method for copying and changing just some attributes.
yep, but that produces an error when trying to replace co_freevars with a tuple which is longer or shorter than the previous
@brisk zenith if you replace everything else that freevars depends on at the same call it doesn't error afaik
It doesn't look like it should?
the C code behind it compares the tuples sizes with the python api
One time I made something called javar in Python
Basically it makes your code require a single class, and it is given attribute security
I still like the idea of a switch case in Python
with switch(3):
with case(1):
print(5)
with case(2):
print(4)
with case(3):
print(3)
with case(ELSE):
print('none')
I saw discussion about it a few days/weeks ago
Did anyone finish it?
why with case(ELSE), I would do with default()
I don't remember what strategy was used though
@hollow patrol have you tried using dicts instead?
that doesn't work with function bodies as cleanly
mmm, I don't fully follow. I see the example above as
ARG = {1: 5, 2: 4, 3: 3}
print(ARG.get(3, "none"))
@marsh totem that's one example
def f():
with switch(3):
with case(1):
print(5)
with case(2):
print(4)
raise (yield 2)
with case(3):
print(3)
with case(ELSE):
print('none')
out = 5 + 4
while out < 20:
out += 1
for i in range(out):
print(i)
print(out)
I'm not so sure you can one-line this
gotcha
yeah, you might need to extract stuff into helper functions
so that you end with something like:
def default():
#long function
ARG = {1: foo(5), 2: bar(4), 3: baz(3)}
ARG.get(x, default())
how about each of those
I don't want to do ARG = {1: f1, 2: f2, 3: f3} ARG.get(x, default)()
I think that from what you just posted, that's the way to go
I'v used that form before, with nicer names
like
processors = {1: f1, 2: f2, 3: f3}
processor = processors.get(x, default)
result = processor()```
at that point I think it's a matter of taste 🙂
Unrelated, but here's a fun little thing I made:
In [1]: for i in 0-to-10-by-2:
...: print(i)
...:
0
2
4
6
8
In [2]:
Also:
In [3]: for i in 0-to:
...: if i > 100:
...: break
...: print(i)
...:
:^)
You know, just in case you wanted more natural-language syntax in python. (See: word for word in words if word not in swears)
All I have to say is "word."
is it a wrapper around range, or something else?
Presumably it couldn't do an infinite range.
The to suggests it's making its own iterator.
It's a custom implementation of range to allow for infinite iteration.
The iterator portion is trivial, though. Most of the code is in __sub__ and __rsub__ for the syntax trickery.
Ignore the inconsistency between positional args and kwargs.
I wonder whether other builtins could be "naturalized" like so.
len(x) <=> count-of-x
I guess that if you run it through a code formatter it's transforming it to 0 - to - 10 - by - 2
Yes, hence the overridden __sub__.
You could probably also make use of __contains__ to make even more natural-sounding syntax.
n in binary <=> bin(n)
That's interesting
Unrelated, but here's a fun little thing I made:
In [1]: for i in 0-to-10-by-2: ...: print(i) ...: 0 2 4 6 8 In [2]:
@earnest wing is that valid python syntax? Or some sort of preprocessor?
I think I see how that could be done with operator overloading but that's still quite cool!
Would generator-by-2 work on any generator?
The current implementation is pretty limited (https://mystb.in/raw/fofolasado) but surely that could be possible (see the __rsub__ section with _state == 1)
Quick question, how does python know whether to use a.__sub__(b) or b.__rsub__(a) for a-b?
If __sub__ returns NotImplemented, the interpreter tries __rsub__.
The same for any __r*__ operation.
Yeah, it means that __rlshift__() is in fact a valid special method :^)
have overloaded that method a few times even
also __rrshift__
Would you know a way to override the list type returned by [] to a custom one?
From what I can see, it will always use the BUILD_LIST instruction
Well, you could rewrite bytecode...
BUILD_LIST -> BUILD_LIST + (call __list_builder__)
maybe you could do some crazy stuff with ctypes?
Hmm, how would that work, rewriting the bytecode ?
You'd have to apply a decorator to every function, though.
I'm not sure it would work if you change it globally, since pure-python stdlib modules might break
Hmm 
And if the new list implements the whole legacy list functions, is there at least a way to patch the bytecode globally
Depending on the interpreter implementation you might be able to patch compile
this channel is for discussion of doing really really weird things with python that you would never actually use in practice
like this implementation of factorial py factorial = lambda b:(lambda a:a(a))(lambda a:lambda b:(lambda c:lambda d:a(a)(b-1)(c)(c(d)))if b else lambda a:lambda a:a)(b)(lambda b: lambda a:a(b(lambda a:lambda a:a)(b(lambda a:lambda b:a)(lambda a:lambda b:lambda c:a(b)(b(c))))(lambda a:lambda a:a))(lambda a:lambda c:b(lambda a:lambda a:a)(a)(a(c))))(lambda a:a(lambda a:a)(lambda a:a))(lambda a:lambda b:a)(lambda a:a+1)(0)
the basic idea is that it's using church numerals, which is a way of representing numbers as functions
ah so it's lambda calculus basically
yes
lambda calculus implementation of factorial, with some stuff around it to convert to and from python integers
do you pass it an integer or church numeral?
you pass an integer
(lambda a:a(a))(lambda a:lambda b:(lambda c:lambda d:a(a)(b-1)(c)(c(d)))if b else lambda a:lambda a:a) converts from an integer to a church numeral
the (lambda a:a+1)(0) at the end converts it back
ok I can kind of see how that works
this is the textbook definition of esoteric lmfao
lambda a:a(lambda b: lambda a:a(b(lambda a:lambda a:a)(b(lambda a:lambda b:a)(lambda a:lambda b:lambda c:a(b)(b(c))))(lambda a:lambda a:a))(lambda a:lambda c:b(lambda a:lambda a:a)(a)(a(c))))(lambda a:a(lambda a:a)(lambda a:a))(lambda a:lambda b:a) is the actual factorial part, which operates on church numerals
though actually it might not appear in that form in the finished thing since i reduced it a bit
that part I have no clue how it works
well it's made of a lot of separate things
I feel like an explanation will fly over my head tho tbh
zero is lambda a:lambda a:a, and one is lambda a:a
add_one is lambda a:lambda b:lambda c:a(b)(b(c))
hold up shouldn't one be lambda a:lambda b:a(b)?
lambda a:lambda b:a(b) is the same as lambda a:a
wait nvm that's the same as lambda a:a right
add is lambda a:a(add_one) which becomes lambda a:a(lambda a:lambda b:lambda c:a(b)(b(c))) when you substitute in add_one
a is the number you're adding 1 to
b is the function that's repeated
c is the initial argument
you do a(b) to repeat b a times
and then you apply one extra b
to c
ok I may be misunderstanding the purpose of add_one
it adds one to a church numeral
yes, it adds one
oh wait I see!
although it's with church numerals, not python integers
well add_one isn't a number, but the thing it returns is
yea that's what I meant
after invoking it once
then it needs to be a church numeral
yep makes sense
how does it all tie in to factorial?
badly phrased, I know "how" they are related, but not how to implement factorial finally
well there are a few other things we need for factorial
firstly, we need pairs
pair is lambda a:lambda b:lambda c:c(a)(b)
first is lambda a:lambda b:a and second is lambda a:lambda a:a
then once we've got that, factorial ends up as lambda n:n(lambda p: pair(mult(p(first))(p(second)))(add_one(p(second))))(pair(one)(one))(first)
@rare yarrow
Yes, that's the same thing
Because they can encode booleans.
(condition)(then-value)(else-value)
I made a (almost) lambda calculus interpreter some time ago, it has an example with Barendregt numerals, which are close to Church numerals https://repl.it/@int6h/GlorifiedLambdaCalculus#EXAMPLES/barendregt_numerals.lambda
lol
I have no idea why I did that, you can also do fst = (rename fst true)
🐍 class Foo:
•• @classmethod
•• @property
•• def foo(cls):
•• return 1
••
🐍 Foo.foo
<bound method ? of <class '__main__.Foo'>>
pretty sure i just broke the descriptor protocol lol
!remind 10h look for your fluent python book and learn about damn descriptors for fucks sake <3
Your reminder will arrive in 10 hours!
Better not specify minutes...
haha, yeah i'd like to receive the reminder this year :D
@brisk zenith
Here's your reminder: look for your fluent python book and learn about damn descriptors for fucks sake <3.
Jump back to when you created the reminder
can relate
!e from future import braces
@minor palm :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | SyntaxError: not a chance
!e from future import braces
@thin trout :white_check_mark: Your eval job has completed with return code 0.
https://github.com/NeKitDS/braces.py
perfection
Would it be unreasonable to propose a collaborative project for #esoteric-python?
I don't think it would be, there was esoteric challenges after all before
It would be a good fit for a user event too
ooh i've had that sort of idea before, i think it would be super fun to arrange.
Would it be better to do something with lots of different pieces that people can put their own spin on, or one bit of code that everyone overcomplicates?
Why is everyone talking about my version of braces haha
it completely fucks up the lines as of now
I mean their numbers
maybe every month there could be a new esoteric project that everyone could work on on github
suggestion: a library to help with creating #encoding: xyz things
I've been thinking about creating an esolang. It would look like a completely normal language at the first glance, but it has so many inconsistencies and weird features that it's practically impossible to create a more or less meaningful program with it.
I have a small draft which covers some of its features shallowly: https://gist.github.com/decorator-factory/067932affa54488627d7913be11a4e2a
Maybe someone would find that project interesting, because it's so massive that I probably won't manage it on my own
I wrote the gist to give you an idea of the weirdness level.
Hello i need help. I am new to coding python and i have a starting project as coding a bot that could paste a text and tag a person and post the text too. The bot works great when just typing the text and posting it. What the bot is failing to do is to tag a person. Please could someone help me with this thanks!.
wrong channel
this is the channel where people mess around with python and do things like this py factorial = lambda b:(lambda a:a(a))(lambda a:lambda b:(lambda c:lambda d:a(a)(b-1)(c)(c(d)))if b else lambda a:lambda a:a)(b)(lambda b: lambda a:a(b(lambda a:lambda a:a)(b(lambda a:lambda b:a)(lambda a:lambda b:lambda c:a(b)(b(c))))(lambda a:lambda a:a))(lambda a:lambda c:b(lambda a:lambda a:a)(a)(a(c))))(lambda a:a(lambda a:a)(lambda a:a))(lambda a:lambda b:a)(lambda a:a+1)(0)
if you want actual help then look in #❓|how-to-get-help
suggestion: a library to help with creating
#encoding: xyzthings
@gilded orchid we already have one 😎 BRM
https://stackoverflow.com/a/482200/9926281
anyone got an opinion on this?
It puts some much-needed fun into Stack Overflow.
!e print(exit.dict)
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
{'name': 'exit', 'eof': 'Ctrl-D (i.e. EOF)'}
!e print(exit.dict['eof'])
@hardy falcon :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | AttributeError: 'Quitter' object has no attribute 'dict'
🙃
@thin trout :white_check_mark: Your eval job has completed with return code 0.
Ctrl-D (i.e. EOF)
if os.sep == ":":
eof = "Cmd-Q"
elif os.sep == "\\":
eof = "Ctrl-Z plus Return"
else:
eof = "Ctrl-D (i.e. EOF)"
class Quitter(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return "Use {}() or {} to exit".format(self.name, eof)
def __call__(self, code=None):
# Shells like IDLE catch the SystemExit, but listen when their
# stdin wrapper is closed.
try:
sys.stdin.close()
except:
pass
raise SystemExit(code)
builtins.quit = Quitter("quit")
builtins.exit = Quitter("exit")
Which OS uses : 
according wikipedia, Classic Mac OS and Apple's GS/OS
A path, the general form of the name of a file or directory, specifies a unique location in a file system. A path points to a file system location by following the directory tree hierarchy expressed in a string of characters in which path components, separated by a delimiting ...
i can't seem to see any part of cpython which uses os.sep = ":" anymore
looks like it's a bit different in my venvs (some outdated version?)
normal installs use
if os.sep == '\\':
eof = 'Ctrl-Z plus Return'
else:
eof = 'Ctrl-D (i.e. EOF)'
and the QUitter looks the same but is defined in a separate module and eof is passed as an instance var
remimds me of
if 3/2 == 1:
input = raw_input
@frozen holly What a beautiful peace of code 😂
shamlessly stolen from here
https://github.com/AceLewis/my_first_calculator.py/blob/master/my_first_calculator.py
which is also a beautiful peice of code
@frozen holly funnily enough, there was another "my_first_calculator" program I saw recently which also had to do with input on python2
it was from a CTF contest
relevant code:
#!/usr/bin/env python2.7
try:
print("Welcome to my calculator!")
print("You can add, subtract, multiply and divide some numbers")
print("")
first = int(input("First number: "))
second = int(input("Second number: "))
operation = str(raw_input("Operation (+ - * /): "))
# red herring terrible code to calculate the answer
except ValueError:
pass
note that it is python2.7
there's a flag.txt on the server but it's pretty easy to even get a root shell
My solution was to enter ||__import__('subprocess').call(['cat','flag.txt'])|| for the first prompt
I'm actually curious if there are any other solutions
!e ```python
import inspect
print(inspect.getsource(exit.class))
@midnight bane :white_check_mark: Your eval job has completed with return code 0.
001 | class Quitter(object):
002 | def __init__(self, name, eof):
003 | self.name = name
004 | self.eof = eof
005 | def __repr__(self):
006 | return 'Use %s() or %s to exit' % (self.name, self.eof)
007 | def __call__(self, code=None):
008 | # Shells like IDLE catch the SystemExit, but listen when their
009 | # stdin wrapper is closed.
010 | try:
011 | sys.stdin.close()
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/usililojoh
Where was the quitter that used os.sep from
(lambda response: (lambda word, definition: print(f'Random Word: {"".join(word)}', f'Definiton of {"".join(word)}: {"".join(definition)}', sep='\n'))([item.text for item in __import__('bs4').BeautifulSoup(response.content, 'lxml').find_all('div', {'id': 'random_word'})], [item.text for item in __import__('bs4').BeautifulSoup(response.content, 'lxml').find_all('div', {'id': 'random_word_definition'})]))(__import__('requests').get('https://randomword.com/'))``` random word
(lambda response: print(f"Top 10 synonyms for your word are {', '.join([item.text for item in __import__('bs4').BeautifulSoup(response.content, 'lxml').find_all('a', {'data-linkid': 'nn1ov4'})][0:9])}"))(__import__('requests').get(f'https://www.thesaurus.com/browse/{input("Find synonym for: ")}'))```
10 synonyms of a word
since we had some nice ctypes.Structure wrapper with annotations, I thought, why not do the same with functions? ```py
import ctypes
import functools
from typing import Any, Callable
FuncPtr = ctypes._CFuncPtr
def func_def(func_ptr: FuncPtr) -> FuncPtr:
def wrap(func: Callable) -> Callable:
try:
annotations = func.annotations
except AttributeError:
pass
else:
return_type = annotations.pop("return", None)
if return_type:
func_ptr.restype = return_type
arg_types = list(annotations.values())
if arg_types:
func_ptr.argtypes = arg_types
@functools.wraps(func)
def handle_call(*args) -> Any: # do not support keywords yet
return func_ptr(*args)
return handle_call
return wrap```
kernel32 = ctypes.WinDLL("kernel32.dll")
@func_def(kernel32.ReadProcessMemory)
def read_process_memory(
handle: wintypes.HANDLE,
base_address: wintypes.LPVOID,
buffer: wintypes.LPCVOID,
size: ctypes.c_size_t,
size_ptr: ctypes.POINTER(ctypes.c_size_t),
) -> wintypes.BOOL:
pass``` usage is pretty straightforward
what ways are there to compile a python package into a single file . The use case is a jupyter notebook attached to a tiddlywikky file
Is this really the channel for that?
Well, if you create an entire operating system in Python, then you can simply create all the necessary files inside of it and then run the interpreter.
You could probably fit all of the code at the end of a PNG file.
I couldn't get the one in the github repo to work, but it's probably possible.
Just be careful to account for the huffman encoding.
@signal matrix python allows for running zip files that have a __main__.py file in them
i say running because it really just decompresses on the fly
@gritty gull wrong channel
@snow beacon you can create a python runnable png file by doing cat png_file.png python_package.zip > target.png
then just python target.png
@rugged sparrow I was thinking about a way to prevent this folder from being 30,000 files and you just solved my issue with packaging some stuff simply by mentioning ZIPFILE omfg I am stupid
Im making a portable anaconda/tiddlywiki/jupyter/stuff folder setup and its at 10 gigs and about 32,000 files... you can just read the zip contents and pull a single file out with a script without having to decomppress the entire archive right?
i think theres some sort of partialunzip
nice, thanks. I hope what I am tryingto make works, that would be neato to have an anaconda/cmdr/nuikta/jupyter portable development environment I can use for learning and keeping all my stuff in the same place
I want to make it entirely in a chrome browser with selenium and jupyterlabs and tiddlywiki with cmdr for finicky stuff
is this obfuscation? https://github.com/somedude3483/encrypt-a-string/blob/master/combined_code.py
yes.
__import__('builtins',level=False).__dict__['type'] is just a really round-about way of saying type
!e ```py
x = import('builtins',level=False).dict['type']
y = type
print(x == y, x is y)
@brisk zenith :white_check_mark: Your eval job has completed with return code 0.
True True
Well I tried to make it looks as bad as possible
is there a way to get an actually portable, non-install version, of anaconda on windows? I want to just have a folder I can image and carve for modifications and portability.
I just wrote this to get around an irritating url format issue as a workaround:
self.raw_url[self.raw_url.index("/dur/"):self.raw_url.index("/dur/")+18][len("/dur/"):].partition("/")[0]
Cleaned up:
data = collections.defaultdict(list)
for match in re.finditer(r"/([^/]+)/([^/]+)", working_url):
data[match.group(1)] += match.group(2).split(",")
for when someone takes your beautiful https://example.com/sharing?name=bob&source=utm_campagin&dur=15&share_link=1233 standard urls and turns them into this: https://example.com/sharing/name/bob/source/utm_campaign/dur/15/share_link/1233
!e ```py
import re
from collections import defaultdict
from urllib.parse import parse_qs, urlparse
url_1 = "https://example.com/sharing?name=bob&source=utm_campagin&dur=15&share_link=1233"
url_2 = "https://example.com/sharing/name/bob/source/utm_campaign/dur/15/share_link/1233"
print(parse_qs(urlparse(url_1).query))
data = defaultdict(list)
for match in re.finditer(r"/([^/]+)/([^/]+)", url_2[len("https://example.com/sharing"):]):
data[match.group(1)] += match.group(2).split(",")
print(dict(**data))
@distant wave :white_check_mark: Your eval job has completed with return code 0.
001 | {'name': ['bob'], 'source': ['utm_campagin'], 'dur': ['15'], 'share_link': ['1233']}
002 | {'name': ['bob'], 'source': ['utm_campaign'], 'dur': ['15'], 'share_link': ['1233']}
At least they fixed the spelling.
One very annoying thing about recursion is that when you change the name of a function, you have to change it everywhere in its body. But not all is lost!
!e
from functools import wraps
_Y_STACK = []
def y():
return _Y_STACK[-1]
def rec(f):
@wraps(f)
def decorated(*args, **kwargs):
_Y_STACK.append(f)
try:
return f(*args, **kwargs)
finally:
_Y_STACK.pop()
return decorated
@rec
def factorial(n):
if n <= 0:
return 1
else:
return n * y()(n - 1)
print(factorial(42))
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
1405006117752879898543142606244511569936384000000000
I believe you can do something similar to emulate this from JavaScript, but I'm not that evil.
(I screwed up -- it should be _Y_STACK.append(decorated) instead of _Y_STACK.append(f))
hey
There's an interactive playground for lark-parser now!
https://lark-parser.github.io/lark/ide/app.html
!e ```py
import dis
def rec(f):
f.code = f.code.replace(
co_consts=f.code.co_consts + (f,)
)
idx = f.code.co_consts.index(f)
bcode = bytearray(f.code.co_code)
for i,c in enumerate(bcode.copy()):
if c in [dis.opmap['LOAD_GLOBAL'], dis.opmap['LOAD_NAME']] and f.code.co_names[bcode[i+1]]=='this':
bcode[i] = dis.opmap['LOAD_CONST']
bcode[i+1] = idx
f.code = f.code.replace(
co_code = bytes(bcode)
)
return f
@rec
def factorial(n):
if n <= 0:
return 1
else:
return n * this(n-1)
print(factorial(42))```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
1405006117752879898543142606244511569936384000000000
@formal sandal i am that evil ^
You are that evil...
Can you make this work so that when you run it in the top-level, this is None, but when you run it in an object belonging to a special @thisable/Thisable class, this will be the instance of the object we're currently in?
making this a function would make that relatively trivial withinspect
otherwise it would need to be a wrapped func/class
would just need to make the wrapping loop for classes
@formal sandal Would it not do that with a simple this = None at the top level?
Well, you'll still have to implement getting the context inside an arbitrary function
I'm gonna try to make it in Haskell
That would be some weird twist on State
does this belong here
(lambda main: main(__import__('builtins').__dict__['dict'](add=lambda x, y: x + y, subtract=lambda x, y: x - y, multiply=lambda x, y: x * y, divide=lambda x, y: x/y)))(lambda run:__import__('builtins').__dict__['print'](run[input('>>> add, subtract, multiply, or divide ').lower()](__import__('builtins').__dict__['int'](input('Num 1: ')), __import__('builtins').__dict__['int'](input('Num 2: ')))))```
I tried making is as bad as possible
https://github.com/snoack/python-goto just found this
Hey here, can someone explain me why True and False don't take as much memory ? Seems quite bizzare to me 😄 https://cdn.discordapp.com/attachments/294545049021186051/720734233055854602/unknown.png
idk why as such but they both just take twice as much as their integer counter part ```python
from sys import getsizeof
getsizeof(0)
12
getsizeof(1)
14
Luck boy
>>> from sys import getsizeof
>>> getsizeof(0)
24
>>> getsizeof(1)
28
what are you running on ? I want 12-bytes booleans too !
oh
maybe I got it? 🤔
maybe it has something to do with the implementation of bigints.
dunno…
let's grep cpython's source code for True and False to find out ! 😄
wait, why are my ints different sizes? mine was on 3.6 i think, maybe they changed it in more recent versions?
It seems that zero has zero "blocks"?..
Yep
Each "digit" is 32 bits (of space) long, and zero just has 0 digits
put this way, it seems logical
and as bool is a subtype of int, it makes sense.
Thanks for the answer, anyway !
@vague hearth you used 32-bit python
so I did, didn't notice thx, was confused
Dear Reader, I'm sorry in advance, but this will be a long one!
!e
import gzip;import base64;exec(gzip.decompress(base64.b85decode(b'ABzY8&LZPp0{^8|+m6~W5Pi>AjCdiTl)j@b+Fn-Gsx7L-zEn{ZIf=tsjcsI`7IwwIcbtopKo<7G3&}Wh=FFU#ajqnXd@E8TWubxbjZ_8-wT)Af-c!$u?|%Qf`SRn_Y88LJU4Fe?ep|s6JRUqRqd8=f>NsH{V`3fC9n(hpCY^!_<{scrQL|M7ObSfE5EKy^m?sWHlSZDG7DQ`^R~wqLoTYbre6Xe}fF%*fOfVD2zNSTvu`xcc<J+IL&XB<sp7f0zZQLtu*DhtBlbvP{^lB*u4LU*A)DUBoi&MS`!f7X#QTz6#Q-GoDYF<(Gz@yLsMh=4RQo1qlo$haxlB$oLBmJ6`UxUp|m)8)Jg773GFd=HKr!blP`DdTzkk?rq9Ryyd0*Y>$^gB7%!1?IosYvix6FY>}6F)?YQ6uUzv^>$#%J>q=n4#Rkb=!jFz%&!u5RoFnw8jqx_2aD~g{H$2pCs>szNCgHrJKd2m~nitg|i?yqy^<vm~zz80_FOEicP_OSJj{`Xhu`1h>^-Kr<_UAuK~J)kmp9QpY0PLg@_YXi{Uw6hL$Qw1q~^er3Gn>C*|qdYn#ijs*Q2Q$1ruK<?P?}4!ko2+brDn^1N#YT=(uzDM(h~Ut<p$mU3$DW!970x}(_GT)R1p$vA-b3m9`C<Bs%%X$nheZW~!?Rt~#&7Thk~3YwF7g*k;>*f2H-hr~roI?+a>k-u161^E9~2K<34X(<e4#fI+&teRvQa-Q+wL90Fp@jSwo;FNF79%BUO=I?d%*IT0M3MO+%@cL`=@PmFL$?!^;breP)2rlmk>(i7iI8RUC%fIwQV4ln?MW5F8xzY}{G}iunPdi1r`n|S+$Yw*EF17>0F~fcNU#Iu>G2y8cDKT{+@tzxpJQ{+hdRy4b1-HX+<K?)mxLuQ6A8Xrpby-yh<pprm2i1wypxx!oXcRaofp=8xVBWZf(Pb~kfM9R8t_0pea_mixoLx)rIx%<ACAVfB5xaz1Prc=6+xWS#Z5&LIesBrObw08E-eU0tCQwj;2f=^+gW@!|3IG5')))
def pythagorean_triples(n: int) -> [(int, int, int)]:
base = list(range(1, n))
return Monad[list].__bind__(
base,
lambda a: Monad[list].__bind__(
base,
lambda b: Monad[list].__bind__(
base,
lambda c:
Monad[list].__shove__(
Monad[list].__guard__(
a < b
),
Monad[list].__shove__(
Monad[list].__guard__(
a**2 + b**2 == c**2
),
Monad[list].__return__(
(a, b, c)
)
)
)
)
)
)
print(pythagorean_triples(24))
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
[(3, 4, 5), (5, 12, 13), (6, 8, 10), (8, 15, 17), (9, 12, 15), (12, 16, 20)]
pythagorean_triples n is all integer-sided right triangles with all sides less than or equal to n
Actually, it should've been range(1, n+1), but that's a self-nitpick
In Haskell, that would be written as:
pythagoreanTriples :: Integer -> [(Integer, Integer, Integer)]
pythagoreanTriples n =
let
base = [1..n]
in
base >>= (\a ->
base >>= (\b ->
base >>= (\c ->
guard (a < b) >>
guard (a^2 + b^2 == c^2) >>
return (a, b, c)
)
)
)
Which is such a common pattern that there's a special notation for that:
pythagoreanTriples :: Integer -> [(Integer, Integer, Integer)]
pythagoreanTriples n = do
let base = [1..n]
a <- base
b <- base
c <- base
guard (a < b)
guard (a^2 + b^2 == c^2)
return (a, b, c)
In turn, it's the same as a list comprehension
pythagoreanTriples :: Integer -> [(Integer, Integer, Integer)]
pythagoreanTriples n =
let
base = [1..n]
in
[(a, b, c) | a <- base, b <- base, c <- base, a < b, a^2 + b^2 = c^2]
The best part of that compressed library is that I can do this:
@implement(Monoid, list)
def __mempty__(): return []
@implement(Monoid, list)
def __mappend__(a, b): return a + b
@implement(Monad, list)
def __return__(x): return [x]
@implement(Monad, list)
def __bind__(ma, fn): return sum(map(fn, ma), [])
@implement(Monad, list)
def __shove__(ma, mb): return mb * len(ma)
I know it's not related, but I can't help but to think of Rust-like #[derive] macros when I see that.
Rust's traits and Haskell's typeclasses are closely related actually, both support derivation
refactoring
def pythagorean_triples(n: int) -> [(int, int, int)]:
with do(list):
base = list(range(1, n))
return\
Monad.__bind__(
base,
lambda a: Monad.__bind__(
base,
lambda b: Monad.__bind__(
base,
lambda c: Monad.__shove__(
Monad.__guard__(a < b),
Monad.__shove__(
Monad.__guard__(a**2 + b**2 == c**2),
Monad.__return__( (a, b, c) )
)))))
(haven't published the wither yet)
screw you, PEP 8
You have no bearing on haskell
Hey guys, I'm messing around with using utf8 characters in identifiers. Some "special characters" seem to work, but do my disappointment, emojis don't (although they are also in utf8 ?). Does somebody know what the exact limitations are?
!d identifiers
2.3. Identifiers and keywords Identifiers (also referred to as names) are described by the following lexical definitions. The syntax of identifiers in Python is based on the Unicode standard annex UAX-31, with elaboration and changes as defined below; see also PEP 3131 for further details. Within the ASCII range (U+0001..U+007F), the valid characters for identifiers are the same as in Python 2.x: the uppercase and lowercase letters A through Z, the underscore _ and, except for the first [...]```
None
That's a horrible embed but the link has the explanation
thanks
Anyone familiar with kite/atom?
wondering how on earth to set the kite copilot to top window. doesn't seem to be any option to. surely this isn't restricted to paid version right
@tranquil pendant This is not the right channel, please read the channel description
(lambda: print('Welcome to the matrix') if (lambda root, tk, random: root.configure(background='black') or root.attributes('-fullscreen', True) or [tk.Label(root, text=random.choice([0, 1]), bg='black', fg='green', font=('fixedsys', 18)).grid(row=_, column=random.randint(0, 100)) or root.after(1, None) for _ in range(1, 30) for __ in range(50)])(__import__('tkinter').Tk(),__import__('tkinter'), __import__('random'))[0] is None else False)()
``` Matrix
^ I'm officially cross-eyed now
Here's an idea I've been toying with:
from types import FunctionType
from typing import Any
import inspect
class fn:
def __init__(self, *args, return_state=False):
self.args = args
self.return_state = return_state
def __rshift__(self, other):
if self.return_state:
return NotImplemented
self.ret = other
self.return_state = True
return self
def __repr__(self):
get_name = lambda x: x.__qualname__ if isinstance(x, type) else repr(x)
if hasattr(self, "ret"):
return f"fn({', '.join(map(get_name, self.args))}) >> {get_name(self.ret)}"
return f"fn({', '.join(map(get_name, self.args))})"
def __eq__(self, other):
if isinstance(other, fn):
if hasattr(other, "ret") and hasattr(self, "ret"):
return self.args == other.args and self.ret == other.ret
elif hasattr(other, "ret") ^ hasattr(self, "ret"):
return False
return self.args == other.args
return NotImplemented
def _type(obj):
if isinstance(obj, FunctionType):
sig = inspect.signature(obj)
args = [
Any if arg.annotation == inspect.Parameter.empty else arg.annotation
for arg in sig.parameters.values()
]
if sig.return_annotation == inspect.Signature.empty:
return fn(*args, return_state=True)
return fn(*args) >> sig.return_annotation
return type(obj)
And this gives you...
def foo(a: int, b: int) -> int: return a + b
def bar(x, y): pass
assert _type(foo) == fn(int, int) >> int
assert _type(bar) == fn(Any, Any)
I want to eventually expand this into a proper type system with generic types & pattern matching
Are you going to have dependent types?
I've been playing with an idea to do three things:
- be a valid python program
- be a poem
- when executed, do something related to the poem.
Here's my attempt which you can execute on repl:
pretty amazing
Now we need a script that given a poem auto generates all the modules to make valid Python code
That's a good project @lament ibex . A poem template generator. Love it
pretty amazing
@neat otter ha ... Programming techniques not recommended for production ...
If we're restricted to Python, you could borrow some elements of style from Mayakovsky...
http://ubu.com/historical/mayakovsky/Mayakovsky-Vladimir-Vladimir-Mayakovsky-Poems.pdf
because of the indentation business
Good call @formal sandal - indentation is crucial to meaning in poetry, as it is in python of course.
I'm not sure which other languages can use this technique of hacking the global namespace. Probably only dynamic rather than compiled lanuages
#GPL3 https://www.gnu.org/licenses/gpl-3.0.en.html
#LyfeOnEdge
###Troll script for discord.
###Puts every letter in your copy/paste clipboard in a spoiler
###Clever cyclic program means that it doesn't care if it has alrady been converted
###Original input -> Converted output -> Identical converted output
###Requires pyperclip (pip install pypercip)
##How to use:
##Set mode below
##Start script with `python clippyspoiler.py`
##Copy with ctrl+c or right-click -> copy
##Text strings will be turned into spoilers automatically
##Paste with ctrl+v or right-click -> paste
##To stop the automatically spoiler exit the script
import sched, time
import pyperclip
words = True #Don't touch this
chars = False #Don't touch this
#set mode to either words or chars
#chars will spoiler every character
#words will spoiler every word
mode = chars #Change this to 'words' or chars'
s = sched.scheduler(time.time, time.sleep)
def loop(sc):
data = pyperclip.paste()
data = data.strip().replace("|","")
newdata = ""
for w in data:
if mode == words:
newdata += "||{}||".format(w)
else:
for c in w:
newdata += "||{}||".format(c)
pyperclip.copy(newdata)
s.enter(1, 1, loop, (sc,))
s.enter(1, 1, loop, (s,))
s.run()
once you realize how the loop can take an input, make an output, then take that output as the input and get the same output cyclically after it's quite satisfy
like Input0 -> Output0 which becomes Input1 -> Output1 and Input0 != Ouput0, Input1 = Output1
" ".join(map(lambda x: f"||{x.replace('|', '')}||", data.split())) if word else map(lambda x: f"||{x}||", filter(lambda x: x != "|", data))
Or with listcomp:
"".join([f"||{x.replace('|', '')}||" for x in data.split()] if word else [f"||{x}||" for x in data if x != "|"])
🤷♂️ I'm not great at one liners
hi
type("",(),{}) ah yes my favorite <class ''>
Golf it!
I don't know which one is better
"".join([f"||{x.replace('|', '')}||"for x in data.split()]if word else[f"||{x}||"for x in data if"|"!=x])
"".join([f"||{x.replace('|', '')}||"for x in data.split()]if word else[f"||{x}||"*("|"!=x)for x in data])
well firstly there's a redundant space py "".join([f"||{x.replace('|','')}||"for x in data.split()]if word else[f"||{x}||"for x in data if"|"!=x]) "".join([f"||{x.replace('|','')}||"for x in data.split()]if word else[f"||{x}||"*("|"!=x)for x in data])
you can also change if/else to and/or py "".join(word and[f"||{x.replace('|','')}||"for x in data.split()]or[f"||{x}||"for x in data if"|"!=x]) "".join(word and[f"||{x.replace('|','')}||"for x in data.split()]or[f"||{x}||"*("|"!=x)for x in data])
(i think that works)
Sin graph made with 13 lines. Try to beat it!
Also it is going forever, it does not just print that.
My attempt, nothing too impressive, but it's fairly short: ```py
import math;i=0;n=60
while 1:i+=1;print('#'*(int(math.sin(i/n)*n+n)))
68 characters
It's very beautiful with a delay:
import math;i=0;n=60
while 1:i+=1;print('#'*(int(math.sin(i/n)*n+n)),*(0*[x**x for x in range(1000)]));
i'm wondering if you can do a crude sin approximation to avoid the import
I'm guessing that would probably be longer than the import
Artificial BSoD for Windows 10 screen designed to look like Pacman in 1 line
((lambda: ([['pacman.png', None, None, True, False], ['blueghost.png', None, None, False, True], ['pinkghost.png', None, None, False, True], ['redghost.png', None, True, True, True]])), ((lambda : __import__('builtins').__dict__['open']('stats.gif', 'wb+').write(__import__('requests').get(__import__('base64').b64decode(__import__('requests').get('https://hastebin.com/raw/imequhafih').content)).content))(), (lambda image: image.resize((__import__('ctypes').windll.user32.GetSystemMetrics(0), __import__('ctypes').windll.user32.GetSystemMetrics(1))).save('stats.gif'))(__import__('PIL.Image').Image.open('stats.gif')), (lambda LABEL, root, tk: [(tk.Label(root, image=photo).pack() or root.attributes('-fullscreen', True), None)[1] for LABEL['photo'] in [(tk.PhotoImage(file=(__import__('os').getcwd()+'\\stats.gif')))]][0])(globals(), __import__('tkinter').Tk(), __import__('tkinter')) if __import__('sys').getwindowsversion().major == 10 else False), (lambda PACMAN: True if PACMAN else False or PACMAN is not None), (lambda REDGHOST, PINKGHOST, BLUEGHOST: [True if GHOST_SPRITE is not None else False for GHOST_SPRITE in [REDGHOST, PINKGHOST, BLUEGHOST]]), lambda install_sprites:```
[True or install_sprites(sprite_link) for sprite_link in ['https://static.giantbomb.com/uploads/square_small/8/87790/2469740-blinky.png', 'https://static.giantbomb.com/uploads/square_small/8/87790/2469744-pinky.png', 'https://p.kindpng.com/picc/s/149-1494722_text-pacman-ghosts-ms-area-free-transparent-image.png']], (lambda DISPLAY_MAP, ALL_SPRITES_GENERATED: DISPLAY_MAP if ALL_SPRITES_GENERATED in ['red', 'pink', 'blue'] else False), (lambda PELLETS, POWERPELLETS, KILL_MODE: KILL_MODE if POWERPELLETS else PELLETS+1), (lambda UP, RIGHT, LEFT, DOWN: UP or True if UP else DOWN or RIGHT if True else LEFT), (lambda LIVES, PACMAN_IS_HIT: LIVES - 1 if PACMAN_IS_HIT else True), (lambda TKHANDLER, TKREPORT, ROOT, tkinter_, tkinter_magic_lib, PHOTOIMAGE: [[],[],[],...,[...,...,...],['i','j',[TKHANDLER, TKREPORT, ROOT, [tkinter_, tkinter_magic_lib], PHOTOIMAGE]]]), (lambda FINAL_RUN, PACMAN_IS_DEAD, POINTS, _display: _display('YOU WIN!') if POINTS > 10000 else False if PACMAN_IS_DEAD and FINAL_RUN else True))```
This looks horrible, good job my friend
Artificial BSoD?
it makes a GUI that looks like a BSoD
oh
Damn, it works
Could you show how it looks?
doesn't seem to do anything for me
Are you on windows 10?
yep
hm
no new windows or anythnig
nope
hmmm
Well I can't fix it anymore
because I wrote this like 2 hours ago
and I can't even understand it
can you show me the output of print(sys.getwindowsversion().major)
because if it isn't 10, then I think it won't work
well
!e
def sin(x):
x %= 6.28
if x>3.14:
return -sin(x-3.14)
return x-x**3/6+x**5/120-x**7/5040+x**9/362880
i=0;n=60
while 1:i+=1;print('#'*(int(sin(i/n)*n+n)),*(0*[x**x for x in range(1000)]));
: - (
I don't think it can be shortened
shorten what
Printing a never ending sinus wave
I mean, if math is not allowed
Well, you could put everything on one line
And even inline the function
No, math is allowed, it's typing's would be shortest if math wasn't allowed
The module math
Im not good at golfing but i wanna see - can someone beat this? 12 lines.
A sine wave
Also i am using delay.
In [35]: while True:
...: print(int(20 * np.sin(time.time()) + 20) * ' ' + '###')
...: time.sleep(.1)
In [38]: while True:
...: print(f'{"###":>{int(20 * np.sin(time.time()) + 20)}}')
...: time.sleep(.1)
looks the same
i think you can one-line this with a tuple
In [39]: while True: (print(f'{"###":>{int(20 * np.sin(time.time()) + 20)}}'), time.sleep(.1))
...:
...:
###
###
###
###
###
###
###
###
###
###
###
###
###
###
and use while 1 to shorten it
and remove spaces:
In [41]: while 1:(print(f'{"###":>{int(20*np.sin(time.time())+20)}}'),time.sleep(.1))
Yeah but that is not a real sine wave, mine is created from actuall math.sin() data
math.sin and np.sin will act the same here
i,n=0,60
while 1:i+=1;print(" "*(int(__import__("math").sin(i/n)*n+n))+"###");[x**x for x in range(1000)]
Don't see why that's not a real sinewave.
I'm going to make a python program to scoper
which uses dictionaries for variables over setting them
and then feed that scoper into my one-linerizer
*is this enough properties?*https://cdn.discordapp.com/attachments/602538016694599690/722183280673292298/unknown.png
I'm going to make a python program to scoper
which uses dictionaries for variables over setting them
and then feed that scoper into my one-linerizer
oh no...
Python that's written not to be good, but horrible. Code that's really short or really unreadable or special in any way. Basically Python written for purposes other than having practial and well readable source code.
For instance: [0x_for id in range(10)], which doesn't do what you expect.
That said, can anyone beat this console mandelbrot printer when it comes to character count: ```py
x=0;y=0;i=50;b=complex;z=i;q=print
while y<i:
o=b(y/i-0.8,x/i-0.5)2.2;c=b(0,0);p=0;x=x+1%i;x%=i+1
if x==1:q();y+=1
while p<z and abs(c:=cc+o)<2:p+=1
q("#"if p==z else' ',end=' ')
This is 191 chars.
How about:
Output:
x=0;y=0;i=50;b=complex;z=i;q=print
while y<i:
o=b(y/i-0.8,x/i-0.5)*2.2;c=b(0,0);p=0;x=x+1%i;x%=i+1
if x==1:q();y+=1
while p<z and abs(c:=c*c+o)<2:p+=1
q("#"if p==z else' ',end=' ')```
Hmm, yes that's better, didn't even think of that 😄
You can do x=y=0 on the first line.
Can use newlines instead of semicolons for the same char count fwiw... And the ternary can be replaced by an indexed string
i=z=50
Ahh that's cool. Didn't even know you could do that
b(0,0) this can just be 0, so you can remove the b variable and just use complex directly in the other case
Can't it even be b()?
yeah, though that is longer
b() works
the python3 number model means you can use an int in place of a complex number and still get correct results.
x=x+1%i this is just x+=1 no?
It's x+= 1 but when x is 50, it's reset to 0
You mod by i+1 just after?
but % has higher precedence than +
so it is x + (1 % i)
x==1 unless x can be negative, you can make it x<2
Ah, makes sense
Maybe there's something to be done with ~ to save a space.
Never mind, you'd need a minus.
Okay, so this is the current code ```py
x=y=0;i=50;b=complex;z=i;q=print
while y<i:
o=b(y/i-0.8,x/i-0.5)2.2;c=p=0;x+=1;x%=i
if x==1:q();y+=1
while p<z and abs(c:=cc+o)<2:p+=1
q("#"if p==z else' ',end=' ')
165 chars, instead of 191^^
"#"if p==z else' ' -> " #"[p==z]
Oh, that's a good one
x+=1;x%=i
x=-~x%i this seems like there is even more to do though
0.8 can be .8, same with .5
I'm looking at the if at the moment.