#esoteric-python
1 messages · Page 59 of 1
holy fuck i think it's done
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())))(operation = {"+": float.__add__, "−": float.__sub__, "÷": float.__truediv__, "×": float.__mul__}[operator]))}), split = lambda string: ((lambda spaces: (string[start:end - 1] for start, end in zip((0, *spaces), spaces)))(spaces = tuple(index + 1 for index, char in enumerate(string) if char.isspace())))))```
>>> reverse_polish("15 7 1 1 + − ÷ 3 × 2 1 1 + + −")
4.0
>>>
@frosty wyvern one statement :D
damn
wait it isn't correct
this is disappointing, it's supposed to equal 5 there i believe.
I have a version i quickly put togheter that for now only works with single digit numbers
a={}
for c in map(lambda b:b.isdigit() and (a.update({len(a):b}) or True) or b==" " or a.update({len(a)-2:eval(a.pop(len(a)-1)+b+a.pop(len(a)-1))}), "1 3 +"): pass
print(a[0])
you can compress that a bunch already, though i am impressed that you managed to use a dict like that.
the problem about my code is that i have no fucking idea where the bug is occurring :P
like yes i totally know exactly where that <generator object <lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<genexpr> at 0x7fdedf8f3660> is.
:D
yeah i figured it out, i wasn't doing the last operation and i got my operands mixed up.
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())))))
this is the working code now. (for #challenge1)
wow
the operators from the input are some weird unicode things, but those are what's used in the examples provided so i'm using them.
(like ÷×−)
(and you can see the expanded/commented code here: https://paste.pythondiscord.com/ujuduzizif.py)
thanks :D
now do it with lisp
now go away
Welcome to the club Shawn
haha, lots of things.
That is, absolutely amazing
also im sorry I didnt notice the example I copy pasted used weird symbols lmao
I guess it's part of the challenge now :^)
lmao fair enough. im glad people find the code interesting c:
k='*-/+^×−÷';v=b'\x14\0',b'\x18\0',b'\x1b\0',b'\x17\0',b'\x13\0';m=dict(zip(k,v*2));b=b'';e=d='';n=();x=0;s=lambda d,n:d in n and(n,n.index(d))or((*n,d),len(n))
for c in input()+' ':
if c.isdigit():d+=c
elif d:x+=1;n,i=s(int(d),n);b+=bytes((100,i));d=e
if c in m:b+=m[c];x-=1
x-1 and 1/0;f=lambda:0;f.__code__=type(f.__code__)(0,0,0,x,0,b+b'S\0',n,(),(),e,e,0,b);print(f())``` #challenge1
m={'+':b'\x17\0','*':b'\x14\0','-':b'\x18\0','/':b'\x1b\0','×':b'\x14\0','−':b'\x18\0','÷':b'\x1b\0'} # map operators to python bytecode that executes that operator
b=b'' # code
d='' # number
n=() # consts
x=0 # number of numbers
o=0 # number of operators
def s(d,n): # search
try:return(n,n.index(d)) # get the index
except:return((*n,d),len(n)) # add it
for c in input()+' ': # add space to handle numbers at the end
if c.isdigit():d+=c
elif d: # end of a number
x+=1 # increment number counter
d=int(d)
n,i=s(d,n) # search for number in constants
b+=bytes((100,i)) # 100 = LOAD_CONST
d='' # reset the number
if c in m: # operator
b+=m[c]
o+=1 # increment operator counter
x-o-1 and 1/0 # if x-o-1 is not 0 then the expression is broken, raise an error
f=lambda:None
f.__code__=type(f.__code__)(0,0,0,x,0,b+b'S\0',n,(),(),'','',0,b'') # create a code object
print(f()) # execute the code object``` ungolfed explained version
yes, lambdas for days
(i've golfed it a bit more now)
nifty
when will the repo for archiving the challenge submissions be made?
Oh I made a github repo, I'll put these up in a jiffy
These are beautiful
Unless you guys wanna make PRs into it but it sounds like too much work
it's up to you, i don't mind.
^
i just edited mine so it works with *+/- rather than the unicode examples
i could also make it allow ^ for power and whatnot, actually.
there we go.
>>> reverse_polish("9 5 3 + 2 4 ^ - +")
1.0
>>>
Pastebin what do you want your name to be I'll credit it in the file
"pastebin"
oki c:
also i've updated mine to allow ^ for power too
Quantum what do you want your credited name to be
who me?
oh, i'll be "juan (kingdom5500)" if you don't mind c:

https://github.com/shawnmcla/python-discord-challenges-archive/tree/master/submissions/challenge1
The two submissions so far are in here 😃
don't look at my repos it's a graveyard
can mine be renamed to juan.py please 👀
oyea mb
thanks :D
I'm so lazy that I'm creating/editing the files directly on the Github website 
That'd be great cause I have no clue how yours works 😄
i posted a link for it but it's an older version, so lemme do it again.
https://paste.pythondiscord.com/hevaveqifa.py @frosty wyvern i believe this is correct.
this is beautiful
and I mean that in the most atrocious of ways
You can get around the no lists limitation by using a deque
nooo no imports
yes just don't import it too hard :^)
oh heck imports 🤔
# through its parameters, such as an entire Stack class.``` lmao
lmao
i was debating on declaring the stack class as a default argument in the function definition, but /shrug
i hope the comments there make it somewhat readable :P
yeah haha, tho im learning some things by reading it, like the way you declared the class 😛
haha
f u n c t i o n a l
"push": lambda self, item: (
...
)
is the same as
def push(self, item):
...
yeah, makes sense
didnt realize you could create classes with type()
though I think Ive seen it but its not something I retained cause
why
yeah, that's how metaclasses control how classes are made
sorta
type is a metaclass, i mean.
i only touched on them yesterday
The same way i did
yes, that's a good skill that most people don't have
By being helpful
exactly
I mean I also understand programming concepts, but im not all that familiar with python's inner workings or its stdlib 😃
Most of my experience comes from other languages like C# and JS
shudders
pastebin's code submission is actually really cool once you understand it.
I still have to look at that one
it constructs the cpython bytecode required to evaluate the expression given, then turns that bytecode into a function which is then executed.
wtf
yeah it's a really cool idea.
I retire
+1 to @sick hound
How did you devise this solution
both me and pastebin have spent (perhaps too much) time fucking with cpython bytecode
so it doesn't surprise me that this is the solution he's submitted haha
funsies
did you see my project that creates a function decorator to make C++'s cin and cout syntactically correct in python?
using cpython's built-in stack avoids creating a stack without lists :)
yeah, that's really smart.
brillian
the call stack and whatever.
haha, well this is the sort of stuff i do when i have nothing better to do. :D
i wonder if you can make a reverse polish notation evaluator using the call stack as the stack
you could if you push the float.__add__ etc. functions
and also push the values as well.
hmm
in the right order.
i imagine
though it would be quite tricky without clobbering the actual call stack, actually.
i have an idea
pastebins code doesnt work on my machine
you'll need a specific version of python, probably
so not micropython?
nope, it relies on the cpython implementation :P
and a fairly recent one at that, i believe
i cant imagine how i'd install micropython on my laptop tho
oh by the way, i think we should show some appreciation for @frosty wyvern for organising this little event thing :D
Oh you 😉 Y'all set the bar too high no one else is gonna enter now
hey, i don't see why other people can't give this challenge a little go. @fallen heath is currently working on a simple solution to this and i feel like other people should be doing something like this too. you don't have to use wacky concepts to have a good submission.
I should probably try to tackle my own challenge eh
yes shawn, do it :D
I'm a simple man, I see a challenge and I skedaddle
very well
hi uh
copypasting thing ehre
currently we've got 100 characters
over at the challenges discord server
if you get a shorter one i'll copypaste it over
im so bad at golf lmao, ive never done any type of code golf
i made a stack class but its not as cool as yours juan lol
class s:
def i(s,v):s.s=(v,)
def m(s,v):s.s=(*s.s,v)
def p(s):t=s.s[-1];s.s=s.s[:-1];return t
literally just a minified class
😦
haha, it works in exactly the same way though, so that's nifty.
im debating adding the init method
except your stack pushes onto the end of the tuple, mine pushed onto the beginning.
right now i do s().i()
but idk how many times id create a stack
prob once so
i save characters
wee
though the annoying thing about using actuaal constructs like class and def is that syntax is stricter
i could have done py type("Stack", (), {...})() to initialise mine immediately but i didn't
but anywho, gotta start somewhere
I guess there's no point trying to come up with the smallest thing from the start, i should build then try to shave where i can
since I'm new to this golf thing ;p
that's what i do when creating functional programs, sorta.
i make the full thing without the functional paradigm, then i slowly turn it more and more into hell afterwards
LOL
although actually, i didn't do that in this case.
by the way we're still at 100 chars
i sorta wrote it with lambdas from the get-go
oh juan i wanna see you wreck that one gogogo
haha, making that functional would be fun but i don't really know anything about chess so /shrug
basically if you have a position (2,3)
with the knight you can move either 1 slot u/d 2 slots l/r
or 2 slots u/d 1 slot l/r
yeah its simple Juan you dont need to know chess
hm okay
😄
so, should i make that functional then?
just make it mindbending.
i have an interesting idea for that, actually.
Reading y'all's code is like consciousness expanding
first thing that comes to mind is a generator that makes lambdas haha
lemme see what i can do.
LOOOOOOOOOL
oh i see.
values from (0,0) to (7,)
must take in 2 inputs somehow and print/return 2 values
must be either stdout or visibile in an IDE
such as replit and the lambda x=lam... ... ... x(0,2)
kk
just for reference this is the shortest solution so far
n=range(8)
k=lambda a,b:[(i,j)for i in n for j in n if min(i!=a,abs(i-a)+abs(j-b)==3,a|b in n,j!=b)]
yikes
knight_moves = lambda x, y: (
[(x, y) for x, y in (
func(x, y) for func in (
(
lambda x_offset, y_offset: (
lambda x, y: (
x + x_offset,
y + y_offset
)
)
)(x_offset, y_offset)
for x_offset in (-2, -1, 1, 2)
for y_offset in (-2, -1, 1, 2)
if abs(y_offset) != abs(x_offset)
)
) if (8 > x > 0) and (8 > y > 0)]
)
this generates a function for every possible move, calls each one, then filters the result. @frosty wyvern @shy vector :P
that makes me physically ill
one thing i love about these single-statement codes is that the indentation doesn't matter at all
knight_moves = lambda x, y: (
[(x, y) for x, y in (
func(x, y) for func in (
(
lambda x_offset, y_offset: (
lambda x, y: (
x + x_offset,
y + y_offset
)
)
)(x_offset, y_offset)
for x_offset in (-2, -1, 1, 2)
for y_offset in (-2, -1, 1, 2)
if abs(y_offset) != abs(x_offset)
)
) if (8 > x > 0) and (8 > y > 0)]
)
true
barfs
Also I'm getting a division by zero error in my code and I have no clue why 😄
I guess I have to learn to use pdb now :))0
oof
my code as one line:
knight_moves = lambda x, y: ([(x, y) for x, y in (func(x, y) for func in ((lambda x_offset, y_offset: (lambda x, y: (x + x_offset, y + y_offset)))(x_offset, y_offset) for x_offset in (-2, -1, 1, 2) for y_offset in (-2, -1, 1, 2) if abs(y_offset) != abs(x_offset))) if (8 > x > 0) and (8 > y > 0)])
LOL
golfed even more
a=lambda x,y:([(x,y)for x,y in(d(x,y)for d in((lambda b,c:(lambda x,y:(x+b,y+c)))(b,c)for b in(-2,-1,1,2)for c in(-2,-1,1,2)if abs(c)!=abs(b)))if(8>x>0)and(8>y>0)])
Actual footage of me trying to code golf
pin this now.
golfed even more
z=-2,-1,1,2;a=lambda x,y:([(x,y)for x,y in(d(x,y)for d in((lambda b,c:(lambda x,y:(x+b,y+c)))(b,c)for b in(z)for c in(z)if abs(c)!=abs(b)))if(8>x>0)and(8>y>0)])
ewwww two statements
trump is a python coder ? 🤔
who said shawn was a python coder?

Whoever it was talking about functional python, there's Coconut: http://coconut-lang.org/
Maybe we can have that as an option for these challenges too?
Simple, elegant, Pythonic functional programming.
@pure dew hey thanks, i'll take a look at that soon
i feel like i am getting better at creating functional python programs given the limitations of the python lambda by doing these sorts of challenges, so that's interesting.
anyone want a code golf challenge
I mean we already have one going on :^)
yeah I'm just interested in how far ppl here can push it
I don't like golfing but I like the solutions other people make
can i make a functional solution instead? :D
same
I love any kind of creative coding
whethter its golf or functional atrocities
anyway
Fractal
Let's observe the fractal F_n, which is defined in the following way recursively:
- Fractal F_1 is a 1x1 -grid, which has one black square.
- Fractal F_k (when k > 1) is obtained by arranging four fractals F_k-1 as a square and inverting the colour of the bottom-right square.
For example F_4 looks like the following:
########
#.#.#.#.
##..##..
#..##..#
####....
#.#..#.#
##....##
#..#.##.
Your task is to form the fractal F_n```
Can we pin that coconut link and allow it for these challenges?
ooh that looks interesting ava.
i'm gonna try to make a functional solution for it.
whew im pretty much done my RPN golf
yes good :D
Eh it's alright I guess
It's much less Arcane than yalls submissions :p
But there's a few limitations like the equation must be formatted perfectly no trailing or leading spaces and it only accepts the funky symbols found in "15 7 1 1 + − ÷ 3 × 2 1 1 + + −"
oshit hold on i can save like 4 bytes if i put the class outside the function
hey shawn
hmmm fudge I need a line break between my class and a function
can't i just spawn dc
what's dc
good question
now that's a fuyn challenge
thank you bro
See if I can get a syscall to run
I can replace the current process with something
if I get access to execve i can tell python to replace itself with dc or whatever
Hmm, interesting, the Python repl complains about syntax but not if I run the script normally
odd
the channel topic should be updated btw. the last bit, i mean.
done
class S:
def __init__(s):s.s=tuple()
def m(s,v):s.s=(*s.s,v)
def p(s):t=s.s[-1];s.s=s.s[:-1];return t
o=lambda z,x,y:{"+":x+y,"−":x-y,"÷":x/(y or 1),"×":x*y}[z]
def f(i):
n=r=0
s=S()
for c in i:
if c.isnumeric():n=n*10+int(c);r=1
elif c==' ':
if r:s.m(n);n=r=0
else:s.m(o(c,s.p(),s.p()))
return s.p()
here's my boring af solution
lol
oh nice :D
you had the oppertunity to spell out word 😔
oh LOL
what
oh wait i found a few more byte saves
you can do isdigit rather than isnumeric if you want it to work properly
and save more bytes too

sys = next(c for c in object.__subclasses__()if'ModuleLock'in repr(c)).acquire.__globals__['sys']
os = sys.modules['os']```
list ocmprehension tsk tsk
;p
NO LISTS.
oh wait
hahahahaha
lmaoooo
Golfing this was fun even though I used no real hacky things like the other two haha
:3
>>> import ctypes
>>> libc = ctypes.CDLL(None)
>>> libc.syscall(39)
20809
so somehow i need to do this without importing ctypes
(39 is the getpid syscall btw)
write your own c stdlib
(why can't you use os.getpid())
thats not esoteric enough
(look at the way we get os)
@sick hound interesting idea
we can get os but not ctypes
Unless the following token starts with e or E. You can remove the space following a number.
For instance:
if i==4 and j==4:
pass
Becomes:
if i==4and j==4:
pass
interesting
yup
well too bad that doesnt help my code 😃
it can't begin with e or E because float literals 1e9 etc
'numbers'or'strings' # i know the syntax highlighting looks weird but it works```
yeah I get it, I just never thought that it would work without space
tuples are allowed right?
yes
yes
good good
if tuples weren't allowed both of the existing solutions would break
and there would be no practical solution other than using {0: first, 1: second, ...} dicts :P
okay boys
s = next(c for c in object.__subclasses__()if'ModuleLock'in repr(c)).acquire.__globals__['sys']
o = s.modules['os']
e = input()
o.execve("/bin/dc", ("dc", "-e", e + " p"), {})
we did it
oh, i think pastebin beat me to it, but mine is prettier
not multiplatform enough
LOL
juan if they don't use linux they aren't worth it
wanna golf it a bit more before I put it in the submissions ;p
yeah i will now
you guys are all geniuses
i consider that cheating, but it is an interesting solution anyways haha :D
of course ^-^
hey it is not cheating it is just being rad
i mean.. he did what the instructions said
precisely
Creatively working around rules isn't really cheating shrugs
sure :D
Anyways this is the kind of things I wanna see, how creative people get, it's inspiring 😄
Everyone is a winner except me
the fun thing here is i am also not spawning a new process
i just LOVE the exec syscall
it's my best friend
you login using exec, you run things in your terminal using exec
everyone uses exec!
Doesn't know what exec does
it replaces the running process with another one
ooo
so in this case i switch python into a dc process
but when you run something in the terminal, the terminal forks itself (creates another process of itself) and then that process exec's into the command you want to run
ooooooo
s=next(c for c in object.__subclasses__()if'ModuleLock'in str(c)).acquire.__globals__['sys']
o=s.modules['os']
e=input()
o.execve("/bin/dc",("dc","-e",e+" p"),{})
this is as golfed as I can get
if anyone has any more ideas please do ping
this was an awesome challenge, just a coincidence i happened to know about dc
dc is pretty damn cool
dont bother with saving o
oh yeah good idea
just next(...).modules['os'].execve("dc", ("dc", "-e", input()+" p"),{})
yeah
next(c for c in object.__subclasses__()if'ModuleLock'in str(c)).acquire.__globals__['sys'].modules['os'].execve("/bin/dc",("dc","-e",input()+"p"),{})
this bad boy is a one liner now
u may be able to remove /bin/ if it's in your path
and it'd become cross platform
@brisk zenith coconut is cool
Y = f -> (*args) -> f(Y(f))(*args)
fac = Y(f -> n -> 1 if n < 2 else n * f(n - 1))
fac(5) |> print
oh hell is that a y combinator
i'm trying to understand those in regular python haha
its a bad one
a what?
it shouldnt be recursive, but im still wrapping my head around the non-recursive version
"In functional programming, the Y combinator can be used to formally define recursive functions in a programming language that does not support recursion."
its a (non-recursive) function that turns a non-recursive function into a recursive function @tropic gulch
🤔
oh rite
In computer science's combinatory logic, a fixed-point combinator (or fixpoint combinator) is a higher-order function fix that, for any function f that has an attractive fixed point, returns a fixed point x of that function. A fixed point of a function is a value that, when a...
dc is not a default package, and it's not on Windows
But it does accomplish the objective...
ah it is owned by bc
λ yay -Qs bc
local/bc 1.07.1-1
An arbitrary precision calculator language
shame
Joseph may I add your solution to our archives (: credit to name Joseph?
Sure thing my guy
do mention it is not compatible on all systems or without the bc package though
yep
@wind maple for your fractal challenge, will we allow imports?
anythings allowed
oh okay
here we go ```py
fractal = lambda factor: (lambda invert, expand: (import("functools").reduce(lambda value, _: (expand(value, value) + "\n" + expand(value, invert(value))), range(factor - 1), "#")))(invert=lambda string: (lambda temp_char: (string.replace(".", temp_char).replace("#", ".").replace(temp_char, "#")))(temp_char=chr(ord(max(string)) + 1)), expand=lambda first, second: ("\n".join(one + two for one, two in zip(first.split(), second.split()))))
hm @wind maple can you confirm this works?
oh okay, sure.
>>> print(fractal(4))
########
#.#.#.#.
##..##..
#..##..#
####....
#.#..#.#
##....##
#..#.##.
looks fine to me though.
>>> print(fractal(6))
################################
#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.
##..##..##..##..##..##..##..##..
#..##..##..##..##..##..##..##..#
####....####....####....####....
#.#..#.##.#..#.##.#..#.##.#..#.#
##....####....####....####....##
#..#.##.#..#.##.#..#.##.#..#.##.
########........########........
#.#.#.#..#.#.#.##.#.#.#..#.#.#.#
##..##....##..####..##....##..##
#..##..#.##..##.#..##..#.##..##.
####........########........####
#.#..#.#.#.##.#.#.#..#.#.#.##.#.
##....##..####..##....##..####..
#..#.##..##.#..##..#.##..##.#..#
################................
#.#.#.#.#.#.#.#..#.#.#.#.#.#.#.#
##..##..##..##....##..##..##..##
#..##..##..##..#.##..##..##..##.
####....####........####....####
#.#..#.##.#..#.#.#.##.#..#.##.#.
##....####....##..####....####..
#..#.##.#..#.##..##.#..#.##.#..#
########................########
#.#.#.#..#.#.#.#.#.#.#.##.#.#.#.
##..##....##..##..##..####..##..
#..##..#.##..##..##..##.#..##..#
####........####....########....
#.#..#.#.#.##.#..#.##.#.#.#..#.#
##....##..####....####..##....##
#..#.##..##.#..#.##.#..##..#.##.
expanded and annotated.
fractal = lambda factor: (
# Below is the "main" part of the function.
lambda invert, expand: (
__import__("functools").reduce(
lambda value, _: (
expand(value, value) + "\n" +
expand(value, invert(value))
), range(factor - 1), "#"
)
)
)(
# A function to invert a string. All '#' are swapped with '.'
invert = lambda string: (
lambda temp_char: (
# Replace all occurrences of "." with a temp char.
string.replace(".", temp_char)
.replace("#", ".")
.replace(temp_char, "#")
)
)(
temp_char = chr(ord(max(string)) + 1)
),
# A function to expand each line of a string
# with the lines of another string.
expand = lambda first, second: (
"\n".join(one + two for one, two in zip(
first.split(), second.split()
))
)
)
do you usually code ina functional style though like in every day use
nah, that's impractical with python's lambda limitations.
yeah
I enjoy functional-ish programming in JS, syntax is a bit better for it
I was learning Haskell for a bit but
i've never used a proper functional programming language though
after learning the 30th operator symbol i got a bit overwhelmed
lmao
I feel like I might enjoy something like Erlang though if I were to try it
or any other functional language
Haskell doesn't see much use in practical every day life
I mean it sees some but
anywho, it was regardless a good learning experience
sorry back on topic
trying to golf a brainfuck interpreter rn
hmmm
grrr Python's function definition syntax is kind of a pain in the rectum
a functional implementation of python
oooo
how does it work? Does it get like transpiled to regular python from its own language or what
ooh i should make a functional brainfuck interpreter
please do
make it a nice oneliner so we can easily embed it in an !eval command : )
all my functional codes thus far have been one-liners
and i plan to keep it that way :D
@frosty wyvern it gets transpiled to python
you can actually see the output on the website, they've got an interactive interpreter
oh not yet, been a little busy :D
no it really isn't
I see multiple solutions up there using list comprehensions, is that allowed under the no lists rule?
interpreting bf is way easier than writing it
@fallen heath list comprehensions are like [x + 1 for x in whatever]
yes
but you can do generators with (x + 1 for x in whatever)
and set comprehensions with {x + 1 for x in whatever}
and dict comprehensions with {key: value for key, value in zip(iter_one, iter_two)} for example
wait
"list comprehension" simply needs [...]
that 2nd one is valid?
yes
😮
why wouldn't it be?
second is a set
i see
so you'll find that none of the examples above used list comprehensions @fallen heath :)
cpython interns small strings or something
oh are <= 20 length strings cached like -5 < ints < 256
interesting
cpython expands 20 * 's' inside its pyc files
above not
so the first one actually gets expnaded during compilation
I had no idea you could make a generator like that
while the 2nd one is evaluated during runtime
yeah, my code has quite a few of them Grote.
it doesn't even need parentheses if it's the only argument in a function or w/e
so py "\n".join(thing for thing in ("hello", "world")) puts a generator as the first argument to str.join and the method consumes it.
also note
>>> x = ['aaaaaaaaaaaaaaaaaaaaa']
>>> 'a'*21 in x
True
>>> 'a'*21 is'aaaaaaaaaaaaaaaaaaaaa'
False
>>>
I can build a python compiler in python!
code = input("Python Code: ")
print(eval(code))
/s
i can break it
@sick hound that would be a python interpreter at best, i don't see a compiler :P
(gp, but then you don't really compile python)
you can.
Yes it gets compiled from source to bytecode
yeah at least use exec sheeeesh
lmao
and as shawn said, cpython (the reference implementation of python) gets compiled to bytecode, which is then interpreted. (i believe)
reference implementation is not always best implementation
who said it was? :P
lemon the python priest
@vague gust can we have
lemon the python priest
as ot name
It's the best implementation because it by far has the most support and development time put into it
and every other implementation stems from the reference implementation as the name suggests, so /shrug
lambda t:(t[a:b]for a,b in map(lambda a,b,v=lambda x:(y for y,z in enumerate(x)if z==' '):(a,b),(0,*v(t)),(*v(t),len(t))))```
the string,split(t, ' ') i finally got working 😃
oh nice :D
my split was pretty chunky: ```py
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())))))
I saw you using zip, didn't know about that :P
lambda t,v=lambda x:(y for y,z in enumerate(x) if z==' '): (t[a:b]for a,b in zip((0,*v(t)),(*v(t),len(t))))```
new version
Also the previous one only worked because of an assignment earlier in the file so that one didn't actually work :/
oh lol
#challenge1
lambda t, a={},v=lambda x:(y for y,z in enumerate(x) if z==' '):{*map(lambda b: b.strip().isdigit() and (a.update({len(a):b})or True)or b==" " or a.update({len(a)-2:str(eval(f"{a.pop(len(a)-1)} {b} {a.pop(len(a)-1)}"))}),(t[a:b]for a,b in zip((0,*v(t)),(*v(t),len(t)))))} and a[0]```
sure
what is this cooode???
@sick hound read channel desc pls
i would say that's beautiful but i'd be lying
I probably should have tested the submissions 😃
challenge #666: rewrite cpython in python using ctypes
@fallen heath Yours works but only for one operation it seems 😛
@brisk zenith yours seems to work perfectly though
@sick hound yours I can't get to run but you generate bytecode so that's cool
It's not a real contest anyways, it's more a coding exhibit than a coding contest
Grote I'll still add yours to the archive, if you want to make another submission we can add it as well 😃
yeah i get invalid syntax on pastebean's
I didn't try running it as a script though
sometimes repl throws syntax errors for things that work in a script file
though if we discount joseph's I think yours is the only one of the other solutions that actually works for deeper stacks
like 1 2 3 + +
well it's pretty simple when you implement a full stack class haha
lol true
Honestly though seeing all these weird solutions make me realize that I don't care much for having actual contests, at least personally
Yeah, it only takes in strings that are formatted with the operators instead of those fancy icons
Of course if people who participate really want to be competitive then whatever I guess but
I much more enjoy a more relaxed environment where people just come up with all kinds of different crazy solutions
long or short, robust or not
i'm not bothered about being competitive
i'm just having fun making stuff like this.
😄
which is ultimately the goal here, is it not? :D
Yes ❤
@brisk zenith You get invalid syntax with mine???
i do.
in the interpreter or a .py file?
moist-machine
...how
might be the way i pasted it
lemme try again
oh never mind
can confirm it works.
#challenge-1
c = lambda t,q=str.replace:(lambda t,a={},d=dict.update,v=lambda x:(y for y,z in enumerate(x)if z==' '):{*map(lambda b: b.strip().isdigit()and(d(a,{len(a):b})or True)or b==" "or d(a,{len(a)-2:str(eval(f"{a.pop(len(a)-1)}{b} {a.pop(len(a)-1)}"))}),(t[a:b]for a,b in zip((0,*v(t)),(*v(t),len(t)))))}and a[0])(q(q(q(t,'×','*'),'−','-'),'÷','/'))```
Now with support for those fancy characters
wow that makes me want to vomit, it's beautiful, I'll update the entry on the repo soon
Unofficial side-challenge:
Do something wtf using ctypes and stuff like memset
>>> ctypes.cast(id(4), ctypes.POINTER(ctypes.c_int))[6] = 5
>>> 2 + 2
5```
OH MY GOD
I WAS TRYING TO DO SOMETHING LIKE THAT LAST NIGHT
I kept crashing my interpreter though
heck
Thanks Ava
😃
Wouldn't that be hilarious to slip into a Python package
changing values of a bunch of those cached constants
hey (:
Greetings
just thought I'd take that question asked in help-0 about inverting an array of 0's and 1's and try to solve it with a one-liner, comments welcome:
flip = lambda a: reduce(lambda x,y: x+[1-y],[[1]]+a)[1:]
ah I see
flip = lambda a: reduce(lambda x,y: x+[1-y],a,[])
frownyfrog, nice
huh, what does that do?
@brisk zenith flip 0's and 1's in an iterable
oh huh
where did reduce get moved to in python3?
ah
and oops, misread that 😃
yeah
i used functools.reduce in my fractal code for ava
@frosty wyvern even though it's not official, i think ava's challenge should be pinned tbh
apparently i dont have itertools on my system

🤔
I think i broke something
>>> 5 != 3
File "<stdin>", line 1
5 != 3
^
SyntaxError: invalid syntax
>>> 5 <> 3
True
from __future__ import barry_as_FLUFL
oh you guys finally gave a better name to this channel huh 😂
@novel vine didn't work
Oh idk then. I don’t really golf
@fast torrent
>>> 0 or 42
42
>>> 0 and 42
0```
you can use that logic to return a different value
natsu has 118
I did it in 2,800
@fallen heath without changing the func name?
Nice
my own solution is 133
I went for the one line everything approach
neat
Submitting the proper one is for the best
Whats we golfing
The code jam verification thing
oh oh i should submit a functional entry.
i could declare the class functionally, at least.
that would be interesting.
is there a better way to initialise a dummy generator than (_ for _ in ())?
Probably not style wise
So he can throw an exception on one line(_ for _ in ()).throw(...)

(_ for _ in()) 🤷
it's not just for one line, it's so that it can be used in an expression
for example, raise can't be used in lambda expressions
fuck too much terminology.
sweet yup
i should make a little module for assistance with functional programming in python 👀
such as a throw function, as an alternative to the raise statement
How in the world
because you can do for (first, second) in zip(...) for example
so the middle () is a tuple
of nothing 🤔
if you just want an exception, do 0/0
:D
ned batchelder uses it for debugging lol
Just cause a name error
oh nice
though my goal here isn't really throwing exceptions in a golfed way, it's more about how throw exceptions in a lambda statement as a whole. as amazed i am at (0for()in()), it's not really any more elegant than (_ for _ in ())
and it seems like creating a generator atm is the only relatively elegant way to raise exceptions
in a single expression, rather than a statement
oh boy
on the topic of the above: if you ever happen to need n copies of some object x in a list, [x for () in repeat('', n)] works
any empty iterable can be used instead of ''
So I wonder if [[] for () in repeat('', 10)] is at all faster than [[] for _ in range(10)]
say it's something you need copies of 🤷
like the usual "idiom" [[] for _ in range(n)]
>>> [1 for () in repeat('', n)]
File "<stdin>", line 1
SyntaxError: can't assign to ()
works on 3.6 for me ye
itertools.repeat my b
I wonder if that's intentional or not
>>> die = lambda: do_raise(ImportError("This is an error right here."))
>>> die()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
File "lambdatools.py", line 5, in <lambda>
).throw(exception)
File "lambdatools.py", line 4, in <genexpr>
_ for _ in () # Damn, that's a chunky error you've got there.
ImportError: This is an error right here.
>>>
i will mock people in my tracebacks
unpacking empty tuple seems really weird
@sick hound range is twice as fast
>>> timeit.timeit("[1 for () in repeat('', 100)]", globals=globals())
5.638906572999986
>>> timeit.timeit("[1 for _ in range(100)]", globals=globals())
2.948414624999714
Where is this repeat coming from?
itertools
Ah
do you guys think i should create a module for bunch of utilities for functional scripts, with the twist that the module itself is also functional? lmao
range is written in c
funny how that works eh?
ikr
there really isn't a way to catch exceptions in a lambda expression, is there?
@sick hound hey pastebean do you have any not-very-hacky ideas? preferably without imports.
@brisk zenith Not without a function that does it for you
yeah that's what i was thinking
def try_func(f):
try:
return f(), True
except Exception as e:
return e, False``` you'd need to have something like this
@frosty wyvern hi mr shawn please merge https://github.com/shawnmcla/python-discord-challenges-archive/pull/1
your isint function can be changed to simply use mem.isdigit() on your stack updating @fervent vine
@vague gust Shouldn't your commit have replaced execve with execvp?
Cause with the latest commit it doesn't run unless you change it to execvp
that's what i was thinking, but i didn't test it.
@little patrol that was an intentional bug and i was just testing you
Did I just ruin it for the whole channel 
Does that really count as not doing an import?
it even relies on an external program to be installed 🤔

Geez you guys are so much more talented than I am haha
talented is a nice way of putting it
@vague gust I'm gonna decline your mr and tell you that you should be retroactively aborted
shAWN WHY
jk 😃
#abortjoseph
Joseph Banks pushed to branch master of python-discord/esoteric-python-challenges (Compare changes)
We've now move the challenges to GitLab, thanks to Joseph. To make submissions simply either create a merge request with your solution in a file called yourname.py under the challenge directory or as before share your code here and I'll add it for you if you don't want to bother. Feel free to submit more than one solution, just append them to your solution file 😃
Where's my credit, joseph was wrong in his original mr
🤔
yeah but i'm awesome
b-but that's owner privilege
joseph is infallible
this is a fact
owner privileges are a serious problem affecting this community!
some of my best friends are owners and they're both pieces of shit so I know what I'm talking about
hey at least i'm not an owner right :^):^)
at least you guys aren't he who shall not be named level of owners/mods/helpers
also wrong channel for this but since you all were here, shoutouts to the peeps who run this discord and the subreddit, you guys and gals are the greatest 
❤
Shawn McLaughlin pushed to branch master of python-discord/esoteric-python-challenges (Compare changes)
Added some info on how to submit solutions and what not
Thanks btw to all who submitted some solutions so far for this week's problem 😃
If you have challenge suggestions, don't hesitate to let me know! Shoot me a DM or whatever. I'll try to have a new challenge at least every week, sometimes a bit earlier. Always feel free to submit solutions for older challenges, too! I lie to stress that this is not a serious competition. The goal is to have fun and code 
Shawn McLaughlin
We related it one way or another
my last name is McLaughlin, capital L and all
are we allowed to use eval in the reverse polish challenge?
i used eval in mine @teal rune
keep in mind the challange uses a different * / and - from the normal python ones
i used eval with a str.replace
yeah I just checked your contrib on the github mentioned in the pinned post
(q(q(q(t,'×','*'),'−','-'),'÷','/'))
here q = str.replace
and t is the string
you can alias functions like that
ok fixed that, don't think it's very compact now though
apparently does have less characters than your submission however
I'm not an expert on git but I have no clue how to properly send a merge request with all these permissions and stuff
so I'm supposed to send a merge request to the gitlab repo, I created a fork commited my addition and now how do I send the request?
basically once your branch is ready on your fork, you just go to the fork on gitlab and follow the wizard in the merge requests tab
Documentation for GitLab Community Edition, GitLab Enterprise Edition, Omnibus GitLab, and GitLab Runner.
it should be fairly straight forward
make sure you target our repo
And though I strongly strongly encourage you learn how to use Git and GitLab (fantastic tools to learn and use!), if you can't figure it out we can post the code up for you :)
it gives me a 404 page
I know how to use git, not familiar with gitlab however
actually 403
I'm following the guide, I was before
I just keep getting this permissions page
I don't know what I'm doing wrong:
I have my fork, it's ready and everything
afterwards I click on the merge requests and click new merge request
I make sure the targets and stuff are correct
now I don't change anything on the next page, it's all good
but if I then click submit I get this error page
am I like the first to test this on the gitlab here? what am I doing wrong?
That's odd hmm
Ah crap, that's my fault @teal rune sorry
I left a configuration option set to private
oh
I've now changed it so hopefully you should be able to access that MR page now
I thought I was going crazy
my apologies haha
still gives me the same error
hmm, can you try once more?
yup all's cool now, I'll just wait for it to be approved I guess
I believe we are approaching time for a new challenge
Hit me up with any ideas, I'm gonna try to come up with something tonight
A one liner that does fizz buzz.... But is a pallandrom?
generate a random simple sentence, like "I have floppy pants.", no literals allowed.

What in the world are floppy pants
Joseph Banks pushed to branch master of python-discord/esoteric-python-challenges (Compare changes)
i have floppy's pants
LOL
dressed in floppy attire
I remember once purchasing a High Density floppy disk at Staples for like 5$ and being disappointed that it didn't mean it had more space on it
Damn
I was one dumb 11 year old
oh i see
but how do it know it a good word
that's part of the challenge
iunno, workshop it
random.choice(string.alphanumeric)
yes, there are.
can you use literals that are in the internals.
I'm guess you'll have to build your own little dictionary out of class names and stuff for internals, possibly partials, and then make it spit out short sentences based on those words?
Well it doesn't have to be code golf challenges either
yeah, any esoterica is fine
as long as it promotes being creative/clever/hacky
haha, palindrom checker that is a palindrom is probably impossible.
oh man
Not litrally
that'd be a tough one
But like lamada on one side
very unless you comment the last half
Lamada on the other
X on one side
X on the other
Closest to a pallandrom wins
That would be really difficult and really interesting
hard to judge more like
too hard, I think
Oh you know what could be also an interesting challenge concept, to have to do something based on some provided pre-written code, instead of always being doing things from scratch
mmmm
Yeah
kinda like the qualifier but yknow, not easy
take this code and fuck it up
LOL
that's actually fun
I did that for the second qualifier
a bit of esoterica I wrote that returns a couple of literals I used to print the lyrics to bob marleys "jammin"
LOL.
Jesus Christ
!eval
exec(''.join([chr(int(c)) for c in '48$61$93$54$91$41$41$116$110$105$95$99$40$82$69$84$78$73$79$80$44$41$52$40$100$105$40$116$115$97$99$59$42$32$116$114$111$112$109$105$32$115$101$112$121$116$99$32$109$111$114$102'.split('$')][::-1]))
print(f"2 + 2 = {2+2}")
I get giddy every time for some reason
he wrote a True bitshift generator
ooo
it's super cool
takes any string and creates that bitshift sequence bullshit in order to reproduce it.
Of course he did
that's a fantastic tool.
:^)
code that generates ugly code is the best
oh oh
that's a good challenge idea
write a text uglifier
take a string, return super ugly code to generate that string
the more unreadable the better
okay I think I'll base the next challenge on Lemon's random text generator idea
sounds fun
hehe i have a great idea
Turn it into a image
That is a screenshot of ugly code
But turns back to the string
errrrrr
Do you guys know if random.seed is consistent between platforms/systems or if it's purely system specific?
e.g. if I run some code with the same seed on different computers will it produce the same results?
Joseph shut up and answer my question 😠
nice lmao
jk
here is a sneak peek https://i.seph.club/k71g7.png
:))))
#!/usr/bin/env python
string = input(">> ")
code = ""
for c in string:
byte = ord(c)
count = 0
while byte != 0:
if byte % 2 == 1:
code += "True << {} ^ ".format(count)
byte >>= 1
count += 1
code = code[:-3] + ", "
code = "''.join([str(chr(c)) for c in [{}]])".format(code[:-1])
print(code)
input a string, output that True bitshift madness. first code i made after joining this server.
give it a go
omg no one will answer my friggin question eh
windoze
ill test on android then ill go to sleeps
I'd assume seed is platform independent
Same seed should give the same randomness
import random
random.seed("poo")
for x in range(10):
print(str(random.randint(0,100)))
please give me outpoots
because it seeds Python's internal rng algo
But for non seeded randomness that's platform dependend
Yeah I'd assume so too but I wanna be sure cause it might have some implications for my challenge
>>> import random
>>> random.seed("poo")
>>> for x in range(10):
... print(str(random.randint(0,100)))
...
89
5
32
76
4
60
34
67
68
24
Randomness with a fixed seed should include no actual randomness
same
whew
thanks guise
<3 yall the bestest
k yall wanna review the draft of challenge 02 before it goes up
Challenge 02 - Random Text Generator
Task: Create a function that takes in a number, and returns a randomly generated string of semi-valid English.
Goal: Program that creates the most consistently coherent phrases "wins", honourable mentions for absurdly hilarious outputs
Restrictions:
[*] NO STRING/CHARACTER LITERALS NOR USER DEFINED STRINGS
[**] That includes fancy shmancy workarounds like storing a bunch of numbers and converting them to letters
[*] NO FILE/USER INPUT EXCEPT LOADING STANDARD LIBRARY MODULES
[*] NO NON-STANDARD LIBRARY MODULES
[*] NO NETWORKING - AT ALL
> Yep. You read that right. You'll have to look deep *inside* for some words to jumble together.
Submission guidelines:
As always, submit your code as specified in the repository's root README file.
Ideally, submit your code with comments including some example outputs and the random seed/state needed to recreate it.
Remember that this is not a true contest, so don't hesitate to try crazy stuff. Get creative.
Tips:
* Since you can't get lists of words from the user or from outside sources, you'll have to look somewhere else.
* The Python [random](https://docs.python.org/3.7/library/random.html) module has functions that allow you to set seeds and to get/restore states. This can be useful
to generate the same output again should you come across some good results on a particular run.
Special thanks to Lemon for the idea <3
:^)
looks good to me
https://gitlab.com/python-discord/esoteric-python-challenges/merge_requests/1 this probably also needs to be commented on @frosty wyvern
So no import randomwords :(
Well, first it doesn't truly respect the restriction of no lists, but it's still otherwise a pretty impressive solutions
I'll pull it in and just add a comment in the header that states that it doesn't fulfill all criteria
but as I hope I've made pretty clear up to now, I don't care that much about restrictions and rules
👌
they're meant to foster some creative thinking
So I'd rather people submit clever solution that break the rules than not submit at all ^_^
Shawn McLaughlin pushed to branch master of python-discord/esoteric-python-challenges (Compare changes)
Shawn McLaughlin (shawnmcla) merged !1 *My commision for the first challenge* in python-discord/esoteric-python-challenges: My commision for the first challenge
looks good to me
i wish gitlab didn't do those funky embeds
but it was just saying you commited the changes to master and merged a MR
yeah I know but I get two Sign in embeds
yep
yeah, odd gitlab thing
that's just gitlab sucking a bit at webhooks :(
:(

