#esoteric-python
1 messages · Page 69 of 1
(probably cos' I coded this all in one go and then tested it afterwards, probably not the smartest idea)
del(inp[0])``` you can't do that with a string, do `inp = inp[1:]` instead
now it actually works 😃 (after I put the whole thing in a try except to avoid the index error from codePos at the end)
now I need to find a way to implement cells before the first one, so doing < at the begining works
Which channel here is for talking about Python design patterns ?
for general discussing, #python-discussion
if it's related to a problem you have and you need specific help, then any of the help channels will do
this channel is for people who take python way too far
I am taking python way to far :), but the issues is not too far 😄
This channel is also for people who take python too far to make it small
well, we're more than just golfers :D
we're
special = [chr(c) for c in (*range(33, 48), *range(58, 65), *range(91, 97), *range(123, 127))]
[Credits][Eviee#0666]
we're py special=[chr(c)for a,b in((33,15),(58,7),(91,6),(123,4))for c in range(a,a+b)]
we're
special=[*__import__('string').punctuation]
I'm currently working on a stack-based esolang, and this is the syntax I have so far
| = Pops the number off of the top of the stack
. = Pushes 0 to the stack
; = Pushes X on to the stack. If X is not passed, pushes 5 to the stack
+ = Adds X to the top number of the stack
- = Subtracts X from the top number of the stack
* = Multiplies X by the top number of the stack
# = Square roots the number at the top of the stack
/ = Divides the top number of the stack by X, then rounds it to the nearest whole number
( = Begin a loop. If after it there is a number, repeats by that number. If after it there is a =, followed by a number,
the loop will end once the end is reached and the top number of the stack is equal to X.
) = End a loop.
> = Swaps the top value of the stack, with the X from bottom of the stack
< = Swaps the top value of the stack, with the X from top of the stack
[ = Begins a function that gets added to the function slot. There is only one space for functions, and it'll get replaced if a new one is began
] = Ends a function
^ = Clears the function
% = Runs function X. If function X is not passed, runs the function in the function slot
? = Runs the function in the function slot if the number of the top of the stack is equal to X
= = Runs the single instruction after it, if the top value of the stack is equal to X
~ = Roll the stack by X
' = Outputs the number X. If X is not passed, outputs the number at the top of the stack
" = Outputs the unicode character of X. If X is not passed, outputs the unicode character of the number at the top of the stack
(Note that 'X' refers to a number directly after the instruction, and it can be any positive integer)
any suggestions?
@gilded orchid fucks brains well
I'm thinking of having a seperate stack for functions, but I don't know how I'd implement that
(I'm thinking up the syntax before actually starting making it for context)
suggestion: operands are for cowards, just make digits operators that pop the stack, multiply by 10, add the number, and push
😛
🤔
and every other operator's X is just popped from the stack
(this is arguably less esoteric, but more stack-based)
anyway the other thing i'd do is have a way to create strings and a way to evaluate them - dc builds loops and functions on this
Could I maybe have a string slot that can be appended to, cleared and outputed
how about hollerith style strings: H: Reads the next [top of stack] bytes of input and places them on the stack as a string object
to build loops and functions dc-style, you need string objects that can be placed on the stack and string variables, not just a single string slot
maybe I can have 3 different stacks, the number stack (the main one), the string stack and the function stack
and then have 3 different instructions that switch what stack the commands are running on
for conditionals you could have an operator that's "If the number on the top of the stack is non-zero, pop two items. Otherwise, pop the number and remove the third item from the stack, leaving the second"
honestly you can probably build loops from that and an eval function without even having an explicit loop operator
oh, a way to copy any given item from the stack can probably usually be used in place of variables.
to replace X?
no i meant for the features i've been suggesting that require variables
oh right
what if the language were stringly typed
then you could just have one stack and all elements on the stack are strings
math operators just treat the string as a number
quick question, is the second number in the stack second from the top, or second from the bottom?
Top. Always top.
Heh, more stack fun incoming? @gilded orchid
I'm making the language way more limiting, to make it a lot harder to code in
. = Pushes 0 to the stack
# = Pops the number off of the top of the stack
; = Duplicates the value at the top of the stack
< = Swap the two values at the top of the stack
> = Roll the stack by the top number of the stack
^ = Makes a string out of the top number of the stack characters below the top character of the stack, and then pops all of those, and pushes that string to the stack
~ = Runs the string at the top of the stack. If it isn't a string, do nothing.
? = Run the string at the top of the stack, if the second number of the stack is non-zero
- = Subtract one from the number at the top of the stack
+ = Add one to the number at the top of the stack
" = Outputs the string at the top of the stack, and pops it off of the stack. If it is a number, do the same with that number corresponding unicode character.
how does this look, I got rid of a load of stuff and added @calm rampart's string suggestion, to make it way more annoying to code in
always the top
in most stack languages each operator only cares about however many operands on the top of the stack, and ignore an unlimited amount below
I'll do that after I quickly write an interpreter (also I'm gonna add a * command to make it so you don't have to do 40 or more +'s to start a loop lmao)
lol
what's an easy way to swap the two things at the end of a list?
wait nvm, figured it out
a[-1], a[-2] = a[-2], a[-1]
Anyway >.>
with my subclass of list called nlist, I can do:
from ntools import nlist # not on pypi yet
a = nlist(1,2,3,4)
a.swap(-1, -2)
So it’s cool :)
you should find a way to modify lists so they function as nlists when using []
ok, just finished the interpreter (I haven't actually tested it yet so it probably won't work lmao)
stack = []
def run(code):
codePos = 1
while codePos<=len(code):
exec({'.':'stack.append(0)',
'#':'stack.pop()',
';':'stack.append(stack[-1]',
'<':'stack[-1],stack[-2]=stack[-2],stack[-1]',
'>':'[stack.append(stack.pop(0))for i in range(stack[-1])',
'^':'[stack.append("".join([chr(i)for i in stack[-1:-stack[-1]:-1]));del(stack[-2:-(len(stack[-1]))-2])'
'~':'(run(stack[-1])if type(stack[-1])==str else pass)',
'?':'((run(stack[-1])if type(stack[-1])==str else pass)if stack[-2]!=0)',
'-':'stack[-1]-=1'
'+':'stack[-1]+=1'
'*':'[stack.append(stack[-1]*stack[-2]),del(stack[-2:-3:-1])]'
'"':'(print(stack[-1]if type(stack[-1])==str else print(chr(stack[-1])))'}[code[codePos-1]])
codePos += 1
(I used a really long dict cos' I was lazy)
ok, I've done that
here's a (I think) working version
codeDict = {'.':'stack.append(0)',
'#':'stack.pop()',
';':'stack.append(stack[-1]',
'<':'stack[-1],stack[-2]=stack[-2],stack[-1]',
'>':'[stack.append(stack.pop(0))for i in range(stack[-1])',
'^':'[stack.append("".join([chr(i)for i in stack[-1:-stack[-1]:-1]]))];del(stack[-2:-(len(stack[-1]))-2])',
'~':'(run(stack[-1])if type(stack[-1])==str else pass)',
'?':'((run(stack[-1])if type(stack[-1])==str else pass)if stack[-2]!=0)',
'-':'stack[-1]-=1',
'+':'stack[-1]+=1',
'*':'stack.append(stack[-1]*stack[-2]);del(stack[-2:-4:-1])',
'"':'print((stack[-1]if type(stack[-1])==str else chr(stack[-1])),end="")'}
stack = []
def run(code):
codePos = 1
while codePos<=len(code):
exec(codeDict[code[codePos-1]])
codePos += 1
run('.+++++++++++.+++*"')
you can use this syntax for dicts too:
some_dict = {
'key': 'value',
'key': 'value',
}
if you want it a little cleaner
that's basically what I'm already doing, except it looks stupid because of short discord line lengths
(here's how it should look)
i'm working on it
Oki
god damn it, I just made 'Hello corld!'
ok got it, hello world is .++++++.++++++*;.++*"#;.+++*;-------"#""+++"#;----"#;.+++*---------------------"#;.+++*+++"+++"------"--------"#;---" @marsh void
Imma try and create the fibonacci sequence using it
noms a cookie
I'm gonna add a new instruction that outputs the number, just to make this not take an eturnity to make
What can you do with the ~ or ? operator?
Are you limited to executing single instructions, or is there some way to set up a chain?
it runs a string, and the string can be as long as you want
it can be used, for example, for loops by using a string that keeps on running itself
@marsh void I just realised to do that, I’m gonna need nested loops, so i need to make a strong that makes another string
oh god
Time to make a quine!
Quines actually aren’t possible lmao, because it uses eval so it breaks if you try to output "
lmao
Wait, how?
yeah maybe
I was sort of just bodging it together, so readability didn't really matter when I was making it
I didn't even do any testing until after I made it, and then I fixed the 9 different syntax errors lmao
Currently my roll instruction is moving everything down, and moving the bottom item of the stack to the top
is that what roll is meant to do?
what do you mean by down
sorry, my brain's always twisted up by this part because the first stack-based language I learned was HP48 calculators, which displays the top of the stack at the bottom of the screen
anyway, the HP48 description of ROLL is
ROLL
Moves a specified level to level 1
( e.g. 4 ROLL will move level 4 to level 1 )
i.e. it moves the X'th item of the stack (after popping X) to the top.
so I think yours is right then
swap is just 2 roll; rot is 3 roll; and dup is just 1 pick, so it might be worthwhile to make your available primitives roll/rolld/pick instead of dup/swap/roll
@gilded orchid
I think mine's wrong, because doing roll on [1, 1, 2, 1, 2] gives [2, 1, 2, 1, 1]
and I think it should give [1,2,1,1,2]
@gilded orchid what does "roll" do?
'Rotate: Also referred to as “roll,” specifies the number of elements in a stack which are rotated in their order. For example, rotating the top four elements of a stack would move the topmost element into the fourth position while the next three elements move up one position.'
so that should rotate the top 2 elements on the stack, then?
wouldn't that be [1, 1, 1, 2]
my roll thing rolls the entire stack by the top value on the stack
now that I think about it, I might change it to roll the top X of the stack (where X is the number at the top of the stack)
and I think it should give [1,2,1,1,2] this makes no sense
why isn't it popping the top number on the stack?
good point, I should probably change that
I'm trying to implement the 'proper' definition of rol, but I'm really struggling to actually get it to work
I currently have [stack.insert(-i,stack.pop(-1))for i in [stack[-1]]*stack.pop(-1)], but that rolls the entire stack, instead of only X from the top of the stack
nvm, I got it to work
top of the stack is index 0?
well if we consider how we can use lists as stacks, doing list.append(x) is like pushing to the stack and list.pop() is obviously popping from the stack
im just a lil confused as to how rolling [1, 1, 2, 1, 2] should give [1,2,1,1,2]
thought maybe the top of the stack was index 0 in this case
i'd expect it to be -1 🤔
I used [stack.insert(-i+1,stack.pop(-1))for i in [stack.pop(-1)]] to make it work like that definition I sent earlier
(pop the top object off of the stack and roll X below it by one)
hm
not really an #esoteric-python question, but probably unpacking
I wonder what features of Python can be turing complete
Lambdas and function calls are because lambda calculus (although technically you do run into a recursion limit)
but what else?...
metaclass abuse for sure
almost all operators are turing complete because you can put anything you want inside the operator overload 😃
Can one-liners be Turing complete?
Anything can be a oneliner
Anything can be anything
behold:
>>> def a():
... print("1")
...
>>> a()
1
>>> a.__qualname__ = "b"
>>> a
<function b at 0x10a79d0d0>
>>> a.__code__ = compile("print('c')", "<string>", 'exec')
>>> a()
c
That function you passed me is now mine :P
Is there a list of all the different double underscore things in python?
look at the python data model in the documentation
there's an entire page on it, but it shows and explains all dunders as well as other things
specifically section 3.3
are you able to override all dunders?
eg: could you override new to run something whenever a new instance of a class is made
Would you just create a class called new?
I don't think so
After doing some research, I’m pretty sure you just create a class that derives from object and then define new in that
wait nvm I’m actually an idiot
@gilded orchid yep, you define __new__ in class, and actually run something in it lol
how would you do that?
hm
class ntuple(tuple):
def __new__(cls, *args):
do_some_stuff()
return super().__new__(cls, args)
little example I guess
what is super()?
I am bad at explaining, honestly
I just googled it and ‘
super() gives you access to methods in a superclass from the subclass that inherits from it.’
I don’t understand any of that lmao
there's hardly anything esoteric about this :D
(I’m just bad at python)
>>> class nlist(list):
... def __init__(self, *args):
... super().__init__(args)
>>> n = nlist(1,2)
>>> dir(n)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
so super() would represent list in that case? (For the class at the top)
don't really understand what you mean >.>
Nvm
@gilded orchid this make any sense?
so super just adds the mainClass's code onto it?
Super() gives you the instance of the class that the methods are inherited from
Sort of
But it's specifically that instance
oh ok
Yeah
so super().test() is an instance of mainClass().test()?
Sorta, it's actually more like mainClass.test(self), giving the method of main class the current instance of subClass
super() is just shorthand for getting the parent class and passing the current instance.
class MainClass:
def print_me(self):
print(self)
class SubClass(MainClass):
def print_me(self):
print('hello!')
super().print_me()
main = MainClass()
main.print_me() # <MainClass object at 0x......>
sub = SubClass()
sub.print_me() # hello! <SubClass object at 0x......>```
completely random, but what would you guys say is the worst esolang hello world?
the Malbolge Unshackled one is absurd https://paste.pythondiscord.com/pobivugini.py
(it's longer then 2k chars so it can't fit in a discord message lmao)
definitely fugue
wow that is ummm... interesting code
also verbose is quite something
AND OUTPUT IT FOR THE CURRENT PERSON USING THIS PROGRAM TO SEE lmao
naming your language verbose and deciding to use roman numerals instead of unary
:pathetic_skinner:
I find it hilarious that you can't see the text "Hello World!" in 99% of these
i'd say the numbers should be spelled out in english
>>> def nrange(start, end, step):
... ret = []
... while start < end:
... ret.append(start)
... start += step
... return ret
...
>>> nrange(1,2,0.1)
[1, 1.1, 1.2000000000000002, 1.3000000000000003, 1.4000000000000004, 1.5000000000000004, 1.6000000000000005, 1.7000000000000006, 1.8000000000000007, 1.9000000000000008]
Can someone explain a bit?
It feels quite weird
That's floats for ya. If you really need decimal math to work with exact precision check out the Decimal module that comes with Python https://docs.python.org/3/library/decimal.html
it's not really esoteric, but there's a website for it :D https://0.30000000000000004.com/
With a domain like that it's esoteric 😝
That’s actually quite neat 
wow, Minifuck is quite something
< : Same as Brainfuck
. : Move to next bit and invert it and output letter stored in first 8 bits, if none then input
[ : Move to next bit and invert it, skip next instruction and invert next bit if zero
I feel like it'd be fun to try and golf that
Is there a short way to convert a list of binary into a denary number? (eg: [1,0,1] would become 5)
int("".join(map(str, my_list)), 2) might work
!e ```py
my_list = [1, 0, 1]
my_number = int("".join(map(str, my_list)), 2)
print(my_number)```
@polar plover Your eval job has completed.
5
Ves Zappa#3787 (not gonna ping) just gave me an identical solution in #help-coconut lmao, thanks though
(also the reason I asked here is because someone said I should because I was trying to golf it)
np 😃 xD
oh wow, 2/3 char brainfuck exists
< = Move pointer one cell to the left. (If pointer is currently over the first bit, do nothing.)
( = Move to next bit and flip it, skip next instruction if zero.
any other character = No-op instruction.
I'm working on a compiler to Subleq, which only has one instruction. It's a little different though because it has operands.
even after looking at esolangs.org/wiki/Subleq, I'm still really confused how it works lmao
@gilded orchid hello do you have a minute to talk about our Lord and savior
@snow beacon what does it compile to?
No, It compiles to Subleq. No way am I going to write any programs with one instruction.
Just some syntax I threw together, with a lot of prewritten compiler macros in Python.
cool
I've got a bnf, but no language name.
I think I'll upload it somewhere once I'm happier with it. I was planning on using it for the pride esoteric python golf challenge. I'd have some golfed Subleq code, a golfed Subleq interpreter, and probably the compiler as a reference.
@frank hazel ?
@gilded orchid you said you didn't know how subleq works
Oh right
so subleq (the instruction not the language) takes 3 arguments
but what do they do?
Does the third run the 3 numbers that are there as a subleq instruction?
all 3 are memory addresses, shockingly
it takes address 1
wait no
subleq x, y, z is like y = x - y; if y <= 0: jmp z
it sets y to x subtracted by y then if y is leq (less than or equal to) 0 it jumps to z
pretty simple
What’s does jump do?
jumps the instruction pointer to that memory address
are you familiar with how control flow in assembly works?
not really
it's all about jumping
time for pseudoassembly
say I want to check if two addresses contain the same number
I might do something like
00 cmp $F0E2 $F0E3
10 jeq 30
20 jeq 40
30 <if code>
40 <rest of code>
not real assembly, but
the idea is to structure it around jumping around since that's the only option you have
So jump changes what instructions are running?
yes
a while True loop with jumps would look like
0xE000: uhh do something
0xE001: do another thing
0xE002: jmp 0xE000
jumping based on addresses is more of a machine code thing, though
in assembly you have something called labels to make it make much more sense
:loop
wow
stuff here
wow code
jmp loop
this is more similar to something a real assembly language would have
Python has gotos, by the way, guess what
pip install goto
then you can import it
sort of, yeah
but in machine code there are no "lines of code"
only instructions
it would jump to the instruction stored at X memory address
Would the first instruction be instruction 0?
yes
well that's not exactly defined by subleq itself, it might begin executing at some other memory address
I think most subleq emulators start at 0
Also, does it jump to value X, or jump to the value stored at address X (where X is the first value)
it jumps to address X
the way execution works is there's an instruction pointer, which is an address
each time it reads the 3 values the pointer points to
executes that as subleq
then increases the pointer and goes again
jumping just sets the instruction pointer, basically
So basically subleq has control flow, if statements and subtraction
in one instruction
yes, that's basically the idea
wdym
memory addresses, like list indexes, always start at 0
but some of the lower numbers might be reserved, like with CHIP-8
where the program actually starts at 0x200
I meant does their value start at 0?
wdym value
I’m so confused lmao
I was thinking kind of like brainfuck
are memory addresses nothing until you try and use it for something
and then it gets assigned to 0 and runs that instruction?
@gilded orchid it's always something
Your code can and should modify itself. Your code is in memory starting from zero generally. After that it's probably zeroes, or it could throw errors. My interpreter has accessing unset values terminate the program.
That way I can put everything in a list
The first thing I put in my compiler was labels, so I didn't have to bother with absolute addresses in code I'm going to change later.
I know, kinda not esoteric, but how can I make the following code faster?
x, y = 1280, 720
a = []
for i in range(x):
for j in range(y):
a.append(
(i, j)
)
I found one though
from itertools import product as f
x, y = 1280, 720
a = [(i, j) for i, j in f(range(x), range(y))]
Is there a faster one?
I think you saved one character with that as f import
simple list comp is considerably faster than the original
Smaller, bit slower
x, y = 1280, 720
a = [(i // y, i % y) for i in range(x*y)]
That's... slower?
from itertools import product
a=[]
a.extend(product(range(x),range(y)))
How does python x, y = 1280, 720 a = [(i, j) for i in range(x) for j in range(y)] compare?
Or perhaps using python list(itertools.product(range(x), range(y)))?
the extend of product or list-ing it are the fastest, and probably the same (with list being more readable)
I challenge you guys to golf the UBFIM interpreter(https://esolangs.org/wiki/Ultimate_bf_instruction_minimalization!)
It's suprisingly complicated because of the how input output works in it
@gilded orchid ultimate bf sounds like ultimate boyfriend lol
lmao
is there a short way to do 1-liner assignment to variables?
wym?
i'm trying to do it in a list
oh
give me an example please, I am bad at abstract stuff
you can write it normally, and I can try to one-line
I was just wondering for it generally
I'm not actually doing anything atm
(apart from my failed attempt to make that esolang interpreter I mentioned earlier)
!e py foo = [1, 2, (locals().__setitem__("bar", 5), 3)[1], bar * 2, bar * 3] print(foo)
@polar plover Your eval job has completed.
[1, 2, 3, 10, 15]
yeah that works
but, why?
yup
print(a:=10)
def _():
try:
idx0 = width_height.index(t0)
except ValueError:
idx0 = 0
try:
idx1 = width_height.index(t1)
except ValueError:
idx1 = 0
how to make that shorter?
for i in [(idx0,t0), (idx1,t1)]:
try:
eval(f'{i[0]}=width_height.index({i[1]})')
except:
eval(f'{i[0]}=0')
not really pythonic but this works I think
@marsh void
could be a bit shorter sinceo nly the numbers change on idx and t
lol, it gives NameError obv
oh yeah
but when you get to eval the question if you really want it to be shorter comes up
well there are plenty variables that are terribly long in there 😄
for i in [0,1]: #shorter then range(2) lmao
try:
eval(f'idx{i}=width_height.index(t{1})')
except:
eval(f'idx{i}=0')
(that's shorter btw)
@marsh void
my ass was lazy so for readability I just made a function for that lol
not really related but I just realised you can do 0,1 instead of [0,1] for golfing
neat
It says t{1} rather than t{I}
oh yeah
oops
https://esolangs.org/wiki/English I love that this has a page lmao
'Many people are familiar with it even if they don't know any other programming language.'
huh. i never knew python even had a unary positive operator: https://docs.python.org/3/library/operator.html#operator.pos, https://docs.python.org/3.7/reference/datamodel.html#object.__pos__
i'm having trouble thinking of what i might even want to overload it to do
well, maybe it would be useful if you had a lib to do particle physics too
Invert could be used for doing fuzzy checks ~my_fancy_thing == my_var, __invert__ would need to return an object that overloads __eq__... Would be way more clear with a named method lol
the one time i've seen ~ overloaded unconventionally is in pyparsing: https://pyparsing-docs.readthedocs.io/en/latest/pyparsing.html#pyparsing.NotAny
Wow lol
@marsh void you can use two loops in one list comp
[(i, j) for i in range(w) for j in range(h)]
not sure if faster though
one cool thing you can do with the invert operator is inverting sequence indexes
>>> def palindromic(sequence):
for i in range(len(sequence)//2):
if sequence[i] != sequence[~i]:
return False
return True
>>> palindromic('abba')
True
>>> palindromic('abbo')
False
>>> palindromic('aboba')
True
>>>
i like how much semantic sense it makes
plus you probably save some cycles over -i-1
@brazen geyser this one is shorter?
def palindromic(seq):
return reversed(seq) == seq
would that really work? doesn't reversed returns an iterator?
It works, since I tested it yesterday
seq[::-1] == seq
In [1]: def palindromic(seq):
...: return reversed(seq) == seq
...:
In [2]: palindromic('abba')
Out[2]: False
>>> a = "abba"
>>> a[::-1] == a
True
that does beg the question though, what's the shortest way to check palindromeness for any type of iterable?
mmm maybe I tested it yesterday and I didn't use it because it returned an iterator 😐
sorry
no worries
[*a][::-1] == [*a]
@mortal ingot wait weird lol
any iterable, including iterators
is the [:] necessary
no
(though it's probably just a=[*i];return a[::-1]==a or something)
@marsh void nope
>>> def test():
... yield 1
... yield 2
... yield 1
...
>>> g = test()
>>> [*g]
[1, 2, 1]
>>> [*g]
[]```
ugh I forget about that
the best I can do is py def p(s):l=[*s];return l[::-1]==l
wait no
def p(s):*l,=s;return l[::-1]==l```
the shortest one is where you add a special palindromic check operator to cpython and use that 😛
that's cheating though
😠
now you have a closed relationship
homewrecker
relationship.seek(0)
ValueError: I/O operation on closed file.```
relationship jokes? lol
@sick hound yeah, I got what is the problem; generator objects, for example, are not subscriptable
relationships: dict
they're not subscriptable, and if you iterate them twice you might get different things
checking an iterator is a palindrom certainly requires casting it into a list or tuple, as checking it forward will consume it, and you don't know the length in advance, and you can't look forward anyway
from ctypes import*;pythonapi._Py_Dealloc(py_object(meta))```
meta has been deallocated now
they don't exist
no
damn, that's abusing the unpackaging syntax 😄
>>> *a, = range(20)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]```
@sick hound importing * is a sin apparently, even worse than ; in normal code
def p(s): return (a:=[*s])[::-1]==a
well it's less characters in this case :P
yep
@marsh void it's not an import of *, it's using the unpacking syntax
from ctypes import*``` this is an import of `*`
@worthy ridge lol I know that; was kinda slow; I replied to ^
ah ok
sorry for inconvenience 
Hey guys, really need your help
import itertools
a = [*itertools.product(range(1280), range(720))]
b = [*itertools.product(range(10, 100), range(20, 200))]
is there a fast way to remove all elements in b from a?
numpy?
something with sets ought to be faster than list manipulation
list(set(a)-set(b))
but you lose how it was arranged
yeah, and actually
c = list(set(a)-set(b))
c.sort()
@edgy kelp why not sort it after operation?
not sure how long sets with sort will take compared to some kind of list comprehension
yeah, that might take long
almost a second on my pc
it actually did sort quite fast lol
>>> a = [*itertools.product(range(1280), range(720))]
>>> b = [*itertools.product(range(10, 100), range(20, 200))]
>>> c = list(set(a)-set(b))
>>> c.sort()
took around a second, even less probably
well second's a lot but trying list comprehension now is taking horribly long compared to that
you can replace the initial lists with sets too if you're not doing anything with them
set comprehension isn't a thing?
just set(itertools.product(range(1280), range(720)))
but there is set comprehension with {} iirc
yeah, didn't know about setcomp tho
still going for least chars?
you can use a SortedSet from https://pypi.org/project/sortedcontainers
no, not really @edgy kelp
that is a lot of instructions for a stack based language lmao
I've given up on implementing a stack based language I designed with two or three modes for almost all of the punctuation. It's a lot of instructions to implement.
But once you get into non-ascii?
I had enough trouble reading APL.
@gilded orchid brainfuck is cool tho
yeah
but I started hating it after trying to do anything difficult with it
for my 6000 character 12 days of Christmas in Brainfuck, I resorted to using python to generate it for me
(after a failed attempt doing it in brainfuck myself)
the good thing is that you can put other chars in code and the get ignored
(at least in online compiler tho)
what compiler do you use for brainfuck?
personally, I mainly use Boof (https://brandly.github.io/boof/) as it updates in real time, however it bugs out if your program is too long. if that happens, I switch over to using Jelly (https://btzy.github.io/jelly)
@gilded orchid why not write your own tho
Dunno, just googled and found one online compiler, don’t remember it’s name
I tried writing my own but got stuck at nested loops
i'll have another shot at it sometime though
@gilded orchid can you send a link of bf instructions here? I forgot one of them >.>
> Move the pointer to the right
< Move the pointer to the left
+ Increment the memory cell under the pointer
- Decrement the memory cell under the pointer
. Output the character signified by the cell at the pointer
, Input a character and store it in the cell at the pointer
[ Jump past the matching ] if the cell under the pointer is 0
] Jump back to the matching [ if the cell under the pointer is nonzero
@gilded orchid kinda don’t get what , does
let user type a character? like input() in python, but limited to one char
i don't get what's interesting about writting brainfuck (or ook or whichever equivalent) code, sure, it's neat to know it's turing complete ande hence you can write any program in it, but why would you? if you want a very constrained env, you can write assembly code, or try to do parallelized code in gpu, or serverless code using distributed erlang code, things where the constraint brings you something
at least piet code is nice to look at
Basically brainfuck programmes can have an input buffer, and , takes the ascii value of that input and puts it onto the current cell. Then that input gets removed from the input buffer
@worthy ridge because it’s a fun challenge, and it’s a difficult logic puzzle (at least that’s why I like brainfuck)
@gilded orchid ok in my mind I have implementation of around 40-50 lines of code
@worthy ridge I would say, esolangs are made for fun, and saying "why would you?" is not a very good question here imo.
probably
i mean, there is no shortage of interesting problems, i rarely see a point in making them harder, but that might just be me
Hey guys, how can I modify variable with exec?
def run():
out = ""
exec("out += '0'")
print(out) -> ""
# I'd like it to be "0" that way
>>> exec('a = 5', globals(), locals())
>>> a
5
>>>
>>> def run():
... out = "0"
... exec("out+='1'", globals(), locals())
... print(out)
>>> run()
0
@brazen geyser
is this cheating? py def run(): out = "0" _locals= locals() exec("out+='1'", globals(), _locals) out = _locals["out"] print(out)
@brazen geyser lol I was pissed off and have just written a class that holds that variable
@gilded orchid
NeKitDS $ bf
++++++++++++[-<+++++>]<.
p+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
while arr[p]:
arr[p]-=1
p-=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
p+=1
p-=1
store.output+=chr(arr[p])
Output: '<'
So yeah, it works but it’s kinda bad at indentation
@marsh void bf -> python compiler?
I made a thing
from collections import*
from operator import*
from functools import*
f=defaultdict(int)
def q(n):
f[n]+=1
for x in filter(partial(gt,n),[0,1]):q(n-x-1)
return n
for i in range(q(int(input())),0,-1):print(f[i])
I made an esoteric fibonacci
and then golfed it, I guess
@frank hazel yeah, bf -> python compiler
NeKit $ bf
>++++++++[-<++++++>]<+..-.+.
.bf -> .py
p+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
while arr[p]:
arr[p]-=1
p-=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
p+=1
p-=1
arr[p]+=1
store.output+=chr(arr[p])
store.output+=chr(arr[p])
arr[p]-=1
store.output+=chr(arr[p])
arr[p]+=1
store.output+=chr(arr[p])
-----Output-----
1101
you're adding to store.output (which isn't even defined in the code?) instead of printing
p and arr aren't defined either
It is not actual code
Lemme send the real one (it’s bad tbh)
@frank hazel there -> https://paste.pydis.com/ogeguxeguj.py
Ok so I needa write so people can copy+paste code that was compiled and it can run? @frank hazel
I would do that
@frank hazel sorry for mention, there you go -> https://paste.pydis.com/ekicutikat.py
Okay
NeKit $ bf test.bf
.bf -> .py
from collections import defaultdict
p = 0
arr = defaultdict(int)
output = ""
... # compiled BF code goes here
@frank hazel okay updated ^
nice
https://paste.pydis.com/fetibesida.py haha first serious brainfuck program
@frank hazel ok some actual program up here ^
also, added new command:
$ - add value of ceil to output
e.g. >+$<$ -> 10
@marsh void can it handle this program I wrote a while ago? (https://pastebin.com/WJVxQnvp)
Let me see
My terminal lagged a bit, I need to make debug: bool thing for it not to print stuff
It's meant to output the lyrics to the song 12 Days of Christmas, but I accidentially used the wrong new line char (I used 13 instead of using 10 lmao)
On the First day of Christmas
My true love sent to me
A Partridge in a Pear Tree.
On the Second day of Christmas
My true love sent to me
Two Turtle Doves, and
A Partridge in a Pear Tree.
On the Third day of Christmas
My true love sent to me
Three French Hens,
Two Turtle Doves, and
A Partridge in a Pear Tree.
On the Fourth day of Christmas
My true love sent to me
Four Calling Birds,
Three French Hens,
Two Turtle Doves, and
A Partridge in a Pear Tree.
... # discord char limit
On the Twelfth day of Christmas
My true love sent to me
Twelve Drummers Drumming,
Eleven Pipers Piping,
Ten Lords-a-Leaping,
Nine Ladies Dancing,
Eight Maids-a-Milking,
Seven Swans-a-Swimming,
Six Geese-a-Laying,
Five Gold Rings,
Four Calling Birds,
Three French Hens,
Two Turtle Doves, and
A Partridge in a Pear Tree.
wow it actually works lmao
It did print :)
Yeah lol
I can give you the interpreter code if you’d like (it’s quite messy rn)
ok
If you're wondering how it works, it basically multiplies the number 32 over around 200 different cells, then it goes through all of them and adds/subtracts to make them into the correct number, so the cells are formatted (numbers for string, 0, numbers for other string, 0, etc.)
then I spam [.>] and [<] to print them all in order
i'm gonna try and golf a brainfuck to python compiler
ok thanks
np, have fun :)
@gilded orchid I’m looking for a way to detect if a brainfuck loop is while True:... any suggestions?
I don’t really know how you’d do that
it actually is impossible
it's the halting problem, exactly
@marsh void basically, it comes down to if it were possible to do that it would be possible for any program, including the program that checks if the loop goes forever
so you can make a program that checks itself to see if it goes forever
if the answer is yes, end the program
if the answer is no, loop forever
no matter what the answer is wrong
so the program that checks if the program loops forever does not exist
You can check if the program exactly repeats itself
Or simple things like a monotonically increasing cell
(That last one would actually be pretty difficult. You'd need to be sure that it doesn't affect other cells.)
But for the former you can just store a bit of a history of program states, and if the program repeats itself exactly, break.
I’m gonna have a shot at
https://code-golf.io/brainfuck#brainfuck later
Code Golf is a game designed to let you show off your code-fu by solving problems in the least number of characters.
although I probably won’t be able to do it
How the fuck should brainfuck in brainfuck work? @gilded orchid
a couple of them already exist lmao
I have an idea of how I'm gonna do everything
so basically I'm gonna start of taking input, which will consist of, using , (obviously) and then repeatedly subtracting from it to work out what brainfuck command (if any) it is
then I'm gonna split the into into lots of 8 bit chunks, where each bit coreesponds to a command
and between each 8 bit chunk there's gonna be an empty gap, which I can put 255 into
255 will represent where it is in the program (and you can always jump to it by using +[->+]-)
and then I'll have the cells, which will be 2 cells each
one of the cells will be that cell's value when running the brainfuck programme, and the other one will be either 0 of 254 (254 represents the position in the cells)
So you need to have an other Lang interpreter already to execute interpreter of brainfuck
yeah basically lmao
wdym?
depends on what implentation of brainfuck you're using
hm
wait no i'm dumb
😂
yeah you would have to enter a null character for that to end
@gilded orchid I mean, do you take inputs with ,, and then execute them?
no, I'm gonna take all the inputs and then execute after that
because executing them straight away wouldn't work for [ or ]
Okay, then how?
I haven't actually started doing it yet but I've planned it out
I think + will be +[->+]->+ because +[->+]- will jump to the current cell and then it'll just add to it
@gilded orchid I found this (not mine):
>>>,[>++++[-<-------->]+<-[----------[>]>[<+<+>>>>]<<<-[>]>[<+<+>>>>]<<<-[>]>[<+<+>>>>]<<<-[>]>[<-<+++>>>>]<<<--------------[>]>[<++<+>>>>]<<<--[>]>[<-<+++++++>>+>>]<<++++[-<------>]+<+[>]>[<++<+>>>>]<<<--[>]>[<<+>>>>]<<-<[+]<[>]>,>]<]>>[->]>+<<<<-[<]>[-[<<]>[<+[>]>>[<]<<[>>+[<<[<]<<-[>>]<[>>>>[>]>+<<[<]<]<-[>>]<[>>>>[>]>-<<[<]<]<++[->>+<<]>>[>]>]<]<[<]>-<]>-[<<]>[<++[>]>>[<<]>[<<+[<<[<]>[-<<+>>]>--[<<]>[[>]>+<<[<]<]>+[<<]>[[>]>-<<[<]<]>+[>]>]]<<[<]>--<]>-[<<]>[[>]>>.<<<[<]<]>-[<<]>[[>]>>-<<<[<]<]>-[<<]>[[>]>>,<<<[<]<]>-[<<]>[[>]>>+<<<[<]<]>-[<<]>[[>]>>>[>>]>[<<<[<<]<+>>>[>>]>-]>[-]<<+[<[->>+<<]<]<[->>+<<]<[<]<]>-[<<]>[[>]>++[-->[-<<+>>]>]+<<-[++<<]<[->>>[>>]>+<<<[<<]<]<[<]<]<++++++++>>[+<<->>]>]
In my implementation raises IndexError if I give it \n
Ooh make a programming language that compiles to brainfuck
It would have to be basically brainfuck but readable with comments and ascii as ints, ontop of a "smart array" system that groups stuff together over the virtual 30 something array you have in brainfuck
@fallow cairn any ideas how to make this work even if user hits enter?:
input(": ")[0]
sys.stdin.read()
Oh yeah
getchar()
this ain’t python lol
getchar() isn't a standard function
It is C though
^
sys.stdout.read() gets one character?
I have no idea what the goal here is
, in BF is basically the same as doing os.read(sys.stdin.fileno(), 1)
I find it absurd that Slashes (https://esolangs.org/wiki////) has been proved to be turing-complete despite the fact that it only has string replacement
NeKitDSS $ bf --debug p.bf
-----Input-----
, # get input
. # print input
[-] # clear cell
.bf -> filter
,.[-]
.bf -> .py
from collections import defaultdict
p = 0
arr = defaultdict(int)
output = ""
def f(k):
n = input(f"In [#{k}]: ")
return chr(0) if not n else n[0]
arr[p]=ord(f(p))
output+=chr(arr[p])
while arr[p]:
arr[p]-=1
print(output)
In [#0]: 2
-----Output-----
2
@gilded orchid the thing is, you can replace text with more string replacement
👏 @marsh void
I want to make that programing language a reality
Need some syntax ideas though
It will basically be a improved brainfuck that compiles to the original
@fallow cairn wym compiles to the original?
Transpiles back to brainfuck
But I want to add a complicated mechanism so it makes a shit load of brainfuck
Hm I have ideas how to improve BF, but it won’t be translatable back
Like a function has to be duplicated in brainfuck text over and over whenever compiled
Like to make the ir (brainfuck) much larger in source then original
Basically make a monstrosity that is nice to work with and makes very, very ugly brainfuck
Like py x=0 for i in range(3): add(x) def add(x): x += 1 Would have to have the add function duplicated every time it ran
:D
NameError: name 'add' is not defined
>+++[-<+>]< @fallow cairn monstrosity?
^ why lmao
Functions that go into other functions and recursion would be fucking annoying
And would make the source code massive for something other then like the hello world of bf
Well time to learn basic bf!
@fallow cairn bf I simple, you just need to keep track of what cell are you pointing at
Yep
(and also nested loops can get kind of insane so you need to keep track of that lmao)
^
even printing out a 3 digit number from a cell is difficult
Or strings
strings are relatively easy compared to printinng out a number from a cell
because you need to do division and modulo only using +1 and -1
Right
I need to learn language dev
Then i'll do it
I can't think straight right now, way too tired 😅
just to prove a point
[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]
>>>[>>+<<-]>>>>++++++++++<<
[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>>>>>
++++++[>++++++++<-]>[<<+<+<<<<+>>>>>>>-]
<<<<<<<.>>>>>.<.
this prints a 3 digit number from a cell (assuming you have [number, 0, 100] and your pointer is on the number)
(also I stole that divmod algorithm from https://esolangs.org/wiki/brainfuck_algorithms#Divmod_algorithm)
@gilded orchid I don’t think that you stoled it tbh, just took it lol
@gilded orchid that was actually kind of a problem in a coding competition I took part in
oh wow
we had to create a program that would determine whether a string could be constructed by repeating a smaller string n times
using only x->y string substitution
e.g. k=2 and the string is 1010 would output true
but 0110 would output false
+[,]
# Transpile update: Hitting Enter on input sets the cell to 0
also storing/doing arithmetic number above 255 is a nightmare (assuming you're using an implementation that wraps around)
I think you'd either have to store it in binary or store it in base 255
All this talk of compiling to brainfuck makes me thing of my original goal for my compiler to Subleq: make really incomprehensible code from much nicer code.
It's technically finished, but I'm going to keep adding macros.
Im afraid of the darkness in the soul of all of you
@fallow cairn sounds good, consider checking out other projects that try to do the same thing
brain comes to mind
also me and two others tried to do this with a language based on C
Dude I still have to learn it :P
maybe you can get further than everyone else
¯_(ツ)_/¯
Gave myself 2 weeks to learn how to make a very basic language
Like very basic
how basic
https://esolangs.org/wiki/Ly made this a while ago
Damn
500 lines
Ok how the fuck did you make this when you where 12
@frank hazel
shrug
Chirst
Not really related but how were you able to get your language added to tio.run? @frank hazel
@gilded orchid asked the creator, he lets anyone add their lang
use the code golf stack exchange chat
You need 20 reputation for that
rip me
How do you actually get reputation on stack Exchange?
Ah, that's what I've been doing wrong.
@gilded orchid woah that brainfuck in brainfuck actually works with my new transpiler:
In [#3]: +
In [#4]: [
In [#5]: ,
In [#6]: .
In [#7]: ]
In [#8]:
In [#10]: a
In [#10]: b
In [#10]: c
In [#10]:
-----Output-----
abc
On #8 I hit Enter
Also takes exclamation mark as an end of input
@marsh void why is the input that way?
@frank hazel what? You can’t input more than one char per cell
It is brainfuck in brainfuck
What if you write a python compiler in brainfuck and a brainfuck compiler in python

@sick hound python compiler in brainfuck? Think about this shit first
(I think it was a joke)
You can simulate decimal math. It's Turing complete
@snow beacon while being Turing complete, it takes hella shit amount of time to calculate something
why did this channel turn from esoteric python into brainfuck
@wind maple don’t know honestly
somewhere down the line it turned into esolangs
iz ok I got it
from collections import*
from operator import*
from functools import*
f=defaultdict(int)
def q(n):
f[n]=-~f[n]
for x in filter(partial(gt,n),[0,1]):q(~-n-x)
return n
for i in range(q(int(input())),0,-1):print(f[i])
boom new and improved obfuscated-golfed fibonacci thing
i'm back from being away from home, and ava makes a good point. your esolang projects are cool, but i think it's best to get this channel back to being true #esoteric-python. :D
while not print("Hello", end=" "):
print("World!")
Would esolang projects be good for the off topic channels? @brisk zenith
@gilded orchid I’m guessing so :)
sure, but also #303934982764625920 could be used when you want to show them off.
If it’s something we created in an esolang, and not an esolang written in python, would it be ok for #303934982764625920?
not really, no.
@marsh void that will never exit the loop right?
yeah
But it will never exit
yes
(unless it increases memory usage each time, meaning it’d eventually run out of memory)
well
in a theoretical world that argument doesn't work
computers wouldn't be turing complete if you account for the fact that they have limited memory
but we say they are because, well, for all intents and purposes they are
so for all intents and purposes a while True loop does indeed go on forever
in practice no if you were to do something silly like allocate 10gb of memory each iteration
but if you just no-op each time then you will indeed run "forever"
until your machine fails
yep
@frank hazel
n,a,b=[],[],[[]]
for i in b*int(input()):n=[n]
while n:print(len(b));a,b,n=b,[*a,*b],n[0]
@grizzled cloak
[0, [...]]
@formal sandal thanks, it's even more awful
have you seen my list comp one
@frank hazel python eval('exec("n,a,b=[],[],[[]]\\nfor i in b*int(input()):n=[n]\\nwhile n:print(len(b));a,b,n=b,[*a,*b],n[0]")')
It seems i'm good at making terrible and unreadable code.
My favorite on is the Brainfuck interpreter
import sys
for p in sys.argv:
s,a='',[0]*32;j=t=0
for i in p:s+=' '*t+['j-=1','a[j]+=1','j+=1','a[j]-=1','print(chr(a[j]),end="")','while a[j]:',0,'',0,0][ord(i)%18-6]+'\n';t+=(i>'Z')-2*(i>'[')
exec(s)
good, that sucks
It's 204 characters long, and someone figured out how to make it 118 characters long.
I feel helpless.
The slowest bf interpreter :D
++[>+++++[>+++++++>+++>++++++++++<<<-]<-]>>+.>>[>+>+<<-]>>[<<+>>-]<<+.++++++++++.--.>+.<+++++++.--.+++++++.<++.[-]<---.[-]>>>----.<------.[-]>+++++++.[-]
Here’s the name of one of my favorite games
[+]
@formal sandal oh shit here we go again
also, it doesn’t do anything
+[+] is the real deal
Right.
+[-+] this is more sad
i go away for another weekend and we're back off the rails for #esoteric-python!
the size of code is really the worst metric one could think of to judge a software on
I don't know about that. If your storage capacity is limited, you don't want your code taking up much space.
Larger code takes longer to read, from a certain point onwards
If it’s really short code then it could become very unreadable
Code golf is to programming what poetry is to literature.
Poems are useful ways of conveying information when you have limited pages. Golfed code is the same for pages of memory.
@distant wave Not really. Well, technically, a shorter piece of code might be faster to literally read, but it might take a lot of time to process it.
A poem might be short, but the shorter the poem is for the same amount of meaning, the harder it is to understand.
And there are also awful poems.
And there are awful short codes
Seems more and more like a good analogy to me.
Many poets die at the age of 27.
Likewise, ninja coders die at 27 because their colleague programmers are so pissed off.
@snow beacon same
@formal sandal ninja code yes
I’m kinda having a strange feeling when typing help('modules') in IDLE
I challenge you guys to obfuscate the number 0 the best you can
I came up with [not[[]]][not[[]]]
or, even better, [[[[not[[]]]]]][not[[]]][not[[]]][not[[]]][not[[]]]
>>> not[]
True
>>> not[[]]
False
🤔
def _(__):
return (lambda _ : _.__code__.co_argcount)(__)
def __():
return 1
_(__)```
(globals().__setitem__("sys",-1),len(__import__("sys").argv)+sys)[sys]```
(globals().__setitem__("sys",-1),len(__import__("sys").argv)**0+sys)[sys]```
@polar plover (so it’s going to be always 0, no matter how many args there are)
hmmmmm,,,,,,, no xD
Explain
ohh wait, you changed it
thought you meant mine
yes yours will always be 0
from what I can see
yup
And your won’t always be 0
stupid python, thinks that 0**0=1
But len(sys.argv) won’t be equal to 0 though
Or can it be 0?
Kinda interested 🤔
I knew that it would not always be 0, but never thought of the **0
Same
I was kinda sitting trying to think of how to operate on x to make it equal to 1
I got another idea: py (<super long code to get any number>) * 0
int(str(ord(str(type(1))[0]))[1]) 🤔
import sys
from collections import defaultdict
class Container:
def __init__(self):
self.output = ""
def clear(self):
self.output = ""
store = Container()
def run(code: str):
p, indent = 0, 0
arr = defaultdict(int)
pycode = (
"""def f(k):
n = input(f"In [#{k}]: ")
return chr(0) if not n else n[0]
"""
)
rdict = {
"+": "arr[p]+=1",
"-": "arr[p]-=1",
">": "p+=1",
"<": "p-=1",
".": "store.output+=chr(arr[p])",
",": "arr[p]=ord(f(p))",
"?": "print('Array:', list(arr.values()))",
"[": "while arr[p]:",
"]": ""
}
code = "".join(filter(lambda x: x in rdict.keys(), code))
for char in code:
n = check_char(char)
pycode += " "*(indent*n) + rdict[char] + "\n"*n
indent += decide_indent(char)
exec(pycode)
output = str(store.output)
store.clear()
return output
def decide_indent(char):
if char == '[':
return 4
elif char == ']':
return -4
else:
return 0
def check_char(char):
return (0 if char == ']' else 1)
# actual 0
int(run(">++++++[<++++++++>-]<."))
obfuscated? sorry for my brainfuck reference
(globals().__setitem__("sys",-1),len(__import__("sys").argv)**((globals().__setitem__("sys",-1),len(__import__("sys").argv)**(globals().__setitem__("sys",-1),len(__import__("sys").argv)**((globals().__setitem__("sys",-1),len(__import__("sys").argv)**(globals().__setitem__("sys",-1),len(__import__("sys").argv)**((globals().__setitem__("sys",-1),len(__import__("sys").argv)**0+sys)[sys])+sys)[sys]+sys)[sys])+sys)[sys]+sys)[sys])+sys)[sys]```
@formal sandal it’s literally a pattern
And it has 0 so not cool
len(__import__('asyncio').get_event_loop()._scheduled)```
I’ve been working on some async stuff so there you go
N ** 0 = 1 is a mathematical truth, for any value of N, so not sure what python could do else
we couldn't count to 1 in binary if 1**0 wasn't 1 😆
(or in any base, of course)
0 ** 0 depends on context, but it too is commonly held as 1.
b=b"~"
t=tuple(b)
f=lambda:[*[hash(s[3:2])]*3,3*2,2**2**2**2*2]
function = type(f)
code = type(f.__code__)
def a():
f.__code__=code(*f(),c.co_code,t+c.co_consts[1:-1]+t,c.co_names,(),s,s,b[-1],b)
s='''if int(False):
try:
from ctypes import*
x=int(input("Enter a single whole number, between 5 and any other number: "))
assert x!=5
except:
x=id(12).bit_length()
i=input("Now enter another integer: ")
z=bool(...)if(~x*i*x)else sum(abs(v) for v in(x.imag,i.find(i)))
else:
f()'''
c=compile(s,s,s[81:-238])
function(c,{"int":bool,"f":a},s,t,())()
zero=max(sum((-f(),*t))**2, z)
print(zero)```
Prompts for some irrelevant input, then prints 0
If you can work out the control flow, I commend you.
I'm certain Python wasn't designed to do this.
i don't know of any context in which 0 ** 0 is not 1, but i'm no mathematician
i'm confused at line 2 already 😆
ah, right
this is only true for the real number line
which is why for most practical purposes (i.e. programming languages) it's commonly just defined to be 1
but python has complex numbers builtin 
well, to be fair 0 is on the real number line
thats...not really the point of ava
lim x->0 of x^x doesn't work anymore in the complex plane
Recently in a code golf, I saw someone use ’@‘<b<‘[‘. How do greater then or less than comparisons work with strings like this?
Oh ok, so it's based on their ascii value
How do comparisons work with strings that have more then 1 character?
Would it return true if one of them passes the comparison?
would that return a tuple of booleans?
no
would it be True if all of them are True, and false otherwise?
Oh ok, that makes sense now, thanks
You know when you alphabetise a list of names, you start with "aardvark" then "aargh" and then "alphabet"? It's like that. "aa" < "ab" < "ba" < "bb"
That's how I think of it.
i just learned about vars(). what other horrid things can you do aside from vars()["a"] = -5?
vars() is nerfed in python 3
outside of class definitions and modules (where it just returns the normal dictionary), it's just a copy now
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined
>>> c
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'c' is not defined
>>> locals()['a'] = 5
>>> a
5
>>> globals()['b'] = 5
>>> b
5
>>> vars()['c'] = 5
>>> c
5```
is vars() based on the current scope?
>>> vars()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}
>>> def test(x):
print(vars())
>>> test('abc')
{'x': 'abc'}
You can get vars() of an object.
Without an argument, vars() acts like locals(). Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.
Hmm...
But this somehow works.
oh ok, I was just wondering because I was trying to do assignment in a lambda with locals().update a while ago, and it didn't work
>>> a=lambda x:(locals().update({'hello':'test'}),print(hello))
>>> a(123)
Traceback (most recent call last):
File "<pyshell#107>", line 1, in <module>
a(123)
File "<pyshell#106>", line 1, in <lambda>
a=lambda x:(locals().update({'hello':'test'}),print(hello))
NameError: name 'hello' is not defined
a=lambda x:(locals().update({'hello':'test'}),print(locals()['hello']))```
works, though.
I get it.
Since hello is not in lambda's args, it is taken from the outer scope.
That makes sense.
>>> [lambda x: i * x for i in range(5)][0](2)
8
>>> [(lambda i: lambda x: i * x)(i) for i in range(5)][0](2)
0```
vars() is basically locals(), the only difference is you can also do vars(obj) to get that object's dictionary
@formal sandal locals at the top level is just the module dictionary, it works fine in modules and classes.
Right, it works as well.
>>> a=lambda x, loc:(loc.update({'hello':'test'}),print(hello))
>>> a(123, locals())
test
(None, None)```
Yes, it's because you give the lambda the ability to change the locals of the outer scope, and lambda's locals are its parameters.
Do I understand it correctly?
well
only because the outer scope is the module
it still wouldn't work within a function
locals isn't very interesting at the module level because it's the same as globals - where it's interesting is in the class initializer
because there, it is the dict that is being used to prepare the class (which isn't the same as the class dict - it's copied when the class is constructed, because it has to be read-only for obscure cpython reasons)
huh, that's interesting
it's a mappingproxy ```py
Test.dict
mappingproxy({'module': 'main', 'dict': <attribute 'dict' of 'Test' objects>, 'weakref': <attribute 'weakref' of 'Test' objects>, 'doc': None})```
yeah, a mappingproxy is just a wrapper around a dict that doesn't let you set any of its values
they added it in, i think python 3.3, someone found a way to make the interpreter crash by overriding magic methods with invalid functions or something
>>> help(vars)
Help on built-in function vars in module builtins:
vars(...)
vars([object]) -> dictionary
Without arguments, equivalent to locals().
With an argument, equivalent to object.__dict__.
so this is what vars() is anyway
Are we allowed to do multiple submissions for the #esoteric-python challenges?
yep absolutely
what's the challenge 🤔
we've done a few previously, you can see them all here: https://github.com/python-discord/esoteric-python-challenges
i was supposed to put one up 5 days ago but i was very busy and stuff
i'll do that soon, i promise. :)
oh neat
yeah some of them are almost a year old by now, but i'll be happy to accept submissions for any challenge from anybody at any time. :)
random challenge: starting with this, call the function a and exit with an exit code of 19. py from ctypes import* def a():print('you win') py_object.from_address(id(locals())+sizeof(c_ssize_t)).value=int
i can do it in 245 characters
That’s some challenge
everything you write has to be after the code
no reading stdin, file i/o, sockets, or anything weird like that
standard library only
can you explain wtf py_object.from_address(id(locals())+sizeof(c_ssize_t)).value=int is actually doing
it turns locals() into an int
which is sad
yes
there's one specific internal value in locals() that says "this is a dict"
this program overwrites that to make it an int
your evil
yes
you need to either get a out without using locals(), or turn it back into an int
either way, you can't access the actual values in locals() unless you turn it back, because it's an int
rhetorical question 😛
does anyone want to see my solution
yes
who? :P
someone im sure 😛
().__class__.__base__.__subclasses__()[69].load_module('builtins').__import__('code').interact('',lambda _:'from ctypes import*;import sys;l=sys._getframe(6).f_locals;py_object.from_address(id(l)+sizeof(c_ssize_t)).value=dict;l["a"]();exit(19)')```
it creates an interactive python console
oh my god
but it lets you specify the input function
that's what lambda _:'from ctypes import*;import sys;l=sys._getframe(6).f_locals;py_object.from_address(id(l)+sizeof(c_ssize_t)).value=dict;l["a"]();exit(19)' is
().__class__.__base__.__subclasses__()[69] is actually the class _frozen_importlib.BuiltinImporter
...now that I think about it, I could probably just get the right importer out and tell it directly to load code
Using l as a variable... Now THAT is wrong
yep, that worked, 236 characters py ().__class__.__base__.__subclasses__()[82].find_module('code').load_module().interact('',lambda _:'from ctypes import*;import sys;l=sys._getframe(6).f_locals;py_object.from_address(id(l)+sizeof(c_ssize_t)).value=dict;l["a"]();exit(19)')
ok, i'll change it

