#esoteric-python
1 messages · Page 61 of 1
He didn't show any hard to read convoluted lambdas
like the rpn ones
:D
Ty for merge based @frosty wyvern
You're welcome my child
execute = lambda b,i=0,line='':(execute(b,b[i+1],line) if b[i]==1 else execute(b,i+2,line)if b[i]==2 else execute(b[128:],i+2,line)if b[i]==3 else(lambda l:execute(b[:b[i+1]]+l[0].encode()+b[b[i+1]+1:],i+2,l[1:]))(line if line else input()+'\n')if b[i]==4 else execute(b[:b[i+1]]+bytes([b[i+2]])+b[b[i+1]+1:],i+3,line)if b[i]==5 else 1/0 if b[i]else(print(chr(b[i+1]),end=''),execute(b,i+2,line))```
Hello my esoteric children
an esoteric bytecode-ish language
b'\1\4\0\0\4\3\1\2' is a cat program
every operator has one operand except for 5 which has two
0 outputs the operand as an ascii character
1 jumps to the operand (starting from 0)
2 does nothing
3 deletes the first 128 bytes of the program and is the only way to jump to parts of the program more than 255 bytes
4 takes input (one character) and writes it to the program at the operand (starting from 0)
5 writes the second operand to the first (starting from 0)
the program's only memory is the program itself, with only 256 addressable bytes
the cat program writes its input to the operand of the output instruction and then executes the output instruction
aaay-aaay (aaay-aaay) opened !13 *Add pastebin's language* in python-discord/esoteric-python-challenges: Add pastebin's language
my first contribution on gitlab is an esoteric language :)
the current challenge is an esoteric language?
Task: Create and(or) implement an esoteric language of your own!
But yeah, the task is about esoteric languages but some people like @vague gust actually created an almost real normal language
I haven't added quite a few crucial things yet but hey it sorta works
and I will submit a MR soon
class KInterpreter:
stack = []
def eval(self, code):
for char in code.split("k?")[1:]:
if char == "+":
self.stack.append(self.stack.pop() + self.stack.pop())
elif char == "-":
self.stack.append(self.stack.pop() - self.stack.pop())
else:
self.stack.append(ord(char))
while len(self.stack) > 0:
print(self.stack.pop())
interpreter = KInterpreter()
interpreter.eval("k?ak?bk?+")
good enough? @frosty wyvern
esoteric enough?
so i guess ill mr this
I wrote 800 lines :^)
loool
NICE
ikr
taking a trip back to web 2.0
ill add an increment with kk?
hey nix
yeah
how do you say hello world in your language
i came up with this in like 2 minutes joseph
😄
class KInterpreter:
stack = []
def eval(self, code):
skip_next = False
for char in code.split("k?")[1:]:
if skip_next:
skip_next = False
continue
if char == "+":
self.stack.append(self.stack.pop() + self.stack.pop())
elif char == "-":
self.stack.append(self.stack.pop() - self.stack.pop())
elif char == "k":
self.stack.append(self.stack.pop() + 1)
skip_next=True
else:
self.stack.append(ord(char))
while len(self.stack) > 0:
print(self.stack.pop())
interpreter = KInterpreter()
interpreter.eval("k?ak?bk?+k?ak?bk?+k?kk?k?a")
what a beauty
not quite so esoteric if you swap k? for spaces
@frosty wyvern nah tbh i think mine does
oh you have the weird lispy thing right
no its applied lambda calculus
i didnt mean pure in any formal sense
applied adds + - * /, numbers, logical operators, and the ability to bind abstractions to names
oh
yea, its just lambda calculus
lolno
:(
ill show an example when i fix the alpha reducer
i got beta reduction done and realized i didnt do alpha reduction correctly
i posted this earlier
py-lci> λabcdef.(a b) (c d) (e f)
(λa.(λb.(λc.(λd.(λe.(λf.(((a b) (c d)) (e f))))))))
Will not be able to complete it this weekend sadly
I guess that makes sense tbh
It takes in garbage, randomises it and outputs garbage
LOOOL
uh

that is offensive
lmaooo
its left associative
In my language all values go in a double ended queue that only accepts unique values and for execution of functions parameters are taken from alternating ends of the queue
I wanna make a new language already
Though if I ever do make another language
I'll write a formal grammar
and probably look into that python yacc binding or whatever
nono
and also use proper ASTs or whatever
use Lark
my interpreter is absolutely crap hacked together
its fast
I really dislike yaccs style
You define variables in the files namespace and then yacc finds those and uses them
Lark (using LALR) is the fastest and lightest on memory out of many common python grammar parser libraries
Perhaps next I should just work on implementing a very simple language "VM" runtime
with bytecode
instead of bothering writing grammars and parsing an actual language
frig it
people can write bytecode
well atm i have a list of opcodes
an now i can jump around that list
so in theory i could have an opcode deleting opcodes from the list
Yeah, I mean I guess that falls into like.. metaprogramming
where the program modifies itself
hk?>k?ek?>k?lk?>k?lk?>k?ok?>k?bk?lk?-k?>k?
@vague gust i taught it to say hello
nice
python-jvm-interpreter is an implementation of the Java Virtual Machine in Python. It works by parsing and interpreting the Java Class files.
Yeah, should've been python-jvm or something
pvm
:p
aight @pure dew self modifying code working whats next
@cunning wave speculative self modification
huh?
is easiest with bytecode
Speculative execution is the normal term
For every condional or jump, predict the result of the conditional or the location of the jump
Ah, introduce spectre into your language
start executing (in a new thread maybe) the instructions as a result of that condtional or at that jump. If the actual cond/jump doesnt equal the predicted one, toss out the computed result or kill the thread
then add conditional jumps
@cunning wave or just randomly decide whether to execute a random instruction every cycle
that feels like it could break the program pretty easily
skni?
skip next if
uh lol
it pops a value from the stack and if its not 0 skips the next instruction
Henrik Boeving (goniX) opened !14 *Add nix' solution* in python-discord/esoteric-python-challenges: Add nix' solution
hm?
first
itll return ["asd"]
2nd if i pass a custom string to it itll split on that custom string
oh you mean that input split
its meant to do
a b c d e f g
well, ye, it returns a list
but if they enter a b cd e f by mistake, itll crash
Shawn McLaughlin pushed to branch master of python-discord/esoteric-python-challenges (Compare changes)
Shawn McLaughlin (shawnmcla) merged !14 *Add nix' solution* in python-discord/esoteric-python-challenges: Add nix' solution
Shawn McLaughlin pushed to branch master of python-discord/esoteric-python-challenges (Compare changes)
Shawn McLaughlin (shawnmcla) merged !13 *Add pastebin's language* in python-discord/esoteric-python-challenges: Add pastebin's language
Looks cool guys! Good job paste for actually adding instructions with your solution :) cough cough Nix
can't wait to have a closer look in a bit
i wrote docs instead of code today
Good man
I might just MR in a Markdown file with links to my GitHub repository
split() splits on string.whitespace
Joseph Banks (JoeBanks13) opened !15 *Move solutions to a new folder on esoteric 1* in python-discord/esoteric-python-challenges: Move solutions to a new folder on esoteric 1
Joseph Banks pushed to branch master of python-discord/esoteric-python-challenges (Compare changes)
Joseph Banks (JoeBanks13) merged !15 *Move solutions to a new folder on esoteric 1* in python-discord/esoteric-python-challenges: Move solutions to a new folder on esoteric 1
okay, i'm about to submit my MR
for?
Joseph Banks (JoeBanks13) opened !16 *Add my solution to the esoteric language challenge* in python-discord/esoteric-python-challenges: Add my solution to the esoteric language challenge
that
fancy
@unborn frost simple calculator in one statement, with input validation and whatnot. ```py
calculator = (lambda:
print("Answer:", (lambda get_input:
(lambda left, op, right:
(lambda func: func(left, right))(
func = {
"+": int.add,
"-": int.sub,
"/": int.truediv,
"*": int.mul
}[op]
)
)(
left = int(get_input(
str.isdigit,
"Enter an integer: "
)),
op = get_input(
lambda char: char in list("+-/*"),
"Enter an operator [+-/*]: "
),
right = int(get_input(
str.isdigit,
"Enter one more integer: "
))
)
)(
get_input = (lambda predicate, prompt:
(lambda itertools:
next(itertools.dropwhile(
lambda string: not predicate(string),
(input(prompt) for _ in itertools.count())
))
)(
itertools = __import__("itertools")
)
)
))
)
huh that's pretty neat
also lmao I forgot I could have just used a list to find the operand
operator?
operator, yes
as you can see there, i actually call the unbound magic methods for int there (cause importing operator is too mainstream)
Is everyone done with their submissio s
no
@unborn frost as one line: ```py
calculator = (lambda: print("Answer:", (lambda get_input: (lambda left, op, right: (lambda func: func(left, right))(func = {"+": int.add, "-": int.sub, "/": int.truediv, "": int.mul}[op]))(left = int(get_input(str.isdigit, "Enter an integer: ")), op = get_input(lambda char: char in list("+-/"), "Enter an operator [+-/*]: "), right = int(get_input(str.isdigit, "Enter one more integer: "))))(get_input = (lambda predicate, prompt: (lambda itertools: next(itertools.dropwhile(lambda string: not predicate(string), (input(prompt) for _ in itertools.count()))))(itertools = import("itertools"))))))
@brisk zenith now turn it into an expression
a lambda is technically an expression, is it not? So remove the assignment and just call it directly
expressions can contain expressions
and if you want to make it an expression, you can assign with globals().__setitem__("calculator", lambda ...)
or locals().__setitem__(...) might be more accurate
oh lol yes
and yes, lambdas are expressions
but they may only contain one expression (the return value)
@frosty wyvern mergey wergey :^)
().__class__.__base__.__globals__.__setitem__("calculate", lambda ...) path to globals may not be correct
Shawn McLaughlin pushed to branch master of python-discord/esoteric-python-challenges (Compare changes)
Shawn McLaughlin (shawnmcla) merged !16 *Add my solution to the esoteric language challenge* in python-discord/esoteric-python-challenges: Add my solution to the esoteric language challenge
that was dunderful
theres some dunderful way to access modules without importing anything
yeah i know
we discussed it earlier for the challenge
joseph@wubalubadubdub:~% cat lang.py
if input() == "4":
print("hello world")
joseph@wubalubadubdub:~% echo 4 | python3.6 lang.py
hello world
joseph used it in his .. yeah
one expression done
This is fully educational and is full of bugs, I have no real intention of developing this past the current state it is at
LOL
I love your attitude
wait until you see my magnificent "its just a simple challenge, ill fix it later" code

actually
my code is better than what it was
it's split into like 6 files so far
i'm actually trying to make my language relatively usable
im actually gonna polish this and upload it to pypi later
Are you saying there is no market for a language that supports nondeterministic flow of operations such as mine and with no flow control?
uh ye
and no functions
mine is like 4 files iirc
yes it is jos-b
no flow control isnt a huge deal
>>> try:
... 1/0
... except ZeroDivisionError:
... raise ValueError
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
ValueError
>>>
>>> try:
... 1/0
... except ZeroDivisionError:
... raise ValueError from None
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
ValueError
>>>
would be cool to be able to chain them though :^)
haha
i want something like this https://i.seph.club/sl8rd.png
raise ValueError from ImportError from ...
What does the from None do
look at the example c:
stops it from tracing back past the immediate error
yup
Ah
if you don't do that it will find the other error (ZeroDivisionError in the example) and show that as well
One thing about pythons syntax that is still weird to me is the for else loop
i guess this'll have to do for now https://i.seph.club/1hafd.png
yeah I guess it's kinda weird but it does make sense
there's while/else
Idk why but it just looks wrong to me
i actually really like it
so, there's
if/elif/.../elif/else
try/except/.../except/else/finally
while/else
for/else
i can't think of any more things like that
i mean, else is everywhere
@vague gust just nest try catch blocks, raising from in each one
hmmm
make a script that generates the nested try/excepts given a string, each exception with a word from str.split()
uh ye

try:
raise Exception("She")
except Exception as e:
try:
raise Exception("Took") from e
except Exception as e:
try:
...
``` you get the idea
no need to do the from though since it's auto-inferred in try/except
joseph as i said you should make a program to create the nested try/except blocks :^)
@vague gust true
i also like type(type(typing))
fuck he's good
now i'm curious, how does type(type) is type work?
like, how can type subclass itself 
interesting
type(type)(type(type)) is type
>>> type.__subclasses__(type(type))
[<class 'abc.ABCMeta'>, <class 'enum.EnumMeta'>]
py-lci now (messily) handles free names colliding with bound names
(λx.(λy.xy) x) x -> (λa.(λy.ay) a) x
I spoke too soon, it only works in the outmost scope lmao
i started working on a biological programming language
where dna is the main computing element, e.g. the computations are just whether or not strands of dna bond because they have complimentary base pairs or not
and i was thinking about what dna could actually do, computationally
"well, strands of dna can pattern match"
"it'd be really awful to read and write just a whole bunch of 1d pattern matching strings"
"and the syntax would be godawful, using GCAT exclusively"
and then i realized it was literally regular expressions
regular expressions are 1 dimensional pattern matchers using terrible syntax
regular expressions match complexity with a language i was specifically trying to make hard to use
You can make a BF interpreter with regex too
progress on my esolang is almost completed, i just need to polish up a bit
i have to rewrite mine lmao rip
I'm glad people are mostly done their entries. I'll be putting up a new challenge probably by tomorrow. Of course, feel free to keep working on this challenge even after the new one is up
I am as always open to suggestions/ideas for the next challenge <3 so speak up
my esolang so far
it just needs polishing a bit
i also need to rewrite some stuff
but yeah, the idea is that it's all valid python syntax, you've just gotta import the esolang and it'll work
oh it is
...wat
tfw you even confuse pastebean
PROGRAM [
# this is the start of a slice now
: # colons are a feature of slices, yes?
]```
that's a thing
numpy uses that, actually.
>>> thing [:,:,:,:,:,:,:,:,:,:,:,:,:,:,:,:]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'thing' is not defined
>>>
you can have as many as you want
wat
() basically 'calls' SHOULD
>>> type('',(),{'__getitem__':lambda s,i:i})()[:,:]
(slice(None, None, None), slice(None, None, None))```
It's a tuple of slices
yes
look up how numpy uses it
yes
i was thinking lua-style function call
>>> def function(_):
... return [1, 2, 3]
...
>>> function (1 > 2) [ 1 ]
2
>>>
this is how it's syntactically valid
yea
i'm gonna continue working on it now
i should add some more stuff to the core module
any ideas? got print/input/int/str/float, can't think of anything else it would really need
there's also stuff like empty_stack
None?
hmm good idea, i'll do that at some point
i've already got null as a dummy identifier
as in, you can assign (well, pop) to null and it'll automatically discard the value
so basically /dev/null
i'm going to make a module for my esolang for super basic file operations
Ayy so it works now
((λx.(λy.(x y))) y) -> ((λx.(λa.(x a))) y)
(1 substitutions)
and it respects free variables in the function body
((λx.((λy.(x y)) y)) y) -> ((λx.((λa.(x a)) y)) y)
I am starting to regret creating this language
lol
Python doesn't allow for emoji variable name 
JS aswell
use haskell
use Elixir
Don't use drugs, stay in school
Shawn McLaughlin pushed to branch master of python-discord/esoteric-python-challenges (Compare changes)
a8522990: add challenge gen
- Shawn McLaughlin
nice
Shawn McLaughlin pushed to branch master of python-discord/esoteric-python-challenges (Compare changes)
sorry for spammerino friends
the annoying guy inside me who learned about formal languages today wants to criticise that sentence
Shawn McLaughlin pushed to branch master of python-discord/esoteric-python-challenges (Compare changes)
New challenge will be up tonight, I was a bit busy creating some scripts to help generate the challenge files/implement some simple test cases
cool
Shawn McLaughlin pushed to branch master of python-discord/esoteric-python-challenges (Compare changes)
Challenge 04 is here! 
This challenge is straight forward: Code golf a maze solver. Details are available in the repository: https://gitlab.com/python-discord/esoteric-python-challenges/tree/master/challenges/04-maze-solver-golf
A couple of notes:
-
This challenge introduces our new simple test-case system. Instructions on how to use it are available in the README in the root directory of the repository! This should help with ambiguous requirements.
-
The entire repository (and the solutions submitted to it) is now licensed under GPLv3 (info: https://www.gnu.org/licenses/quick-guide-gplv3.html
By submitting code you understand and agree to the licensing terms.
Happy Hacking ❤
so short instead of fast, will be interesting to see
for these smaller mazes I wonder if it would be better to fill all white with dots, then remove any dots which aren't connected or have no use
that sounds like an optimization
you don't want that
unless of course you want a stable and fast solution
I've never written any algorithms to solve mazes so I'm wondering myself what kind of solution will end up being more golfable, something more bruteforcy or an actual algorithm
and also whether writing an algorithm using the maze as a 2d list vs parsing the maze into a graph structure
shrugs
well is a maze where all dots are filled in count as a valid path
ebbit (ebbit) opened !17 *Add my submission for challenge 03* in python-discord/esoteric-python-challenges: Add my submission for challenge 03
such a beautiful creation
@sick hound No, you can look at the test cases, though they're a bit hard to see in the format they're in in the json file
there's only one valid solution and its the direct path
the most direct path, that is
🤔 lang should be pronounced "u+1F914 lang" or "colon thinking colon lang" on
Discord, "please no thank you" also suffices.
HAHAHAHA
Shawn McLaughlin (shawnmcla) merged !17 *Add my submission for challenge 03* in python-discord/esoteric-python-challenges: Add my submission for challenge 03
Shawn McLaughlin pushed to branch master of python-discord/esoteric-python-challenges (Compare changes)
fc09523f: add my submission for challenge 03
"thinking_face" lang is an esoteric pure emoji language by ebbit
b1851492: Merge branch 'master' into ebbit
c11f513e: Merge branch 'master' into 'master'
Add my submission for challenge 03
See merge request python-discord/esoteric-python-challenges!17 - Shawn McLaughlin
@frosty wyvern i'm nearly done with my submission for challenge four but
Expected Output:
#####################
### ## ##...#########
##........#..########
##.#########. # #
# . #.###....#### # #
##.##.###.## #### # #
#####.###.## #### #
# .....#### ### ##
## ###### ######
#####################
Actual Output:
#####################
### ## ##...#########
##........#..########
##.#########. #
# . #.###....#### # #
##.##.###.## #### # #
#####.###.## #### #
# .....#### ### ##
## ###### ######
#####################
am i blind or is there no difference
this is test case 2
there's no extra trailing whitespace or anything
diff time
i'm messing with the test runner to get the actual variables out
oops
you deleted a wall >:(
lol
unless i fucked up the test cases
which is very likely actually.
i mean it passed the first two tests so i'm very confused how it deleted wall here
I hope to be submitting a small version of my project for #03 tonight or tomorrow
but yeah about the question of how golfable brute force maze functions are
mine is a depth first search
hold on trying to fix this dumb shit : )))
and it's about 221 characters depending on if it passes the fixed tests or not
okay so
i fixed the test(I think)
HOWEVER
The thing I broke in the original test
meant that there was no test case where it was possible for a path to loop in circles
so lets see if it still passes haha
uhm
do you wanna just monkey patch your testcases.json file
sure why not
[
{
"input": "###S###\n# #\n## ## #\n## ## #\n##E####",
"expected_output": "###.###\n# .. #\n##.## #\n##.## #\n##.####"
},
{
"input": "##########\nS ###\n### ## ###\n### #### E\n# #\n##########",
"expected_output": "##########\n.... ###\n###.## ###\n###.####..\n# ......#\n##########"
},
{
"input": "#####################\n### ## ## #########\n## # ########\n## ######### #\n# #S### #### # #\n##E## ### ## #### # #\n##### ### ## #### #\n# #### ### ##\n## ###### ######\n#####################",
"expected_output": "#####################\n### ## ##...#########\n##........#..########\n##.#########. #\n# . #.###....#### # #\n##.##.###.## #### # #\n#####.###.## #### #\n# .....#### ### ##\n## ###### ######\n#####################"
}
]
pfp pun intended
lemme know if this works
all test cases passed
weee :D
hold on lemme fix up my solution for any easy characters and then i'll push this version
Shawn McLaughlin pushed to branch master of python-discord/esoteric-python-challenges (Compare changes)
13ee0c89: fix testcase bug
- Shawn McLaughlin
a5b21d85: Merge branch 'master' of gitlab.com:python-discord/esoteric-python-challenges
- Shawn McLaughlin
nm there we go
IMPORTANT NOTICE FOR THOSE WHO ALREADY PULLED CHALLENGE 04
There was a bug, I messed up one of the test cases. Please ensure that you pull the updated testcases.json file, sorry for any inconvenience and shout out to @pine edge for making me realize it 
Morado walrus (morado.walrus) opened !18 *added solution to #04* in python-discord/esoteric-python-challenges: added solution to #04
haha whoops that's a merge conflict
but yeah i wrote this function so it will always return the shortest path, but if there is a second, longer path, it will find it
and then because it's written to take advantage of the fact that only one path exists it will immediately crash
so if it returns, it is the shortest path
gah is there a way to resolve that on the site
if not can you just do a new commit and only include your solution file :DDD
sure
i was hoping it would merge automatically because we both have the same file, but it's upset that we made the same file separately
shit, that looks super fun
I wish I had time to do that maze challenge
maybe I'll do it later on
In this post I’d like to test limits of python aiohttp and check its performance in terms of requests per minute. Everyone knows that asynchronous code perf...
I’m jizzing my pants
Props to @polar wolf for finding it!
❤
AnonymousDapper (AnonymousDapper) opened !19 *Master* in python-discord/esoteric-python-challenges
@frosty wyvern I got u fam. Its more or less done, arithmetic operators are gonna take some design rewrite i think, so i didnt add those in
🤔 needs some more esothericalness
Shawn McLaughlin (shawnmcla) closed !18 *added solution to #04* in python-discord/esoteric-python-challenges
Shawn McLaughlin (shawnmcla) merged !19 *Master* in python-discord/esoteric-python-challenges
Shawn McLaughlin pushed to branch master of python-discord/esoteric-python-challenges (Compare changes)
@pine edge please re-MR with only your solution file and not the modified testcases
Morado walrus (morado.walrus) opened !20 *the same thing but i just did the merge on command line* in python-discord/esoteric-python-challenges
it's really a valuable skill to have
also if you just ping and ask me to fix it, any commits are automatically put into existing merge requests iirc
so no cancel/remake has to be done
lol was just trying to merge from my phone gimme a break :P
Shawn McLaughlin pushed to branch master of python-discord/esoteric-python-challenges (Compare changes)
Shawn McLaughlin (shawnmcla) merged !20 *the same thing but i just did the merge on command line* in python-discord/esoteric-python-challenges
@frosty wyvern isn't latest challenge just to write Dijkstra and making distances with walls a ridiculously high number?
@grave rover hi
Sup daps
@grave rover What? The challenge is code golf. The algorithm is irrelevant, it's whatever solution you can write the most succinctly
But isn't that realistically the best method to do this other than trying everything and taking the shortest path?
doesn't matter, golf it
@grave rover The goal is simple, write ANY code that solves the problem, it doesn't matter if it's efficient or not, as long as it solves the problem, and make it as short as possible
Perhaps Djikstras, perhaps a bruteforce solution. Depends how you implement it and who can implement it in the fewest characters
what do i win if nobody else commits until next challenge
What, we're already up to challenge 4?!
I'm not made for these challenges
Not great at algorithms, so my first thought goes to "what would be the most wacky solution that's still technically within the rules"
Well, ok, train a machine learning algorithm on the solutions, obviously
But, no imports!
Well, we use pip inline with:
from pip._internal import main; main('install tensorflow')
But that's an import!
Well, we put it in a different .py file that's on a GitHub gist, which is then linked to by a bit.ly link
To avoid imports of urllib, we determine the OS type by attempting to read OS-specific files
We then read the contents of urllib/request.py and exec:
exec(open('C:\\Program Files\\Python36\\Lib\\urllib\\request.py').read())
Now that we have urllib in our grubby not rule breaking technically probably please don't hurt me Shawn hands, we get the file:
urlretrieve('https://https://bit.ly/2E8iGuS', filename='evil.py')
exec(open('evil.py').read())
Then we simply call our solution, where i is the test input string:
f(i)
@frosty wyvern How's that
name resolution fails for me. It's not compatible with pihole
Well, that just adds complications, because now I have to change the DNS settings of the local system to not be pihole
Why ya gotta complicate thangs Drappar'?
reminds me of this one xkcd
Which one?
the uh, the one where this old guy sends a youtube link in an extremely roundabout way
This is how my mind works.
Elegant mathematical solution? Nah.
Glue available pieces together until I have something that does approximately the same thing? Yup.
Oh that rings a faint bell
Ah yes, that one
yeah that's what your devilish thing reminded me of
hmm that is probably more efficient than my code at times
the tests don't guarantee an ethernet cable is plugged in but it's too far to turn back now
i keep ending up writing recursive solutions for these
because loops are expensive but f(x) isn't
not in code golf
maze solver:
return input.replace(" ",".") # im really bad at mazes
haha
peak efficiency
that won't pass the test cases but ok :D
Senpai Shawn, how did you like my answer?
Creative breaking of unwritten rules, I like it
Thank you 
just a couple more days until i win by default
is there a language, where we have DNA sequences as syntax?
there might be in an off topic channel
unless you're suggesting DNA sequences as an esoteric language for the challenge
or an esoteric implementation of DNA sequences as a language
(technically you can make a quaternary system out of DNA to represent instructions)
Challenges Update
Greetings. Esoteric Python challenges will be on hiatus starting now and for the duration of the code jam. If you haven't signed up yet and would like to, hurry because the signups close this weekend!
https://pythondiscord.com/jams
As for the challenges and this channel in particular, do feel free to take a look at the various challenges if you haven't yet and try your hand at any of them! I welcome Merge Requests for solution submissions even for past challenges. If you have any challenge suggestions, comments, ideas on how we could make #esoteric-python events more exciting, etc. Feel free to DM me on Discord. We only have a small handful of people who regularly participate in the challenges which is fine, given that this is esoteric python and not everyone is interested in Golfing or various challenges but I would still love ideas on how we could get more people involved!
Our GitLab Repository for challenges: https://gitlab.com/python-discord/esoteric-python-challenges/
@pallid schooner no but most of the operations dna based computing does is equivalent to regular expressions
actually mit made one but still regexes
Simple and useless Python unix-like Pipe implementation 
""" P I P E S R G O O D"""
class PYEDPIPER:
def __init__(self):
self.tmp = None
def __or__(self, other):
args = []
if type(other) is tuple:
args = other[1:]
other = other[0]
if self.tmp:
self.tmp = other(self.tmp, *args)
else:
if callable(other):
self.tmp = other(*args)
else:
self.tmp = other
return self
def ret2():
return 2
def double_x(x):
return x*2
def add_1(x):
return x+1
P = PYEDPIPER()
import math
(P
| 2
| double_x
| add_1
| (math.pow, 2)
| int
| (int.__sub__, 73)
| abs
| print
)
# >>> 48
CAPS class names 
oh hush

""" Unix-like pipe syntax for chaining functions """
import math
class Piper:
def __init__(self):
self.tmp = None
def __or__(self, other):
args = []
if type(other) is tuple:
args = other[1:]
other = other[0]
if self.tmp:
self.tmp = other(self.tmp, *args)
else:
if callable(other):
self.tmp = other(*args)
else:
self.tmp = other
return self
def __call__(self, init):
self.tmp = init
return self
if __name__ == "__main__":
""" Simple demo functions """
def ret2():
return 2
def double_x(x):
return x*2
def add_1(x):
return x+1
P = Piper()
(P(2)
| double_x
| add_1
| (math.pow, 2)
| int
| (int.__sub__, 73)
| abs
| print
)
# >>> 48
Happy bytes?
;p
if you implement bashs subshell feature I'd like it
.<
:P
python one liner i made to encode a string using a variation of the caesar cipher, where every letter is shifted by its position in the string
print("".join([list(map(chr, range(97, 123)))[(list(map(chr, range(97, 123))).index(char)+i) % len(list(map(chr, range(97, 123))))] if char in list(map(chr, range(97, 123))) else char for i, char in enumerate(input("string to encode: "))]))```
thats not a variation of the caesar cipher, the caesar cipher has at least some kind of key
how does it makes this not a variation?
0/10 not enough list(map(chr, range(97, 123)))
lol
that just alpahabet
oh, and everyoen calls it a caesar cipher
the normal one
how is mine not?
yes
and caesar chose 3
but he had the option to chose n
here nobody has the option to choose anything
you need to be able to select a key
mathematically speaking a symmetric encryption function (which is what caesar cipher is) is a function taking the clear text and a key
what it does with that is up to the function
fixed it:
print("".join([list(map(chr, range(97, 123)))[(list(map(chr, range(97, 123))).index(char)+i) % len(list(map(chr, range(97, 123))))] if char in list(map(chr, range(97, 123))) else char for i, char in enumerate(input("string to encode: "), int(input("key: ")))]))
Caesar trash for not using PGP smh 😤
somebody should make a PGP Fork which relies on caesar cipher instead of modern symmetric ciphers
ROT13
PGP Fork which relies on ROT13 and the whole key thing is just an honour system
okay time to improve my Pyed Piper module
I should add another o perator that creates a Thread
like..
hmm
i wanna add concurrency
im not sure how to model it though
I need an esoteric code guru like @brisk zenith
I guess I could just do like
hello
okay
I want to add onto my Piping shitcode some concurrency like
P
| a
| b
& a1
& a2
errr
this is gonna get complicated vvv quick
hmm okay
cause what are the inputs where do the outputs even go
how does the P object handle waiting for threads
imma start cleaning the apt and think about it, help me brainstorm you little genius
(btw why don't you use metaclasses to make it so you don't really need to initialise your class when you want to use it?)
(I don't know how to use metaclasses I've never used em)
can you convert my current code into a metaclass so I can learn from the sensei
i'm thinking something like
(P ([1, 2, 3, 4, 5])
| print # prints the list
& "my_thread", sum # spawn a thread called "my_thread"
| print # still prints the list
@ "my_thread" # get (or wait for) the output of the thread
| print # now prints the result of the `sum`
)
wow thank you syntax
a metaclass is basically what creates class objects
cause everything is an object, even classes
the main metaclass is actually type (remember how i used that to define a class in my one-liners?)
so subclassing type allows you to make a metaclass
and i'm thinking that you could pass multiple arguments like ```py
(P (2)
| print, "my number =", ... # my number = 2
| print, ..., "is my number" # 2 is my number
)
cause that's valid syntax
it just creates a tuple of (func, *args)
and ... would be replaced with the pipe value
you're a pipe value
wow thank you so much! :D
but you should also allow people to change this magic ... value in case they want to actually pass Ellipsis to a function
in which case you would make a different singleton so that you can check with is consistently
btw doing | fn, arg, arg doesnt seem to work without the ( )
really?
unless its just my current code thats fucky
>>> P(2) | 2, 3, 4 | "heck"
Traceback (most recent call last):
File "<input>", line 1, in <module>
P(2) | 2, 3, 4 | "heck"
NameError: name 'P' is not defined
>>>
no syntaxerror here
in the middle of sweeping so cant rly debug rn
when is , evaluated
doesnt create a tuple
yeah okay
i'm rethinking this and don't think a metaclass would be ideal if we want user-changeable values
i.e if they want to change the value of the ...
maybe you could have a bunch of singletons for different things
teeing would be interesting
like, ```py
(P(2)
| print T # prints the value of the pipe (2) but also replaces the return of print with the original pipe value of 2
)
well, however you want your syntax to work
teeing? well, you have tee in linux which sorta does something similar
oo cool
oo is the symbol like a T_ shaped pipe where the shit falls down into something but also keeps going in the same direction
yup
hehe we plumbers now
beautiful
very
and good for pipes
cause the return value of None in print is annoying if you want to keep your original value, for example
Yep
ok well
heres the thing
how would I implement those other symbols
cause they not operators
I make em constants?
that get interpreted?
i don't think they'd need to be operators
what syntax are you going with for arguments?
(P(2)
| (print, T) # prints 2, passes 2 down the pipe
| (print, ...) # prints 2, consumes the value
| print # prints None, because the above `print` returned that
)
is what i'm thinking
yeeeeee
Agreed
hm
I feel like
(P(2)
| (T, print)
| (print, ...)
is a bit more visually appealing
cause the T is closer to the pipes
: )
yeah, it makes more sense
but then, where does the value get passed to the print?
i suppose ... would have to be used there too
so py (P(2) | (T, print, ...) | (print, ...) )
well if it's just a function id say it gets implicitly passed
yeah but what if the function takes multiple arguments
which one is given the pipe value?
whatchu mean
as in,
(btw i think T should be a function/callable object, which executes the function and returns the value)
(P(2)
| T(print, "shawn is", ..., "years old")
| (print, ...)
)```
aw yeah cause thatll just evaluate to the original value and i can just keep chugging along
yup
i don't think ... should be implicitly passed either, cause maybe there's a function that doesn't take any arguments at all
yeah if we're Tee-ing then it might make sense to call something that takes no argument
but like otherwise it kinda ruins the whole pipe thing
yeah true
if ... isnt implicit in regular pipes then its like why bother cause its no longer like a unix pipe at all
at that point im just complicating calling functions LOL
yeah that's a good point to be fair
i suppose if you have a function that needs to be called without any arguments, you could just do T(my_argless_func()) and that would work just as well
but then that requires a normal function call 
Juan we need a stupid project to work on together
we do
yes
Is there a way to create symbols in Python? Guess not eh, guess I can just make a plain object
idea, dms
b'e\0d\0\4\0\4\0d\1\x19\0\2\0d\2\x19\0\3\0\3\0d\3\x19\0\x83\3S\0'``` I just wrote some cpython bytecode manually
This indexes the 0th constant with the 1st, 2nd and 3rd constants, then calls the function with the first name with those arguments in that order without using * or **
very hexing
AHCKULALAYA, you're still writing regular python. You need to open a hex editor to write pure bytecode
that is bytecode represented with python
it's cpython bytecode
@pure dew i'm using python as a way to represent the cpython bytecode I wrote...
that's better lmao
Oh yeah pipes
I've done that before
list(range(10)).apply | (lambda x: x*x) # => [1, 4, 9, 16, ...]
Same with .filter and .first and stuff
map would be better there
actually useful pipes would do multithreaded generator to generator
that'd be neat as fuck
functions could just be automatically wrapped in a generator
python
the python you use is not written in python, at least not the language part
cpython (the interpreter the majority of people uses) is written in C and the enormous stdlib is written in python
then there is the pypy interpreter (also interprets python) which is written in rpython
and then there are a few smaller languages such as hylang for example which is written in python and uses the python vm
jython, a java implementation
what do you even mean by "language written in Python"? You can't write a language in another. That's like saying I write Spanish in French. And interpreters for languages can be (re)written in any language.
#javaisnotpython
^
class WhatAreYouDoingCPython:
def __init__(self, x):
self.x = x
def __hash__(self):
return self.x
print(hash(WhatAreYouDoingCPython(-1)))
hash(-1) is -2 hm
@cunning wave relevent cpython source:
switch(i) {
case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
case 0: return 0;
case 1: return v->ob_digit[0];
}
v is the int object
yes i know why this happens
why
-1 is an internal error code of cpython
so returning python one from the "user code" isnt ok
huh, so it's like "fuck you this is reserved"
kinda
wait so does cpython get upset if you return a C int of -1 like that?
uh how do you even
magic
if you return -1 and you don't set an error string it raises some exception like "An exception was raised but no exception string was set!"
iirc
i never tried catching it because, like, why
unreadable on mobile
it's not your mobile's fault... 
reminds me of that one-line all lambda hello world
Unreadable on desktop too @cunning wave is just bad at formatting
I expect perfection
It is perfect
class Meta(type):
@property
def thing(cls):
pass
@thing.setter
def thing(cls, value):
print('setter was called')
# # # # # # # # # # # # # # # # #
class Blah(metaclass=Meta):
thing = 1
thing = 2```
is there a way to get this to "work" or is it just completely impossible because the class vars are handled before anything to do with the metaclass
(the assignments to thing don't trigger the setter func)
@sick hound object.__setattr__(self, name, value)¶ Called when an attribute assignment is attempted. This is called instead of the normal mechanism (i.e. store the value in the instance dictionary). name is the attribute name, value is the value to be assigned to it.
?
Override setattr instead, it'll make it less of a pain
or @property
i'm not sure if i'm missing something but
- i know what
__setattr__does @ seinfeld :p and overriding it should in theory have the same effect as writing an@propertyso i wasn't sure why you posted that doc quote - overriding
__setattr__doesn't work here, so i went on to try@property-- that's the codeblock i posted
it looks to me like class-var assignments (that are done within the body of the class itself) happen before anything from the metaclass happens, even if Blah.thing = 1 later on would behave appropriately
(so then I'm not sure if this problem in turn has anything to do with that the name of a class isn't bound within its own scope??)
yeah just instance methods, i'm not sure how to describe the "non-method-inclusive scope of a class"
"top-level class statements" lol
class Test:
thing = Test
def test(self):
print(self.thing == Test)
i dont know if it works, i on my windows machine rn
i was asking
🤔 interesting
you can do this with Lua
local variable aboose
ahh ok
whoops sorry for not catching that extra bit of complexity
uhhhh
i checked by disassembling some python functions
and when you set a variable in a class definition like that the bytecode is doing a STORE_NAME
but the thing __setattr__ catches is STORE_ATTR
i can't think of any mechanism short of parsing the program yourself with something like ast to check to see if this happens
TIL you can set __dict__
what happens if you set __dict__ in __slots__
oh shoot that's good seinfeld thank u (and dang 😔)
you can do that jack and it behaves like not setting __slots__ would
but i don't know how it fares performance-wise
pythons URL parsing is weird
the highlighted part is the IP the libraries would access
lmao
like even stdlib fails to agree on one IP
I'm tempted to read the RFC which defines the URI grammar to find out which one is correct
do it
tfw you want to monkeypatch a function written in C
PyEval_GetLocals in cpython/Python/ceval.c
you can access it via ctypes.pythonapi.PyEval_GetLocals but monkeypatching that doesn't work
i mean we are doing grammars in school atm..... so it counts as school work i guess
https://tools.ietf.org/html/rfc3986 @brisk zenith HERE WE GO
welp have fun :D
oh they do ABNF i only know BNF and EBNF 😦
@brisk zenith monkeypatching a function written in C is not easy
you might be able to cast the _FuncPtr from ctypes.pythonapi to a POINTER(c_char) and then write machine code to that
yoinks
but you'd need to make sure that area of memory is writable first
who needs compatibility anyways 
or
cast a CFUNCTYPE/WINFUNCTYPE to a POINTER(c_char) and copy it over
you'd still need to make the C function code writable first though
@cunning wave i dont think thats a valid url
that is a valid URI
after reading the grammar I'd say 1.1.1.1 would be the correct IP to access
Whats the red box?
space
Looking at the grammar, its a valid url
but wtf
the first ip would be the correct one
well ye
it would be so convenient to be able to have a function called whenever a variable is accessed. i can achieve it easily with global variables, but not at all with local variables.
this is what the locals builtin does ```c
static PyObject *
builtin_locals_impl(PyObject *module)
{
PyObject *d;
d = PyEval_GetLocals();
Py_XINCREF(d);
return d;
}
that's all very simple
it just calls PyEval_GetLocals and assigns it to a python object
now, accessing a local variable doesn't actually use the locals builtin to look it up, it uses this PyEval_GetLocals function
which is why i want to somehow monkeypatch PyEval_GetLocals
oh no i just found a goto in cpython
#define GETLOCAL(i) (fastlocals[i])```
getting closer to the root of it i suppose
wew
import ctypes
dummy = object()
ctypes.memmove( # move some memory
id(dummy), # into `dummy`
id(True), # from `True`
object.__sizeof__(dummy)
)
print(dummy) # outputs `False` what
try moving the size of True rather than the size of dummy?
causes a segfault
hmm...
huh
fancy
but you can't call the original function... yet
i see
size_of = object.__sizeof__
print(size_of(True))
print(size_of(False))
prints 36 then 32
False is smaller than True
wut
loool
Traceback (most recent call last):
File "testing.py", line 32, in <module>
[1] 27418 segmentation fault (core dumped) python3 testing.py
this is a new one haha
that's real neat
not only did you throw an error
it segfaulted
after your program stopped
a work of art
lolwat
how can i learn esoteric python
then why does it exits lol
just how python works. we abuse it to do stupid stuff
well

for example, making 0 equal to 1
its impossible scientifically
wait, so my production bot code is useless?
lmao
0 is just a symbol we assigned a value to
how is compuiter doesnt give a fuck about science
in lambda calculus, 0 means fuckall
ok im gona try
don't.
im just trying to get more understandings to make my brain like this 
haha small brain people here i guess 
anywhere else in the server is nifty.
ok bye dumb
🤔
cant get called dumb if you call them dumb and leave :weSmart:
haha
!eval ```py
import ctypes
ctypes.memmove(
id(0),
id(1),
object.sizeof(1)
)
print(0 == 1)
@brisk zenith Your eval job has completed.
unknown error, code: 111
heck
Socket error connection refused
u know what im sorry for the joke earlier it doesnt mean to be serious
this code looks like the opposite of dumb
cause i dont unders tand it 
it's dumb becasue you should never do it
haha that's fine, you don't need to understand it.
in a project
yup
can i see example of cool estoic python code? 
reverse_polish = lambda expression: ((lambda PolishStack, split: ((lambda stack: tuple(stack.push(float(item)) if item.isdigit() else stack.operate(item) for item in split(expression)) and stack.pop())(stack=PolishStack())))(PolishStack = type("Stack", (), {"__init__": lambda self: (setattr(self, "_tuple", ())), "push": lambda self, item: (setattr(self, "_tuple", (item, *self._tuple))), "pop": lambda self: ((lambda tmp: tmp.add(self._tuple[0] if self._tuple else None) or setattr(self, "_tuple", self._tuple[1:]) or tmp.pop())(set())), "operate": lambda self, operator: ((lambda operation: self.push(operation(*(self.pop(), self.pop())[::-1])))(operation = {"+": float.__add__, "-": float.__sub__, "/": float.__truediv__, "*": float.__mul__, "^": float.__pow__}[operator]))}), split = lambda string: ((lambda spaces: (string[start:end - 1] for start, end in zip((0, *spaces), (*spaces, len(string) + 1))))(spaces = tuple(index + 1 for index, char in enumerate(string) if char.isspace())))))
oh hey is that my code
yes it is
👌
reverse_polish = lambda expression: ((lambda PolishStack, split: ((lambda stack: tuple(stack.push(float(item)) if item.isdigit() else stack.operate(item) for item in split(expression)) and stack.pop())(stack=PolishStack())))(PolishStack = type("Stack", (), {"init": lambda self: (setattr(self, "_tuple", ())), "push": lambda self, item: (setattr(self, "_tuple", (item, self._tuple))), "pop": lambda self: ((lambda tmp: tmp.add(self._tuple[0] if self._tuple else None) or setattr(self, "_tuple", self._tuple[1:]) or tmp.pop())(set())), "operate": lambda self, operator: ((lambda operation: self.push(operation((self.pop(), self.pop())[::-1])))(operation = {"+": float.add, "-": float.sub, "/": float.truediv, "*": float.mul, "^": float.pow}[operator]))}), split = lambda string: ((lambda spaces: (string[start:end - 1] for start, end in zip((0, *spaces), (*spaces, len(string) + 1))))(spaces = tuple(index + 1 for index, char in enumerate(string) if char.isspace())))))
"""
Annotated version
wow
oh
we look at the same 
haha
u write that sir spooky?
i did.
wow
i'd never write code like that in actual projects
now i know why you are spooky AND scary alpaca
also uh this
line_gen = ((t, r, st) ->((tran, text) ->(derot ->(lines ->(raw_lines ->(raw_words ->(words ->(shuf -> ((sli, sli_len) ->(raw_sent ->(sentences ->[sent[0].upper() + sent[1:] for sent in sentences])(derot[3].join(ss) + r.choice((derot[63], derot[63] * 2, derot[855], derot[477] + derot[475:477])) for ss in raw_sent))([sli[i:i + sli_len] for i in range(0, len(sli), sli_len)]))(shuf[:(len(shuf) |> r.randrange)], r.randrange(3, 15)))(r.sample(r.sample(words * 3, k=len(words) * 3), k=len(words) * 3)))(list(map(w -> w.lower(), filter(w -> w != str(), raw_words)))))(reduce((l, ll) -> (l, ll) |*> (+), raw_lines)))(map((raw -> [s.strip(st.punctuation + st.whitespace) for s in raw.lower().split()]), lines)))(filter(s -> s != str(), derot.splitlines())))(text.translate(tran)))(str.maketrans(t.d), t.s))((def -> sys = __import__("sys"); io = __import__("io"); old = sys.stdout; sys.stdout = io.StringIO(); __ = __import__("this"); sys.stdout = old; __)(), __import__("random"), __import__("string"))```
technically coconut, but its a python superset
very good
because it is the smallest number i think
uhh
!e print(object.sizeof(0), object.sizeof(1), object.sizeof(2))
@frosty wyvern Your eval job has completed.
24 28 28
!e print(object.sizeof(-1))
@frosty wyvern Your eval job has completed.
type object 'object' has no attribute 'sizeof'
!e print(object.sizeof(-1))


