#esoteric-python
1 messages · Page 70 of 1
this is how satan programs
I kinda get the flow though
().__class__.__base__.__subclasses__()[82].find_module('code').load_module() imports and gets the code module
@sick hound () at the start is just initializing a tuple to get to subclasses?
yep
hm
().__class__ = tuple
There might be a one-char thing?
().__class__.__base__ = object
().__class__.__base__.__subclasses__() = every class
then use that to pull out classes from the import mechanism and get code
isn't type(()) shorter?
Yep
@hot crypt that pfp is nice anyway 
so you get this py TypeError: 'int' object is not subscriptable
thanks 😄
if you could access locals then all of that would be pointless
why not?
is there a random or something behind this
just random
if you can get it to have an exit code of 19 you're probably not just segfaulting it or doing something else weird
¯_(ツ)_/¯
is there like a list of common python code golfing/esoteric problem solving techniques?
TIL the code module can do all this cool stuff
>>> cipher=lambda s:"|".join(map(lambda c: ".".join([str(bin(ord(n)))[2:] for n in str(ord(c))]),s))
>>> cipher('NeKit')
'110111.111000|110001.110000.110001|110111.110101|110001.110000.110101|110001.110001.110110'
Very weird thing I made lmao
https://codegolf.stackexchange.com/q/54/36188 there's this maybe? i found it in the pins of this channel @brazen geyser
decipher=lambda d:"".join(map(lambda p:chr(int("".join(map(lambda x: str(chr(int(x,2))), p.split("."))))),d.split("|")))
and here’s a decipher lol
ty @sick hound
np
why does python even have ;
guessing it's from the super early days trying to make it easier for c/c++ programmers to adapt
@marsh void a bit shorter for your decipher ```python
decipher=lambda d:"".join(chr(int("".join(chr(int(x,2))for x in p.split("."))))for p in d.split("|"))
sec
That was actually way shorter imo lol
cipher=lambda s:"|".join(".".join(bin(ord(n))[2:]for n in str(ord(c)))for c in s)
@marsh void
thanks
cipher=lambda s:"|".join("".join(bin(ord(n))[2:]for n in str(ord(c)))for c in s)
decipher=lambda d:"".join(chr(int("".join(chr(int(x,2))for x in [p[i:i+6]for i in range(0,len(p),6)])))for p in d.split("|"))
Is there a way to make [p[i:i+6]for i in range(0,len(p),6)] shorter?
Kinda making it so there’s no dot
Oops a typo
Fixed
__import__('textwrap').wrap(p,6)
@brazen geyser lmao this thing actually exists
yep
>>> cipher=lambda s:"|".join("".join(hex(ord(n)+13)[2:]for n in str(ord(c)))for c in s)
>>> decipher=lambda d:"".join(chr(int("".join(chr(int(x,16)-13)for x in __import__('textwrap').wrap(p,2))))for p in d.split("|"))
>>> cipher('NeKit')
'4445|3e3d3e|4442|3e3d42|3e3e43'
>>> decipher(cipher('NeKit'))
'NeKit'
So here’s a thing I have now
Some security improvements? Maybe b64 on hexed values?
from textwrap import*;decipher=lambda d:"".join(chr(int("".join(chr(int(x,2))for x in wrap(p,6))))for p in d.split("|"))
``` @ your previous code
Yep oki
didnt know about wrap though, that's neat meta
while id:r=input();id=1if r else 0;s=iter(r.split(" "));t=next(s,"");e=1if t==""else 0;exec("try:t=float(t)\nexcept:t=0");e=1if hasattr(t,"__or__")else e or 0;u=next(s,"").lower();e=1if u==""else e or 0;z={"f":lambda x:(x-32)*5/9,"c":lambda x:x*9/5+32};c=z.get(u,lambda x:0)(t);e=1if c is 0else e or 0;y="C"if u=="f"else"F";print(f"{c}{y}")if id and not e else 0;print("E")if all((id,e))else 0```
from textwrap import*;cipher=lambda s:"|".join("".join(hex(ord(n)+13)[2:][::-1]for n in str(ord(c)))for c in s);decipher=lambda d:"".join(chr(int("".join(chr(int(x[::-1],16)-13)for x in wrap(p,2))))for p in d.split("|"))
ok so this is the final version
you can condense your cipher function a bit @marsh void
cipher=lambda s:"|".join("".join(f'{ord(n)+13:x}'[::-1]for n in str(ord(c)))for c in s)
Oh yep formations. Cool! @sick hound
😎
Has anyone used this trick?
for i in[0]*input():print bin(input())[2:]
V
exec input()*"print bin(input())[2:];"
(that's for python 2, but works with other things in python3)
might even shave off another byte (space) by swapping the input() and exec string
oh yeah
Hm
I wonder how my code is somehow leaking 1.7GB just by instantiating a few classes
well i've got 42 in python haha
yeah like a normal person
my quotes are consistent with the guidelines described for docstrings in PEP257
:)
A double quote takes twice as much effort to type as a single one because you have to press Shift to enter it.
a capital letter takes twice as much effort to type than a lowercase one yet you still use capitals in your sentences
you don't know that :D
More than twice, actually. The pinky is a bit weaker than the other fingers, I think. Unless press (L|R)Shift with a different finger, which is awkward.
I think I'm overthinking it.
that's esoteric fingers, not esoteric python. haha
Is there a high-level wrapper around brainfuck?
Like a languages that get translated into bf.
there are transpilers for almost all languages into brainfuck
how limited the section of code they allow is a different story though
what was the task? :D
also that's not maximum compression, you could easily get rid of some whitespace like if i==0:
I miss clicked and summited way to early
this was the challenge
this was my cheating code lmao
we should have a clash of code channel
you guys got me addicted
Yes, it's very addictive.
How does the score system work in CoC?
I mean, in the leaderboard.
Maybe that was a bash noob :)
not even obfuscated, it's the simplest most straightforward way to do it, unless i'm misunderstanding the problem
Does anyone want to play clashofcode in a private game?
Do you know how the scores for the leaderboard are calculated?
idk, never really looked at it.
It doesn't even say what the columns mean :\
is this real?
Probably yes.
what?!
yhe, only played that on here.
https://www.codingame.com/ide/puzzle/code-of-the-rings might be interesting.
Brainfuck generation.
I had no idea you could connect Lord of the Rings and brainfuck.
@polar plover We're doing python only, right?
yes
@polar plover both 2&3?
Are you using round or //?
158
I went for datetime when I say the challenge xD, might not been the best idea.
but I gota go now
Also, if you use only one thing from a module, it's more costly to from it than to just import the whole module
Should have used * at least....
Can't, Just wanted to answer you real quick
ok
@formal sandal I am back if you still want to play?
Sure.
damn it
?
I started my own as well :))
oof
what does your code look like?
like this
👍
I have shared it
saw that
maybe another one?
Holy crap, I'm first in Russia now 🍷
👍 I am first in Norway and something 400 in the world
reverse is not that fun, it's just fast with extra things that is not really coding
???
@formal sandal nice spaghetti though
Maybe we could do an esolang contest.
I mean, making our own esolangs and interpreters/compilers for them.
I'm not sure how the winner will be determined, though.
Why just make esoteric language when you can also make an esoteric style guide?
"all variable names must contain exactly one character"
"also, always use meaningful identifiers"
I think golfers have the first one down pat.
On a scale from 0 to 10, how garbage does this look?
{xSfSoldSoldLlenS|JnewS0iS{old i!jSj x fO{j new:Z}{}?i1+iS}lenRnewV}filterS{oldSoldLlenS|JnewSlen2<.{|Jold;newS}{old0!xSoldV[<.]xVfilter#qsort#oldV[=]xVfilter#oldV[>.]xVfilter#qsort#;;newS}?newV}qsortS
oh
the scale is garbage too :)
10 is pure garbage
0 is pep8-compliant well-written code
I can see a lot of filter and qsort
dont know if this counts as esoteric but..
num_on = [6,2,5,5,4,5,6,3,7,6]
n = 3
q = ["12:58", "01:15", "6:35"]
for i in range(n):
cur=0;new=0;t=q[i]
for c in t.replace(":", ""): cur+=num_on[int(c)]
times=list(map(int, t.split(":")))
times[-1] += 1
if times[-1] > 59: times[-1] = 0;times[0] += 1
if times[0] > 23: times[0] = 0
time = times
if time[0] < 10: time[0] = "0" + str(time[0])
else: time[0] = str(time[0])
if time[1] < 10: time[1] = "0" + str(time[1])
else: time[1] = str(time[1])
time = "".join(time)
for c in time:
new += num_on[int(c)]
print(new - cur)```
lovly code to figure out how many parts of a lcd clock have to change if you go 1 min into the future..
xD
- You can use 's' only one time per program, and you can't store a variable which has 's' as an element
- You can use eval and exec, but only as functions (not
"eval") - You can't use any other letters or digits.
- You can use any other symbols.
- print
Hello, world!
I think I am soo close to do it without s, but then. it does not work.
I see letters....
I solved this already 😔
@hot crypt You can't use letters.
nor digits... only 1 's' and eval/exec?
and symbols like <>()[]...+-% ect
I can get arbitrary numbers, I just can't convert them into strings.
@snow beacon You can use 's' once.
!e ```python
print('%s' % 31415)
@formal sandal Your eval job has completed.
31415
You can get repr, but other stuff is harder...
!e ```python
_ = []==[]
__ = +++++++++++
___ = (('%s'*())%(' ',[]==[],...,' ',[]==[],...,' ',[]==[],...,' ',[]==[],...,))[::+]
print(___) # printing just for demonstration
@formal sandal Your eval job has completed.
repr
Then you can even access the letter 's'.
!e ```py
___ = 'repr'
_ = 1
print(eval(__)([]<[])[~])
#repr(False)[~True] == 'False'[-2]```
@formal sandal Your eval job has completed.
s
The Holy Grail...
@polar plover s
Now it's easy.
!e python _ = []==[] __ = _+_+_+_+_+_+_+_+_+_+_+_ ___ = (('%s'*(__))%(' ',[]==[],...,' ',[]==[],...,' ',[]==[],...,' ',[]==[],...,))[__::__+__] ____ = eval(___) _____ = [ ___[_+_], #p ___[_-_], #r ____(...)[_+_+_], #i ____(exec(''))[_+_], #n ____(eval)[_+_+_+_+_] #t ] ______ = eval(_____[_-_]+_____[_]+_____[_+_]+_____[_+_+_]+_____[_+_+_+_]) ______(______)
@formal sandal Your eval job has completed.
<built-in function print>
You can get s a bit more simply: ("%(_)s"%{"_":...})[-(""=="")]
Well, you can't store it in a variable according to rule 1, so that's not very useful.
So you could just use 's'.
You can multiply it and concatenate it.
you can't store a variable which has 's' as an element
You don't need to store it.
How would you use it then?
If you have already used 's', you can't use '%s' again.
If you have s already, you can just use that. You don't need to get s from s
Exactly.
im not good enough for these challenges yet 😢
[..., ""=="", ""<"", exec(''), exec, eval, {...}-{...}] is all the values that are easy to get, for the purpose of stealing letters from their names.
[Ellipsis, True, False, None, <built-in function exec>, <built-in function eval>, set()]
I have thought of another trick some time ago.
EFNTabcefilnoprstuvx
We have an x, and an f, so it should be pretty simple from there
I hope it's okay if I use numbers as shortcuts.
\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64\x21```
Now if I could only form these without python complaining about unterminated bytes...
So the goal seems to be \x105\x109\x112\x111\x114\x116\x32\x95\x95\x104\x101\x108\x108\x111\x95\x95 or similar.
Oh, wait, that's not in hex
\x69\x6d\x70\x6f\x72\x74\x20\x5f\x5f\x68\x65\x6c\x6c\x6f\x5f\x5f
can I spoil it
I kind of already know the steps, I just can't be bothered typing out a bunch of underscores to actually assemble the result.
you can't use \x because it has a letter
)
but you can use octal
You can get x from the representation of exec
how
what
oh right
seems overcomplicated
>>> eval('"\\%s"' * 13 % (110, 145, 154, 154, 157, 54, 40, 167, 157, 162, 154, 144, 41))
'Hello, world!'```
If you eval the string "repr" you get repr
Is there a way to get d?
dict?
You would need type for that...
It's not in any of the easy literals. You'd probably need to do ascii stuff
ya im awful at python
You could use chr, but we don't have h.
Well, I have to resort to \x now...
Behold my new trick:
!e python _ = []==[] __ = _+_+_+_+_+_+_+_+_+_+_+_ ___ = (('%s'*(__))%(' ',[]==[],...,' ',[]==[],...,' ',[]==[],...,' ',[]==[],...,))[__::__+__] ____ = eval(___) _____ = [ ___[_+_], #p ___[_-_], #r ____(...)[_+_+_], #i ____(exec(''))[_+_], #n ____(eval)[_+_+_+_+_], #t ___[_], #e ____(exec)[~_+~_], #x ] ______ = eval(_____[_-_]+_____[_]+_____[_+_]+_____[_+_+_]+_____[_+_+_+_]) __ = ____(______) _______ = "__"+__[_:_+_+_+_+_+_]+__[_+_+_+_+_+_+_:_+_+_+_+_+_+_+_+_]+____([]<[])[~_]+"__" _____ += [eval("'\\"+_____[~_+_]+____(_+_+_+_+_+_)+____(_+_+_+_)+"'")] ______(eval(_____[~_+_]+_____[_+_]+_____[_])(_______))
@formal sandal Your eval job has completed.
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
BAM
what have I just stumbled into
- You can use 's' only one time per program, and you can't store a variable which has 's' as an element
- You can use eval and exec, but only as functions (not
"eval") - You can't use any other letters or digits.
- You can use any other symbols.
- print
Hello, world!(doesn't have to be exactly like that I guess)
I'm so confused how you were even able to get a string there
the %s % True, Ellipses, etc
[this all evolved in staff lounge before lemon kicked them out]
is there anyway to create strings not using any letters?
"<", from a number: I have tried for a long time, and no.
ah rip
it might be, but if soo. I have no clue were to even look. I have tried to find a way for a long time now.
I guess the first thing to do would be to work out all of the things that can be accesed using only symbols (eg: ... for Ellipsis, []==[] for True etc.)
also, out of curiousity, is there a way to get None only using symbols?
My builtins trick won't work, though, because it seems that builtins here are different from my builtins.
Oh, I'm stupid.
I took builtins of a str instead of the entire file, but you get the point.
I think I am too deep into the rabbit hole.
I have spent too much time doing this.
This is more addictive than Clash of Code.
I just realised how easy this would be in Python 2, since you can just use backticks to get strings
I challenge you guys to get the number 100000 into a variable using the least characters possible, whilst only using symbols
_=[]==[]
_=_<<_
_=_<<_|_
_=_*_*_*_*_
this is the best I was able to come up with
_=_+_
it's a cool challenge
I think there might be a way to get inf and NaN using only symbols somehpow
also, I can do _+=_ instead of _=_+_ @jade dust
turns out you can get inf by spamming multiplication on a float
>>> _*_
65536.0
>>> _*=_
>>> _*=_
>>> _*=_
>>> _*=_
>>> _*=_
>>> _*=_
>>> _*=_
>>> _
inf
Turns out you can get NaN by doing infinity divided by infinity
Well, in python 2 it's easy to get s: ````[]<[]`[~([]==[])]```
_="%s"
__=~~(()==())
___=__<<__
____=___<<__
_____=___<<___
______=____<<___
_______=___<<____
________=____<<____
_________=eval((_%(()==()))[__::___]+(_%...)[____]+(_%(()==()))[__])
__________=eval((_%...)[____]+(_%(()==()))[__]+_________(_________)[_____-__:_____+__]+_________(_________)[____+__])
___________=_________(eval((_+".__"+_+"__")%((_________(_________)[-____-__:-__],)*___)))
_=eval(___________[_______+_____+__]+___________[____]+(_%(()==()))[__])
__________(
_(+_____+_______+________)
+ _(+__+____+_______+________)
+ _(+____+_____+_______+________)*___
+ _(+__+___+____+_____+_______+________)
+ _(+____+_____+_______)
+ _(+_______)
+ _(+__+___+____+______+_______+________)
+ _(+__+___+____+_____+_______+________)
+ _(+___+______+_______+________)
+ _(+____+_____+_______+________)
+ _(+____+_______+________)
+ _(+__+_______)
)
@formal sandal
@brisk zenith Good, but you broke the rule number 1: ...you can't store a variable which has 's' as an element
oh well :D
Also, why ~~(()==()) when you can use []==[]?
Right, but you can use True as an integer.
...hmm
- is less characters
True.
Pun intended?
False.
@sick hound haha your code makes idle error:
so does any code in the situation you've set up
do it in an actual python REPL or something, not idle
@sick hound
yeah I realised
was sitting there going what the heck I can't do anything
I have proved python list comps to be turing complete by implementing a 110 cellular automata with them
[print(x) for n in [int(input())] for l, x in [(''.join(' X'[e == n - 1] for e in range(n)), 1)] for r in range(n) for l, x in [(''.join('X '[l[c - 1:c + 2] in ('XXX',' ','X ','',' ')] for c in range(n)), l)]]```
if you paste this in it'll prompt you for a number and print that many iterations of it starting from `001`
I guess one could say "You could have just done [exec(...) for _ in [1]] but screw off
why would you do that
yeah I guess
(lambda f:f(f))(lambda f,p=2,c=2**0.5,i=0:print(p)if i>100 else f(f,p*2/c,(2+c)**0.5,i+1))
thats my most shitty code that i have ever done
to calculate pi
using that formula
say_hello = (function (str)
| call(print) ("hello", ...)
)
get_name = (function (None) >> str
| call(input) ("tell me your name: ")
| tee(say_hello) (...)
)
name = get_name()
print("-----")
print("returned name:", name)
### example output:
# tell me your name: juanita
# hello juanita
# -----
# returned name: juanita
new python syntax 😎
Can anyone explain why in python2 the result of this toggles between True and False on console? It boggles my mind
(lambda a: a) < (lambda b: b)```
centos 6 python 2.7.5 does that
py3 is giving me TypeError: '<' not supported between instances of 'function' and 'function', but I can confirm the behaviour you described for py2.7 using <
that may actually be a bug or at least undesired behaviour which has since been fixed
Yeah, py3 introduced some more sense into comparisons between types
valid_python_version = (
match (amount=3)
[3, 7, :] (True)
[:, :, :] (False)
)
print(valid_python_version(3, 7, 4)) # True
print(valid_python_version(3, 7, 0)) # True
print(valid_python_version(3, 6, 9)) # False
print(valid_python_version(2, 7, 16)) # False
@cunning wave @vague gust do you approve?
its not perfect pattern matching yet
but a start
also if it gets to function features ping rags
@brisk zenith
how should i expand on it? i was gonna allow for a <= value <= b testing by doing stuff like [a:b] as patterns, for example
I hate it and love it
i just love it
mainly because all the ideas i had for it before looked really ugly, and that right there doesn't look half bad
if you can get it to the point where it can imitate
match x {
Ok(val) => things
Err(e) => things
}
ill be proud of you @brisk zenith
maybe
actually, that's not possible i don't think
no it's not
actually.. i could try something similar, perhaps.
@sick hound why does it toggle though? If it was based on address wouldn't it either be always equal, or always lambda a < lambda b?
well it's creating a new function every time you do that
if you eat an apple and then you eat an apple, did you eat the same apple twice?
yeah but it goes back and forth between True and False predictably
probably just some quirks of memory allocation then
If that's random that could be quite useful for codegolfs, instead of doing
from random import*
random.randint(0,1)
(assuming you want to use py 2 for a code golf)
https://tio.run/##K6gsycjPM/r/v6AoM69EQyMnMTcpJVEh0UohUVPBTgHGT7JSSNLU5Breiv7/BwA why does it seem to alternate between True and False?
Exactly 😅
Oh running it twice inside the same statement seems to work aswell
As in, it continues the sequence
i'm guessing it's something to do with memory
>>> dis.dis("(lambda a:a) > (lambda b:b)")
0 STORE_SLICE+0
1 IMPORT_NAME 28001 (28001)
4 DELETE_GLOBAL 24932 (24932)
7 SLICE+2
8 STORE_GLOBAL 24890 (24890)
11 STORE_SLICE+1
12 SLICE+2
13 BINARY_LSHIFT
14 SLICE+2
15 STORE_SLICE+0
16 IMPORT_NAME 28001 (28001)
19 DELETE_GLOBAL 24932 (24932)
22 SLICE+2
23 DELETE_GLOBAL 25146 (25146)
26 STORE_SLICE+1
they bytecode looks disturbing
their hashes are equal
wrapping them in id() results in them becoming the same object
>>> dis.dis("id(lambda a: a) > id(lambda b:b)")
0 BUILD_MAP 10340
3 IMPORT_NAME 28001 (28001)
6 DELETE_GLOBAL 24932 (24932)
9 SLICE+2
10 STORE_GLOBAL 8250 (8250)
13 STORE_GLOBAL 8233 (8233)
16 BINARY_LSHIFT
17 SLICE+2
18 BUILD_MAP 10340
21 IMPORT_NAME 28001 (28001)
24 DELETE_GLOBAL 24932 (24932)
27 SLICE+2
28 DELETE_GLOBAL 25146 (25146)
31 STORE_SLICE+1
!e ```python
print(id(lambda a: a) == id(lambda b: b))
@formal sandal Your eval job has completed.
True
python 2 weirdness
what even is STORE_SLICE+0 o.O
STORE_SLICE+0()¶
Implements TOS[:] = TOS1.
interesting
Yep
Sorry, but you may only use this command within #bot-commands.
for _ in range(20):
a = lambda a: a
b = lambda b: b
print(id(a) < id(b))``` (python3) this outputs ```py
False
True
True
False
True
True
False
True
True
False
True
True
False
True
True
False
True
True
False
True```
which is basically the same as the thing in python 2
but the output here is different 🤔 False True True
I'm getting the outputs negated with that code
swap the a = and b = around then
for _ in range(20):
b = lambda b: b
a = lambda a: a
print(id(a) < id(b))``` this outputs `True False False True False False ...`
I smell an allocation
same
so who is gonna bring out the debugger to find out whats happening now
my guess is that the allocator for function objects uses a freelist
and the object for a is returned to the freelist first, then used for b in the next loop
hmm no that doesn't explain cycling between three values
also i mixed up a and b because of your swap
>>> for _ in range(50):
... b = lambda b: b
... a = lambda a: a
... print(id(a), id(b))
...
35176928 44135696
44135696 44021824
44021824 35176928
(repeats)
>>> for _ in range(50):
... a = lambda a: a
... b = lambda b: b
... print(id(a), id(b))
...
35176928 44135696
44021824 35176928
44135696 44021824
(repeats)```
hmm these are globals
so the prior a isn't free until a is reassigned, and vice versa
yep... hmm...
>>> for _ in range(50):
... a = lambda a: a
... b = lambda b: b
... print(id(a), id(b))
... del a, b
...
44135696 44021824
44021824 44135696
(repeats)```
oh so that means
>>> for _ in range(50):
... a = lambda a: a
... b = lambda b: b
... print(id(a), id(b))
... del b, a
...
44135696 44021824
(repeats)```
and for completeness and more or less as expected,
>>> for _ in range(50):
... a, b = lambda a: a, lambda b: b
... print(id(a), id(b))
...
44135696 44021824
35176928 44162856
44021824 44135696
44162856 35176928
(repeats)```
four addresses in play because old-a and old-b are both not deleted until after new-a and new-b are allocated
(the other possibility is that it cycles between two lines both with unique addresses, and I'm honestly not sure why it doesn't do that)
anyway i can't go further than this
"simple" character to binary converterpy to_bin = lambda char: int(bin(ord(char))[2:])
better than string, am i right?
In which way?
An int is stored in binary anyway.
And you can't force it to be 8 or 16 or n character long.
why store a number as a str if you could use int
If you want to store a number, you can just store ord(char).
Instead, you're storing its binary representation. That would be useful if: a) you want to print it, b) you want to access the individual bits. For both of these pursposes, str is easier to use.
@cunning wave @brisk zenith
that doesnt exactly resemble the idea of pattern matching
var has to be present as var on the right side as well
Wondering if it is possible to make increment and decrement in Py3.8
I mean, translate i=0; print(i++) to something that is actually working
In that case you'd probably want ++i though 😉
Yeah
I don't see it happening
print(i:=i+1)?
Oh well I thought using that exact syntax
Some regular expressions and we cool
To get the attr name
I mean, if we doing it in normal python
Also, anyone with 3.8: python ok with assignment expression in the code? Like i := 0 would raise an error?
(a, a:=a+1)[0] for postfix
a := a+1 for prefix
i just learned you can unpack a 0-tuple:
>>> [*()]
[]
good job
this is great news
sure
it makes calling functions from dicts a lot easier
a = [*(1,2), *(3,4)]
a
[1, 2, 3, 4]
yes, but those aren't 0-tuples
But it’s cool
yeah, but it's already expected behavior, but this is the weird edge case
Decided to go and run test to define whether list(iterable) is slower than [*iterable] and measure the time and stuff
[*iterable] is apparently way faster
by about 0.0000001066 seconds for iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], if I got the calculation right there
Is it the same with sets?
from enum import Enum
class Color(Enum):
class HEX:
def __init__(self, hex_code: str):
self.code = hex_code
class RGB:
def __init__(self, R: int, G: int, B: int):
self.r = R
self.g = G
self.b = B
def __call__(self, *args):
return self.value(*args)
>>> Color.HEX('#00ff00')
<__main__.Color.HEX object at 0x108740f28>
Rust like enums. 
runBF = lambda f:(
lambda f,a=[],p=[],c=[]:(
lambda b,q={}:[
q.update({
'>':lambda:[p.append(p.pop()+1),a.append(0) if p[0]==len(a) else None],
'<':lambda:p.__setitem__(0,p[0]-1 if p[0]>0 else 0),
'+':lambda:a.__setitem__(p[0],a[p[0]]+1 if a[p[0]] < 255 else 0),
'-':lambda:a.__setitem__(p[0],a[p[0]]-1 if a[p[0]] > 0 else 255),
'.':lambda:print(chr(a[p[0]]),end=''),
',':lambda:a.__setitem__(p[0],ord(input()[0])),
'[':lambda:None if a[p[0]] else c.append(b[c.pop()]),
']':lambda:c.append(b[c.pop()]) if a[p[0]] else None
}),
[*map(lambda x:[x.clear(),x.append(0)],(a,p,c))],
[*iter(
lambda:[
q[f[c[0]]](),
c.append(c.pop()+1),
c[0]<len(f)
][2],
0
)]
][0]
)(
(
lambda s=[],b={}:[
s.clear(),
b.clear(),
[
[
s.append(p)if c=='['else 0,
b.update({
s[-1]:p,
p:s.pop()
})if c==']'else 0
]for p,c in enumerate(f)
],
b
][3]
)()
)
)(''.join(filter(lambda x:x in '><+-.,[]',f)))``` if anyone wants to try to figure out why this isnt working properly, go for it (its a bf interpreter)
Looks like flex
@marsh void any ideas why it wouldn't work?
@rugged sparrow what string does it fail on and what does it do instead of working
http://www.hevanet.com/cristofd/brainfuck/xmastree.b this one does weird things
and ik it works normally cause i tested it on another interpreter
it loops taking and printing input for me
it looks like it's expecting you to input a null byte (character 0) at some point
hmm ok
but your program doesn't have any way of doing that
and the way you're doing input in general is kind of weird
',':lambda:a.__setitem__(p[0],ord(input()[0])),```
this will only let you input one character every line
something like __import__('sys').stdin.read(1) would work better
i thought ',' was only supposed to input one char
yes, it does only input one character
but the way you're doing it reads one line and then only takes the first character
oh
ah
(in case it's unclear, the input was test, what)
i'm trying to get the highest number I can only using 10 characters
the best I could get is 9**9**9**9, which has around 3.7 billion digits
tsk inf is one char off
oh wow
welp wanted to try 9**9999999 and my pycharm's borked
I used wolfram alpha to check it
now I gotta update skeletons >.<
9**9999999 has 9.5 mill digits
oh wow
(it's infinity)
>>> 9E307
9e+307
>>> 9E308
inf
9E307 is the highest you can go without being inf
best thing is, not going to bork your pycharm 😄
what about 1e308
in 10 characters the highest you can actually go without it being inf is 1.79769e308
as far as I can tell
well, in floats
@gilded orchid
oh wow, how did you figure out that decimal?
!e ```py
import sys
print(sys.float_info.max)
@brisk zenith Your eval job has completed.
1.7976931348623157e+308
that's the highest possible float in python.
I did it with trial and error
>>> 1e308
1e+308
>>> 2e308
inf
>>> 1.5e308
1.5e+308
>>> 1.7e308
1.7e+308
>>> 1.8e308
inf
>>> 1.75e308
1.75e+308
>>> 1.85e308
inf
>>> 1.78e308
1.78e+308
>>> 1.79e308
1.79e+308
>>> 1.799e308
inf
>>> 1.795e308
1.795e+308
>>> 1.797e308
1.797e+308
>>> 1.79e308
1.79e+308
>>> 1.798e308
inf
>>> 1.7975e308
1.7975e+308
>>> 1.7977e308
inf
>>> 1.7976e308
1.7976e+308
>>> 1.79765e308
1.79765e+308
>>> 1.79768e308
1.79768e+308
>>> 1.79769e308
1.79769e+308
>>> 1.79769e308
1.79769e+308```
runBF = lambda f:(
lambda f,a=[],p=[],c=[]:(
lambda b,q={},i=[]:[
q.update({
'>':lambda:[p.append(p.pop()+1),a.append(0) if p[0]==len(a) else None],
'<':lambda:p.__setitem__(0,p[0]-1 if p[0]>0 else 0),
'+':lambda:a.__setitem__(p[0],a[p[0]]+1 if a[p[0]] < 255 else 0),
'-':lambda:a.__setitem__(p[0],a[p[0]]-1 if a[p[0]] > 0 else 256),
'.':lambda:print(chr(a[p[0]]),end=''),
',':lambda:a.__setitem__(p[0],[
0 if i else i.extend(input()),
ord(i.pop(0)) if i else 0
][1]),
'[':lambda:None if a[p[0]] else c.append(b[c.pop()]),
']':lambda:c.append(b[c.pop()]) if a[p[0]] else None
}),
[*map(lambda x:[x.clear(),x.append(0)],(a,p,c))],
[*iter(
lambda:[
q[f[c[0]]](),
c.append(c.pop()+1),
c[0]<len(f)
][2],
0
)]
][0]
)(
(
lambda s=[],b={}:[
s.clear(),
b.clear(),
[
[
s.append(p)if c == '[' else 0,
b.update({
s[-1]:p,
p:s.pop()
})if c == ']' else 0
]for p,c in enumerate(f)
],
b
][3]
)()
)
)(''.join(filter(lambda x:x in '><+-.,[]',f)))``` @sick hound fixed the input issue without importing something. but i cant figure out why the tree program doesnt work
Is it possible to get the instance bound to a method if all you have is the method object?
@whole kiln so you have for example x.__dir__ but not x? Just use x.__dir__.__self__
Let's say I have a class Foo with method bar. Now I'm in a function and as a parameter I was given foo_instance.bar. So, inside this other function, all I have is the bar method, not the foo_instance.
Alright
That works
__dir__.__self__ was just returning the same method
not sure what you meant by that
i meant that the __dir__ was the bar method from your example. i just wasnt super clear about it
ah
also i misread what you asked originally and wrote this py getInstances = lambda cls:[*filter(lambda x:x.__class__ == cls,__import__('gc').get_referrers(cls))] which can get every instance of any non builtin class
Python 3.7.3 (default, Mar 27 2019, 22:11:17)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> getInstances = lambda cls:[*filter(lambda x:x.__class__ == cls,__import__('gc').get_referrers(cls))]
>>> class Foo:
... pass
...
>>> a = Foo()
>>> b = Foo()
>>> a
<__main__.Foo object at 0x799524d55da0>
>>> b
<__main__.Foo object at 0x799524d55d68>
>>> getInstances(Foo)
[<__main__.Foo object at 0x799524d55da0>, <__main__.Foo object at 0x799524d55d68>]
>>> ```
Neat, I could see that being useful somehow
I had a much simpler question 😄
true lmao
now i wonder if i can get that function to work for base types
huh
getInstances(dict) returns the __builtins__ dict
2 different versions of it
and a dict of all exception types
Python 3.7.3 (default, Mar 27 2019, 22:11:17)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> getInstances = lambda cls:[*filter(lambda x:x.__class__ == cls,__import__('gc').get_referrers(cls))]
>>> class Foo:pass
...
>>> a = Foo()
>>> getInstances(Foo)
[<__main__.Foo object at 0x7db337b50da0>]
>>> del a
>>> getInstances(Foo)
[<__main__.Foo object at 0x7db337b50da0>]
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>>
``` more weird shit
its the garbage collector in python
or at least an interface for it
also objects it grabs that aren't referred to by anything disappear after a bit
which makes sense
@rugged sparrow note: https://stackoverflow.com/a/47030886/10444096
i think a better option here might be a class decorator or metaclass
if you only need to keep track of the instances of certain classes
this looks good
@rugged sparrow when you did del a, a still existed as part of a list returned by getInstances which the interpreter implicitly stored in _
is there any way to overwrite errors, so you can make your own code run when an error gets called?
(not using try except, actually overwriting the error class itself)
From memory there are some libraries and ctypes tricks let you monkey patch builtin types
so you can do things like this ```py
2 + 2
4
_ + 1
5```
works in 2.7
Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 2 + 2
4
>>> _
4```
Ok
i don't have any versions before that installed
well if you have something that returns an object
and you run it
and it prints a normal unhelpful object repr and you want to look more at the object
you can just use _
and you get the object
Why doesn't python have a built in range function that allows for floats? Is there a reason?
How would you implement that? Many numbers don't exist as floats. Rounding errors would become a problem. At least that's my guess.
It's just weird for me since all the other languages I've tried allow for for(i = 3.03; i < 200; i += 2.402)
you can use a list comprehension or generator expression
[x * 0.5 for x in range(5)]
you could also define your own generator to do it
def frange(start, end, step=1):
while start < end:
yield start
start += step
as for why there isnt one built in, i dont know
heh, what’s frange?
sounds interesting
if you want more precision there's arange and linspace in numpy
How is there more precision? Pardon me, I'm new to Python and programming in general. Isn't there only floats in python?
...
(hold on, code incoming)
>>> import numpy as np
>>> np.arange(0, 1, .1)
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
>>> def frange(start, end, step=1):
while start < end:
yield start
start += step
>>> list(frange(0, 1, .1))
[0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6, 0.7, 0.7999999999999999, 0.8999999999999999, 0.9999999999999999]
>>>
Sorry, but you may only use this command within #bot-commands.
also
>>> [x * 0.1 for x in range(0, 10)]
[0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001, 0.7000000000000001, 0.8, 0.9]
though this works a lot better for some reason
>>> [x/10 for x in range(0, 10)]
[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
>>>
@brazen geyser we have talked about this here, it is the way python treats floats
>>> import decimal
>>> decimal.Decimal(0.1)
try this code
i dont see how this explains why division is more precise than multiplication
also if you want a precise value you should pass a string into Decimal, not a float
@brazen geyser yeah I know about precise values, but yup, division and multiplication is weird
can you stop pinging me please?
ok sorry
decimal.Decimal(0.1) is the exact same value as 0.1
You have to construct using a string, decimal.Decimal('0.1') in order to get the correct handling
When you multiply by 0.1 it has to approximate twice: once for the literal, again for the result of the multiplication. If you divide by an integer, it only approximates once.
>>> decimal.Decimal(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')```
that is exactly 3602879701896397*2**-55
🤔
I don't really understand why languages like Python prefer to implement floats rather than rational numbers. Ignoring that they take a bit more space, the single problem of factorising the numerator and denominator to get their simplest form, they just seem a lot more useful. No rounding errors for values like 0.1.
i guess a lot of languages use floats instead of rational numbers
How would rational number be better?
Yup, I've had some of those weird things happening once. I know it's because they use weird things with math like you said above that is exactly 3602879701896397*2**-55.
With floats, only values with denominators powers of two can be exactly represented. Rationals can represent any denominator
But why use floats then? Is it memory usage?
Do you guys know any like official or unofficial module that has rational numbers? If I need to use rational numbers.
fractions module
I don't like it though because I tried to use modulo and it didn't work properly.
Might have just been my code though because it does what I expect as I'm testing it now.
Nevermind, fractions is just great and I never realised.
floats are how your hardware represents decimal numbers. that means they can be VERY fast. other representations require a lot of extra work to operate on and most math operations on a computer dont need the accuracy.
anyone here have any small esoteric challenges they want to throw my way?
@brazen geyser arange isn't actually better precision, it just prints differently.
>>> list(numpy.arange(0, 1, .1))
[0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001, 0.7000000000000001, 0.8, 0.9]```
you can get better precision by dividing an integer range
>>> list(numpy.arange(0, 10, 1) / 10)
[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]```
(those still aren't exact of course, but printing that way means they're the closest possible for a float)
i'm disappointed that linspace doesn't do a better way (i checked, it doesn't)
this sounds like kind of a big oversight for a library like numpy, no?
then again i guess speed is more important here than a bit of imprecision
the weird thing is, they do have some differences
oh I think it's just edge cases
arange can end up off by one due to cumulative error e.g. ```py
np.arange(0, 1, 1/49)[49]
0.9999999999999999```
otherwise the results are generally identical for equivalent calculations [arange(0, 1, 1/i) vs linspace(0, 1, i, False)]
i suspect linspace(a, b, x, False) is basically just something like a+arange(x)*((b-a)/x)
whereas the more accurate version would be a+(arange(x)*(b-a))/x
but division is expensive
and they're hardly ever off by more than one floating point unit
the above does make linspace a superior method to arange, even if the values are generally numerically the same
Why does // return a float? Woudlnt it make sense to just return an int? If you're using // in most cases you want an int right
it doesn't unless you use it with a float
also this is for esoteric python, not actual questions that make sense
:P
haha
What's the most esoteric way to round a float to x digits
e.g. ```py
round_func(0.999999, 4)
0.9999
round_func(3.141528, 2)
3.14
The easiest would be lambda x,p:(x*10**p)//1/(10**p)
But I wonder what other ways it could be done
lambda x,p:float(f"{x:.{p}f}") is a close one but seems to round 0.9999 to 1.0
lambda x,p:float((lambda s:s[:s.find('.')+p+1])(str(x))) this is the shortest I can do with substringing
lambda x,p:float(str(x)[:log(x,10)//1+1+p])
>>> f(0.999999, 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
TypeError: slice indices must be integers or None or have an __index__ method```
@distant wave
ugh
That's annoying
Yeah, I don't even know why since it's literally rounding to a whole number
This one's functional
!e ```python
from math import log
a = lambda x,p:float(str(x)[:int(log(x,10)+2+p)])
print(a(3.1415926, 4))
@distant wave Your eval job has completed.
3.1415
Nice
ooo, found something interesting
wait a min this one is posted
is this the opposite of code golf
Not really
We're trying to come up with the most unreadable and idiotic way to do something
>>> a = lambda x,p:x-x%(1/10**p)
>>> a(3.1415, 3)
3.141
Which is kinda similar to code golf since we're trying to do it as small as possible
Actually
Shouldn't that one be 3.142
Think
Due to rounding
Same here
If I want to round, I just need to double that % end, then remove it. Makes it kind a long though
bast cant you make it shorter with lambda x,p:x-x%10**-p
interesting solution though
lambda x,p:(x+2*(x%10**-p))%10**-p)
that's a rounder
I want to do something with mantissa manipulation, but I'm not willing to dive into the bits
lambda x,p:(lambda m:(lambda v:(v//1+(v%1>=0.5))/m)(x*m))(10**p)
Should work too I think
something like
lambda x,p:x&(2**(64-p)) ought to work too
Needs to be offset right
You can't AND floats tho
ugh
>>> 0.1 & 0.2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'float' and 'float'```
Yeah, you can't
I already tried that :p
You can use struct
Let's find out..
lambda x,p:float.fromhex(x.hex()[:2+p]+x.hex()[-int(log(x,2)+2):]) rounds with p as the digits in hex
you could just do it the human way:
a = lambda x,i :float(str(x)[:str(x).find(".")] + str(x)[str(x).find("."):str(x).find(".")+i] + (str(x)[str(x).find(".")+ i] if int(str(x)[str(x).find(".")+ i + 1]) < 5 else str(int(str(x)[str(x).find(".")+ i]) + 1)))
that looks pretty stupid to me --- but it doesn't check index ranges
it uses if else ternary operator to round
In [166]: a(234.43637457,3)
Out[166]: 234.436
In [167]: a(234.43637457,4)
Out[167]: 234.4364
In [168]: a(234.43637457,5)
Out[168]: 234.43637
In [169]: a(234.43637457,6)
Out[169]: 234.436375
In [170]: a(234.43637457,7)
Out[170]: 234.4363746
also won't work if you round places above the decimal
maybe that makes it extra stupid
Idk who could use this
>>> a = ["foo", "bar", "egg"]
>>> [b for b in [c for c in a]]
['foo', 'bar', 'egg']
>>> [b for b in c for c in a]
['e', 'e', 'e', 'g', 'g', 'g', 'g', 'g', 'g']```
Last line does not work without allocating c on the 2nd line
what are you trying to do
Flatten a list, I think.

only 1 layer?
at first, yeah
Don't need second line if you swap the for clause order.
It also has the added bonus of actually flattening the list properly.
!e ```python
print([*[1,2,3], *[2,3,4], *[4,5,6]])
from functools import reduce
a = ["foo", "bar", "egg"]
print(reduce(lambda x, y: x + y, a))
# or just this
print([b for c in a for b in c])
list comprehension is faster
!e ```python
a = ["foo", "bar", "egg"]
b = [*i for i in a]
print(b)
sadness
ye i tried that too
If you define your own class you can do it with sum
I did it in my terrible multiplication program.
i dont actually have a use for this, just exploring nested fors in list comprehension 😄
I think, at least. It was a while ago.
(It wasn't a terrible program, it just did terrible multiplication.)
or sum
Or a for loop
sum isn't intuitive to use for this.
There are hoops to jump through.
>>> sum([*i] for i in a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
It starts with 0
oh
you can give it a start value
It's picky about strings as well.
sum(([*i] for i in a), [])
might not be the most obvious, but hey. this is #esoteric-python
It looks prettier if you replace all square brackets with normal ones.
Might need an extra comma though
Coming back to my original question, just to make sure I understood it. I can use nested fors in list comprehension as long as I declare them by access order?
# Complains because there is no c when trying to iterate
[b for b in c for c in a]
# [b (for b in c) (for c in a)]
# c is declared before trying to iterate over it, so it's fine
[b for c in a for b in c]
# [b (for c in a) (for b in c)]```
I have one of these in my working code, let me find it
Yep, you can chain 4-5 for and more but you have to take care of declaration order
This multiple for can do really weird things
lemme find that one in discord.py
>>> x = [1,2,3,4]
>>> y = [1,2,3,4]
>>> [a+b for a in x for b in y]
[2, 3, 4, 5, 3, 4, 5, 6, 4, 5, 6, 7, 5, 6, 7, 8]```
[print(x) for n in [int(input())] for l, x in [(''.join(' X'[e == n - 1] for e in range(n)), 1)] for r in range(n) for l, x in [(''.join('X '[l[c - 1:c + 2] in ('XXX',' ','X ','',' ')] for c in range(n)), l)]]```
sorta like a zip? but awful?
Credited to the one made / share it
it's not a zip, sounds like a weird implementation
yeah, it just adds all combinations
multiplication is easier to understand
>>> [a*b for a in x for b in y]
[1, 2, 3, 4, 2, 4, 6, 8, 3, 6, 9, 12, 4, 8, 12, 16]```
I also posted it here 👀 https://canary.discordapp.com/channels/267624335836053506/470884583684964352/603674251865620527
isn't that for r in range(n) just flexing as you dont really use it anywhere?
but yeah it's impressive ^^
I understand now, really cool 😃
I'm really hoping the retro-game themed #esoteric-python challenge isn't announced this week
Because I won't have internet this week
i'll do it on the 15th. i missed last month because i was busy doing NCS, but i'm free for basically all of this month so i should be able to think of something. i'd like to do a challenge on the 15th and 1st of each month (not today though, i don't want to clash with the retro event straight away)
I wonder what they could be? I cant really think of anything right now.
i have an idea for september 1st, but a retro game-themed esoteric challenge will require some thinking
make a retro game, but with restrictions. maybe
inb4 2d pokemon
the thing with an esoteric challenge is that i usually prefer the challenging part to be making the code interesting and unique, and making a retro game would be a significant challenge on its own which some esoteric-pythonistas might struggle enough with. i don't think a truly difficult challenge once in a while is a bad idea though, for those looking for something harder to work on.
Write a one-line command prompt game 😄
ouch
Wait what? In one line?
This sounds like something I need to see!
i had a one-line pygame game aswell! sort of a jungle speed
(globals().__setitem__("setvar",lambda k,v:globals().__setitem__(k,v)),setvar("pg",__import__("pygame")),setvar("random",__import__("random")),setvar("sys", __import__("sys")),setvar("locals", __import__("pygame.locals")),setvar("newfood",lambda:setvar("food",pg.Vector2(random.randint(3, 57)*10,random.randint(3, 57)*10))),newfood(),setvar("snakepos", pg.Vector2(30,30)),setvar("snakedir", pg.Vector2(10,0)),setvar("snakebody", []),setvar("clock", pg.time.Clock()),pg.display.set_caption("snake"),setvar("screen",pg.display.set_mode((600,600))),setvar("x",[0]),[(x.append(0),screen.fill((0,0,0)),pg.draw.rect(screen,(255, 0, 0),pg.Rect(food,(10, 10))),[(pg.draw.rect(screen,(255,255,255),pg.Rect(part,(10,10))))for part in snakebody+[snakepos]],snakebody.append(pg.Vector2(snakepos)),snakebody.remove(snakebody[0]),snakepos.__iadd__(snakedir),(setvar("snakepos", pg.Vector2(30, 30)),setvar("snakedir", pg.Vector2(10, 0)))if(snakepos in snakebody or snakepos.x == -10 or snakepos.x == 600 or snakepos.y == -10 or snakepos.y == 600)else None,(snakebody.append(pg.Vector2(snakepos)),newfood(),)if food == snakepos else None,[((pg.quit(),sys.exit(1))if event.type==locals.QUIT else((((setvar("snakedir",pg.Vector2(0,-10)))if event.key==locals.K_w else None,(setvar("snakedir",pg.Vector2(0,10)))if event.key==locals.K_s else None)if snakedir.x!=0 else((setvar("snakedir",pg.Vector2(-10,0)))if event.key==locals.K_a else None,(setvar("snakedir",pg.Vector2(10,0)))if event.key==locals.K_d else None))if event.type==locals.KEYDOWN else None))for event in pg.event.get()],pg.display.update(),clock.tick(10))for _ in x])```
thx 😃
neat :D
oh dear
it's like writing a normal program, just with "different syntax" and harder bugs.
"there is a bug on line 1" that helps xD
it basically a tuple with functions. and some tricks to do things like for loops, while loops, variables ect.
Maybe for the retro game themed challenge, we could have a retro game themed esolang challenge. (Something like
https://esolangs.org/wiki/MarioLANG)
Anyway, that's pretty crazy @polar plover I thought I was joking about a challenge like that 😄
thx 😃
i know i'm doing something bad when i have a lambda inside a lambda inside a lambda :D
why? can we see?
this is the function ```py
call = lambda func: (
lambda *args, **kwargs: (
lambda: func(*args, **kwargs)
)
)
i'm gonna be using it for postponed function calling. you'll see why in a bit
hello = call(print)("hello world!")
hello() # output: "hello world!"
a normal function would be better?
what are they? sounds interesting
the only keyword you can use is lambda.
hmm, and is there a goal?
i just wanna see how complex of a program i can make with that sort of restriction
and how decent i can make the code look (or at least, how readable i can make it) with that restriction
list-comps would not be allowed since we use for ?
exactly.
okay, lets make snake
also, boolean operators like and do count as keywords
lambda calculus can express any turing machine
@polar plover if in doubt, do ```py
from keyword import iskeyword
iskeyword("and")
True
if it's a keyword, you can't use it (unless it's lambda)
so using only lambda is definitely possible
could use recursion to make a loop, but would hit that recursion limit at some point.
yup.
you can get around that with trampolines
While loops will be tougher but if you have an infinite repeating sequence like itertools provides it'll work
is this cheating? py exec("print('hello world!')\nprint([x for x in range(2, 100) if 0 not in [x%y for y in range(2, x)]])")
map(lambda _: print("in for loop"), range(10))
[print(i) for i in iter(int, 1)]
no, no keywords except lambda
You're practically using keywords tbh
me? I just used exec and a string :P
iter and int aren't keywords
but for is
for and in are
Also @sick hound yours would fail if the text "for" wasn't allowed anywhere in the code
hm.
exec("print('hello world!')\nprint([x fo" "r x i" "n range(2, 100) if 0 no" "t i" "n [x%y fo" "r y i" "n range(2, x)]])")```
Like I said, just use map(f, range(n))
it should go without saying that things like exec and eval are not allowed
^
even though your code doesn't technically have keywords, it does use them
Also where's my events role I wanna host esochallenges too, I even have rewards in the form of steam keys
that's basically what my function above does
call = lambda func: (
lambda *args, **kwargs: (
lambda: func(*args, **kwargs)
)
)
just a bit different
yeah, yours passes things through
Not esoteric enough
@brisk zenith why bother with the 3 level lambda tho?
this is a decorator
because it looks nicer to do ```py
call(print)("hello, world!")
than
```py
call(print, "hello, world!")
imo
lambda func,*args,**kwargs:lambda:func(*args,**kwargs)``` wouldnt this work?
thats fair
but yeah, both would work
there isn't any, really. just trying to see how complex i can make it without having massively unreadable code
aight thats fair
like, right now i'm trying to reconstruct some common keywords (like if and for) using just lambda
it is not a keyword
ifs can be done with array indexing: [if_false, if_true][test]
yes
name = input("enter your name: ")
if_(name != "",
then(
call(print)("hello", name),
),
otherwise(
call(print)("hello!")
)
)
this is how i've reconstructed if else
"Speaker: David Beazley These days, programming style guides are all the rage. However, what if your style guide was so restrictive that it only gave you sin...
name = input("enter your name: ")
if_(name != "",
then = (
call(print)("hello", name)
),
otherwise = (
call(print)("hello!")
)
)
actually i prefer this, it's simpler
and can be replaced by all(), or with any()
how so
all and any don't return the object they short-circuit at like and does
hm
they just return true or false
hmm i wonder how a while could be structured to look/function normally
remember guys, None, True, and False are all keywords too
true = 0 == 0
false = 0 != 0
none = print("", end="")
easy to deal with though
while = lambda check, then_stmt: list(map(if_(check, then_stmt), itertools.repeat([0])))
while(v == 2,
then( ... )
)
mart, that v == 2 check will only be executed once
not at each loop
it's tricky to deal with that
stop the loop with next(iter([]))
while = lambda check_func, then_stmt: list(map(if_(check_func(), then_stmt), itertools.repeat([0])))
It throws StopIteration, which causes the expansion to end
oh yeah
while = lambda x: [*iter(lambda: [lambda: next(iter([])), lambda: print("hi")][x](), 1)]
while = lambda check_func,func:[*iter(if_(check_func(),then=func,otherwise=lambda:next(iter([]))))]``` @brisk zenith would this work?
oh wait
while = lambda check_func,func:[*iter(if_(check_func(),then=func,otherwise=lambda:next(iter([]))),1)]
I feel like part of the function ought to be a few layers of that expansion, so it can repeatedly erase the lists it relies on, so the ram usage is more log(n) than n
@sonic ginkgo i saw your fork of the python shenanigans this morning and i love it
@brisk zenith i meant to tag you
its getting unruly
did you see the calculator parser i tried and failed to write in the tests
its probably buried on a branch
i made the pattern and result take callables as an option. that i think was a good change. then i introduced a whole system for returning the value of the match with a special result __matchresult__
which i implemented cause i was trying to write a kind of hack recursive descent parser
will try and split off the insane stuff from the useful stuff, so i can make a PR for the docs and tests
neat :D
thought i had it compressed in a single line but it's not... a highly simplified jungle speed with pygame:D
https://paste.pydis.com/vavewovule.py
used it as part of a TTIE project, here's the same code but as an image
how are you supposed to read the code from the image?
parsing the bytes through a custom algorithm
(that i lost)
it was basically some shifts and xor-s, nothing too complicated
I think Discord compresses images a little
It definitely does
i've seen some of my uploaded gifs become real hard to see after uploading here
@sonic ginkgo thoughts?
option = input("Choose 0 or 1: ")
print_state = (
switch (option)
.case("0") (
call(print)("off!"))
.case("1") (
call(print)("on!"))
.default (
throw(ValueError)("invalid!"))
)
This like working?
can it do pattern matching and/or fallback or is it just if/else
well, did you see my pattern matching shenanigans from before?
idr
@brisk zenith i liked how you alternated between [] and () for the pattern matcher
print_state = (
switch (option)
.case["0"] (
call(print)("off!"))
.case["1"] (
call(print)("on!"))
.default (
throw(ValueError)("invalid!"))
)
idk, either one works
but yeah thats fun
but yeah thats fun
oh yeah i could make that alternate if i wanted
now you need an evangelism squad like attrs so people start using it 😛
i actually think the () feels more pythonic
the []s were sort of a hack instead of using a named method
@wind maple ```py
valid_python_version = (
match (amount=3)
[3, 7, :] (True)
[:, :, :] (False)
)
print(valid_python_version(3, 7, 4)) # True
print(valid_python_version(3, 7, 0)) # True
print(valid_python_version(3, 6, 9)) # False
print(valid_python_version(2, 7, 16)) # False
yes
valid_python_version = (
match (amount=3)
[3, 6:7, :] (True)
[:, :, :] (False)
)
what about ORs
