#esoteric-python

1 messages · Page 70 of 1

sick hound
#
().__class__.__base__.__subclasses__()[82].find_module('code').load_module().interact('',lambda _:'from ctypes import*;import sys;o=sys._getframe(6).f_locals;py_object.from_address(id(o)+sizeof(c_ssize_t)).value=dict;o["a"]();exit(19)')```
#

there

marsh void
#

Nice

#

Now that is cool 😎

brazen geyser
#

this is how satan programs

marsh void
#

I kinda get the flow though

sick hound
#

().__class__.__base__.__subclasses__()[82].find_module('code').load_module() imports and gets the code module

marsh void
#

@sick hound () at the start is just initializing a tuple to get to subclasses?

sick hound
#

yep

marsh void
#

hm

sick hound
#

().__class__ = tuple

marsh void
#

There might be a one-char thing?

sick hound
#

().__class__.__base__ = object

#

().__class__.__base__.__subclasses__() = every class

#

then use that to pull out classes from the import mechanism and get code

hot crypt
#

isn't type(()) shorter?

sick hound
#

we can't access type here

#

locals() is an integer

marsh void
#

Yep

hot crypt
#

ah

marsh void
#

@hot crypt that pfp is nice anyway okhandbutflipped

sick hound
#

so you get this py TypeError: 'int' object is not subscriptable

hot crypt
#

thanks 😄

sick hound
#

if you could access locals then all of that would be pointless

marsh void
#

But you can’t lmao

#

@sick hound why 19 though?

sick hound
#

why not?

marsh void
#

is there a random or something behind this

sick hound
#

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

marsh void
#

I’d make it 13 though

#

It’s my favorite number

#

¯_(ツ)_/¯

sick hound
#

¯_(ツ)_/¯

brazen geyser
#

is there like a list of common python code golfing/esoteric problem solving techniques?

#

TIL the code module can do all this cool stuff

marsh void
#
>>> 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

sick hound
#

https://codegolf.stackexchange.com/q/54/36188 there's this maybe? i found it in the pins of this channel @brazen geyser

marsh void
#
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

brazen geyser
#

ty @sick hound

sick hound
#

np

brazen geyser
#

why does python even have ;

#

guessing it's from the super early days trying to make it easier for c/c++ programmers to adapt

sick hound
#

@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("|"))

marsh void
#

Oh that’s cool

#

what about cipher?

sick hound
#

sec

marsh void
#

That was actually way shorter imo lol

sick hound
#
cipher=lambda s:"|".join(".".join(bin(ord(n))[2:]for n in str(ord(c)))for c in s)
#

@marsh void

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

brazen geyser
#

__import__('textwrap').wrap(p,6)

marsh void
#

@brazen geyser lmao this thing actually exists

brazen geyser
#

yep

marsh void
#
>>> 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?

sick hound
#
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
marsh void
#

Yep oki

sick hound
#

didnt know about wrap though, that's neat meta

desert zenith
#
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```
marsh void
#
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

sick hound
#

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)
marsh void
#

Oh yep formations. Cool! @sick hound

sick hound
#

😎

formal sandal
#

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)

tropic gulch
#

might even shave off another byte (space) by swapping the input() and exec string

formal sandal
#

oh yeah

grave rover
#

Hm

#

I wonder how my code is somehow leaking 1.7GB just by instantiating a few classes

formal sandal
#

How is that even possible?

brisk zenith
#

well i've got 42 in python haha

formal sandal
#

same

#

for x in input():print('01'[x<'1'],end='')

brisk zenith
#

for d in input():print("10"[d>"0"],end="")

#

fucking

#

yes

#

great minds think alike

formal sandal
#

Well, our solutions are totally different.

#

You used double quotes.

brisk zenith
#

yeah like a normal person

#

my quotes are consistent with the guidelines described for docstrings in PEP257

#

:)

formal sandal
#

A double quote takes twice as much effort to type as a single one because you have to press Shift to enter it.

brisk zenith
#

a capital letter takes twice as much effort to type than a lowercase one yet you still use capitals in your sentences

formal sandal
#

Right, because there is no 15min timer!

#

I hope.

brisk zenith
#

you don't know that :D

formal sandal
#

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.

brisk zenith
#

that's esoteric fingers, not esoteric python. haha

formal sandal
#

Is there a high-level wrapper around brainfuck?

#

Like a languages that get translated into bf.

wind maple
#

there are transpilers for almost all languages into brainfuck

#

how limited the section of code they allow is a different story though

sick hound
#

i just did my first clash of code

#

8 lines in python

brisk zenith
#

what was the task? :D

#

also that's not maximum compression, you could easily get rid of some whitespace like if i==0:

polar plover
sick hound
#

this was the challenge

#

we should have a clash of code channel

#

you guys got me addicted

formal sandal
#

Yes, it's very addictive.

#

How does the score system work in CoC?

#

I mean, in the leaderboard.

calm rampart
#

wait, how do you use up 20 bytes trying to do that in bash

#

tr 01 10, boom, done

formal sandal
#

Maybe that was a bash noob :)

calm rampart
#

not even obfuscated, it's the simplest most straightforward way to do it, unless i'm misunderstanding the problem

formal sandal
#

Does anyone want to play clashofcode in a private game?

polar plover
#

okay 😃

#

just wrote some spaghetti 🍝

formal sandal
#

Do you know how the scores for the leaderboard are calculated?

polar plover
#

idk, never really looked at it.

formal sandal
polar plover
formal sandal
#

Probably yes.

polar plover
#

what?!

formal sandal
#

I'm 2nd in Russia.

#

In Coc, though :)

#

Oh, yours is for coc too.

polar plover
#

yhe, only played that on here.

formal sandal
#

Brainfuck generation.

#

I had no idea you could connect Lord of the Rings and brainfuck.

#

@polar plover We're doing python only, right?

polar plover
#

yes

formal sandal
#

@polar plover both 2&3?

polar plover
#

okay

#

I am having trouble with the hours on the last test xD

formal sandal
#

Are you using round or //?

polar plover
#

got it working

#

was using datetime

#

and it only has hours up to 24

formal sandal
#

oh

#

I think I've found the intended trick.

#

How long are you?

polar plover
#

158

#

I went for datetime when I say the challenge xD, might not been the best idea.

#

but I gota go now

formal sandal
#

Also, if you use only one thing from a module, it's more costly to from it than to just import the whole module

polar plover
#

Should have used * at least....

formal sandal
#

@polar plover maybe another one?

polar plover
#

Can't, Just wanted to answer you real quick

formal sandal
#

ok

polar plover
#

@formal sandal I am back if you still want to play?

formal sandal
#

Sure.

formal sandal
#

damn it

polar plover
#

?

formal sandal
#

I started my own as well :))

polar plover
#

xD

#

should we just start, or see if somebody else joins?

#

how is it going?

#

gg

formal sandal
#

gg

#

it was going bad :)

polar plover
#

what did your code fail at?

#

ignoring the edge?

formal sandal
#

idk

#

I don't remember the second test.

polar plover
#

could have gotten one less: 0 <

#

why did I not see that

#

one more?

formal sandal
#

OK, just a second

#

I am ready.

polar plover
#

should we wait for more to join, or just start?

formal sandal
#

oof

polar plover
#

what does your code look like?

formal sandal
polar plover
#

👍

formal sandal
#

I have shared it

polar plover
#

saw that

formal sandal
#

maybe another one?

polar plover
#

was the score the totals of the inputs?

#

I took the average

formal sandal
#

well, average = total / 3.

#

it doesn't matter when you sort it.

formal sandal
#

Holy crap, I'm first in Russia now 🍷

polar plover
#

👍 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
#

???

marsh void
#

@formal sandal nice spaghetti though

formal sandal
#

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"

snow beacon
#

"also, always use meaningful identifiers"

#

I think golfers have the first one down pat.

formal sandal
#

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

sick hound
#

you haven't specified which way the scale is going

#

is 0 more garbage or less garbage

formal sandal
#

oh

#

the scale is garbage too :)

#

10 is pure garbage

#

0 is pep8-compliant well-written code

marsh void
#

I can see a lot of filter and qsort

grizzled cloak
#

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..

polar plover
#

xD

formal sandal
#
  1. You can use 's' only one time per program, and you can't store a variable which has 's' as an element
  2. You can use eval and exec, but only as functions (not "eval")
  3. You can't use any other letters or digits.
  4. You can use any other symbols.
  5. print Hello, world!
polar plover
#

I think I am soo close to do it without s, but then. it does not work.

hot crypt
#
import __hello__```
#

:v ?

polar plover
#

I see letters....

wind maple
#

I solved this already 😔

formal sandal
#

@hot crypt You can't use letters.

hot crypt
#

nor digits... only 1 's' and eval/exec?

polar plover
#

and symbols like <>()[]...+-% ect

hot crypt
#

i might have an idea

#

idea is dead

snow beacon
#

I can get arbitrary numbers, I just can't convert them into strings.

formal sandal
#

@snow beacon You can use 's' once.

snow beacon
#

but no t or r

#

f would be really helpful

formal sandal
#

!e ```python
print('%s' % 31415)

night quarryBOT
#

@formal sandal Your eval job has completed.

31415
snow beacon
#

Oh, neat.

#

I will continue tinkering.

formal sandal
#

You can get repr, but other stuff is harder...

#

!e ```python
_ = []==[]
__ = +++++++++++
___ = (('%s'*())%(' ',[]==[],...,' ',[]==[],...,' ',[]==[],...,' ',[]==[],...,))[::+]
print(___) # printing just for demonstration

night quarryBOT
#

@formal sandal Your eval job has completed.

repr
formal sandal
#

Then you can even access the letter 's'.

#

!e ```py
___ = 'repr'
_ = 1

print(eval(__)([]<[])[~])
#repr(False)[~True] == 'False'[-2]```

night quarryBOT
#

@formal sandal Your eval job has completed.

s
formal sandal
#

The Holy Grail...

#

@polar plover s

#

Now it's easy.

#

!e python _ = []==[] __ = _+_+_+_+_+_+_+_+_+_+_+_ ___ = (('%s'*(__))%(' ',[]==[],...,' ',[]==[],...,' ',[]==[],...,' ',[]==[],...,))[__::__+__] ____ = eval(___) _____ = [ ___[_+_], #p ___[_-_], #r ____(...)[_+_+_], #i ____(exec(''))[_+_], #n ____(eval)[_+_+_+_+_] #t ] ______ = eval(_____[_-_]+_____[_]+_____[_+_]+_____[_+_+_]+_____[_+_+_+_]) ______(______)

night quarryBOT
#

@formal sandal Your eval job has completed.

<built-in function print>
snow beacon
#

You can get s a bit more simply: ("%(_)s"%{"_":...})[-(""=="")]

formal sandal
#

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'.

snow beacon
#

You can multiply it and concatenate it.

formal sandal
#

you can't store a variable which has 's' as an element

snow beacon
#

You don't need to store it.

formal sandal
#

How would you use it then?

snow beacon
#

("%"+("%(_)s"%{"_":...})[-(""=="")])*-~-~-~-~-~(""=="") is a start

#

Wait, hold on...

formal sandal
#

If you have already used 's', you can't use '%s' again.

snow beacon
#

If you have s already, you can just use that. You don't need to get s from s

formal sandal
#

Exactly.

hot crypt
#

im not good enough for these challenges yet 😢

snow beacon
#

[..., ""=="", ""<"", 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()]

formal sandal
#

I have thought of another trick some time ago.

snow beacon
#

EFNTabcefilnoprstuvx

#

We have an x, and an f, so it should be pretty simple from there

formal sandal
#

I hope it's okay if I use numbers as shortcuts.

hot crypt
#
\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...
snow beacon
#

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

wind maple
#

can I spoil it

snow beacon
#

I kind of already know the steps, I just can't be bothered typing out a bunch of underscores to actually assemble the result.

wind maple
#

you can't use \x because it has a letter

formal sandal
#

)

wind maple
#

but you can use octal

formal sandal
#

You can't use digits.

#

Oh, you can have repr.

snow beacon
#

You can get x from the representation of exec

wind maple
#

how

#

what

#

oh right

#

seems overcomplicated

#
>>> eval('"\\%s"' * 13 % (110, 145, 154, 154, 157, 54, 40, 167, 157, 162, 154, 144, 41))
'Hello, world!'```
snow beacon
#

If you eval the string "repr" you get repr

formal sandal
#

Is there a way to get d?

hot crypt
#

dict?

formal sandal
#

You would need type for that...

snow beacon
#

It's not in any of the easy literals. You'd probably need to do ascii stuff

hot crypt
#

ya im awful at python

formal sandal
#

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(_____[~_+_]+_____[_+_]+_____[_])(_______))

night quarryBOT
#

@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']
formal sandal
#

BAM

gilded orchid
#

what have I just stumbled into

formal sandal
#
  1. You can use 's' only one time per program, and you can't store a variable which has 's' as an element
  2. You can use eval and exec, but only as functions (not "eval")
  3. You can't use any other letters or digits.
  4. You can use any other symbols.
  5. print Hello, world! (doesn't have to be exactly like that I guess)
gilded orchid
#

I'm so confused how you were even able to get a string there

calm rampart
#

the %s % True, Ellipses, etc

#

[this all evolved in staff lounge before lemon kicked them out]

gilded orchid
#

is there anyway to create strings not using any letters?

polar plover
#

"<", from a number: I have tried for a long time, and no.

gilded orchid
#

ah rip

polar plover
#

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.

gilded orchid
#

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?

polar plover
#

the challenge allows using exec

#

exec("")

#

but with just symbols, idk

formal sandal
#

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.

gilded orchid
#

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

jade dust
#

_=_+_

gilded orchid
#

oh yeah, wow I'm dumb

#

no clue why I used a bitwise operator there

jade dust
#

it's a cool challenge

gilded orchid
#

I think there might be a way to get inf and NaN using only symbols somehpow

#

also, I can do _+=_ instead of _=_+_ @jade dust

jade dust
#

oof

#

good job

gilded orchid
#

turns out you can get inf by spamming multiplication on a float

>>> _*_
65536.0
>>> _*=_
>>> _*=_
>>> _*=_
>>> _*=_
>>> _*=_
>>> _*=_
>>> _*=_
>>> _
inf
snow beacon
#
_=""==""
_+=_
_-=~_
_=_**_<<_```
#

Actually,

#
_=""==""
_-=~_-_-_
_=_**_<<_```
gilded orchid
#

Turns out you can get NaN by doing infinity divided by infinity

formal sandal
#

Well, in python 2 it's easy to get s: ````[]<[]`[~([]==[])]```

brisk zenith
#
_="%s"

__=~~(()==())
___=__<<__
____=___<<__
_____=___<<___
______=____<<___
_______=___<<____
________=____<<____

_________=eval((_%(()==()))[__::___]+(_%...)[____]+(_%(()==()))[__])
__________=eval((_%...)[____]+(_%(()==()))[__]+_________(_________)[_____-__:_____+__]+_________(_________)[____+__])
___________=_________(eval((_+".__"+_+"__")%((_________(_________)[-____-__:-__],)*___)))
_=eval(___________[_______+_____+__]+___________[____]+(_%(()==()))[__])

__________(
    _(+_____+_______+________)
    + _(+__+____+_______+________)
    + _(+____+_____+_______+________)*___
    + _(+__+___+____+_____+_______+________)
    + _(+____+_____+_______)
    + _(+_______)
    + _(+__+___+____+______+_______+________)
    + _(+__+___+____+_____+_______+________)
    + _(+___+______+_______+________)
    + _(+____+_____+_______+________)
    + _(+____+_______+________)
    + _(+__+_______)
)
#

@formal sandal

formal sandal
#

@brisk zenith Good, but you broke the rule number 1: ...you can't store a variable which has 's' as an element

brisk zenith
#

oh well :D

formal sandal
#

Also, why ~~(()==()) when you can use []==[]?

sick hound
#

I guess the ~~ is to turn it into an integer?

#
>>> []==[]
True
>>> ~~(()==())
1```
formal sandal
#

Right, but you can use True as an integer.

sick hound
#

...hmm

formal sandal
#

~ is binary negation

snow beacon
#
  • is less characters
formal sandal
#

True.

snow beacon
#

Pun intended?

formal sandal
#

False.

sick hound
#

@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

wind maple
#

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

gilded orchid
#

why would you do that

sick hound
#

why not

gilded orchid
#

yeah I guess

brazen geyser
#

lol

#

awesome

sick hound
#
(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

brisk zenith
#
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 😎

sick hound
#

my friend has done something like thiss too

#

its cool

hot crypt
#

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)```
brisk zenith
#

does it?

#

it always gives False on 2.7.16 for me

hot crypt
#

centos 6 python 2.7.5 does that

hollow hazel
#

always gives False in 2.7 and 3.7 on Ubuntu 18.04

#

2.7.15rc1 to be precise

hot crypt
#

wait i messed up

#

it's < not ==

hollow hazel
#

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

hot crypt
#

Yeah, py3 introduced some more sense into comparisons between types

sick hound
#

seems like it orders them by address

#

in py2

brisk zenith
#
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?

cunning wave
#

its not perfect pattern matching yet

#

but a start

#

also if it gets to function features ping rags

#

@brisk zenith

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

vague gust
#

I hate it and love it

brisk zenith
#

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

cunning wave
#

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

brisk zenith
#

maybe

#

actually, that's not possible i don't think

#

no it's not

#

actually.. i could try something similar, perhaps.

hot crypt
#

@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?

sick hound
#

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?

brisk zenith
#

yeah but it goes back and forth between True and False predictably

sick hound
#

probably just some quirks of memory allocation then

gilded orchid
#

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)

hot crypt
#

Exactly 😅

#

Oh running it twice inside the same statement seems to work aswell

#

As in, it continues the sequence

sick hound
#

i'm guessing it's something to do with memory

cunning wave
#
>>> 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

distant wave
#

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
formal sandal
#

!e ```python
print(id(lambda a: a) == id(lambda b: b))

night quarryBOT
#

@formal sandal Your eval job has completed.

True
brazen geyser
#

python 2 weirdness

#

what even is STORE_SLICE+0 o.O

#
STORE_SLICE+0()¶
Implements TOS[:] = TOS1.
#

interesting

marsh void
#

Yep

night quarryBOT
#
Noooooo!!

Sorry, but you may only use this command within #bot-commands.

sick hound
#
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

hot crypt
#

but the output here is different 🤔 False True True

#

I'm getting the outputs negated with that code

sick hound
#

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 ...`
distant wave
#

I smell an allocation

marsh void
#

same

cunning wave
#

so who is gonna bring out the debugger to find out whats happening now

calm rampart
#

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

sick hound
#

yep... hmm...

calm rampart
#
>>> 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)```
sick hound
#

oh so that means

calm rampart
#
>>> for _ in range(50):
...     a = lambda a: a
...     b = lambda b: b
...     print(id(a), id(b))
...     del b, a
...
44135696 44021824
(repeats)```
sick hound
#

hmm

#

that's interesting

calm rampart
#

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)```
sick hound
#

wait what

#

I wasn't expecting that

calm rampart
#

four addresses in play because old-a and old-b are both not deleted until after new-a and new-b are allocated

sick hound
#

OH

#

ok

calm rampart
#

(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

distant wave
#

hold on

#

nvm

#

It loops between four because it makes before it stores

vestal tusk
#

"simple" character to binary converterpy to_bin = lambda char: int(bin(ord(char))[2:])

sick hound
#
>>> to_bin('a')
1100001``` wot
#

why are you storing binary as a base 10 integer

vestal tusk
#

better than string, am i right?

formal sandal
#

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.

vestal tusk
#

why store a number as a str if you could use int

formal sandal
#

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
#

that doesnt exactly resemble the idea of pattern matching

#

var has to be present as var on the right side as well

marsh void
#

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

whole kiln
#

In that case you'd probably want ++i though 😉

marsh void
#

Yeah

whole kiln
#

I don't see it happening

formal sandal
#

print(i:=i+1)?

marsh void
#

@whole kiln i=0; print(++i) -> i=0; print(i:=i+1)

#

Yeah sorta

#

Should work out

whole kiln
#

Oh well I thought using that exact syntax

marsh void
#

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?

brazen geyser
#

(a, a:=a+1)[0] for postfix
a := a+1 for prefix

marsh void
#

Wait no

#

ok needa think

zealous widget
#

i just learned you can unpack a 0-tuple:

>>> [*()]
[]
marsh void
#

good job

zealous widget
#

this is great news

marsh void
#

sure

zealous widget
#

it makes calling functions from dicts a lot easier

marsh void
#

a = [*(1,2), *(3,4)]
a
[1, 2, 3, 4]

zealous widget
#

yes, but those aren't 0-tuples

marsh void
#

But it’s cool

zealous widget
#

yeah, but it's already expected behavior, but this is the weird edge case

marsh void
#

Decided to go and run test to define whether list(iterable) is slower than [*iterable] and measure the time and stuff

sick hound
#

[*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

snow beacon
#

Is it the same with sets?

agile patio
#
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. pysun

rugged sparrow
#
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)
gilded orchid
#

For the +, wouldn't it be less then 256?

#

instead of less than 255

#

Oh wait nvm

marsh void
#

Looks like flex

rugged sparrow
#

@marsh void any ideas why it wouldn't work?

sick hound
#

@rugged sparrow what string does it fail on and what does it do instead of working

rugged sparrow
#

and ik it works normally cause i tested it on another interpreter

#

it loops taking and printing input for me

sick hound
#

it looks like it's expecting you to input a null byte (character 0) at some point

rugged sparrow
#

hmm ok

sick hound
#

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

rugged sparrow
#

i thought ',' was only supposed to input one char

sick hound
#

yes, it does only input one character

#

but the way you're doing it reads one line and then only takes the first character

rugged sparrow
#

oh

sick hound
#

so if you have a simple cat program bf ,[.,]

#
>>> runBF(',[.,]')
test
twhat
w```
rugged sparrow
#

ah

sick hound
#

(in case it's unclear, the input was test, what)

rugged sparrow
#

oooohhhh

#

i get it now

#

dunno how to get the tree program to work tho

gilded orchid
#

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

edgy kelp
#

tsk inf is one char off

gilded orchid
#

oh wow

edgy kelp
#

welp wanted to try 9**9999999 and my pycharm's borked

gilded orchid
#

I used wolfram alpha to check it

edgy kelp
#

now I gotta update skeletons >.<

gilded orchid
#

9**9999999 has 9.5 mill digits

edgy kelp
#

got it 9E999

#

can't go higher than that 😛

gilded orchid
#

oh wow

sick hound
#

(it's infinity)

gilded orchid
#
>>> 9E307
9e+307
>>> 9E308
inf

9E307 is the highest you can go without being inf

edgy kelp
#

best thing is, not going to bork your pycharm 😄

sick hound
#

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

gilded orchid
#

oh wow, how did you figure out that decimal?

brisk zenith
#

!e ```py
import sys
print(sys.float_info.max)

night quarryBOT
#

@brisk zenith Your eval job has completed.

1.7976931348623157e+308
brisk zenith
#

that's the highest possible float in python.

sick hound
#

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```
rugged sparrow
#
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
whole kiln
#

Is it possible to get the instance bound to a method if all you have is the method object?

rugged sparrow
#

@whole kiln so you have for example x.__dir__ but not x? Just use x.__dir__.__self__

whole kiln
#

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.

rugged sparrow
#

yes

#

bar.__self__ should have the foo_instance

whole kiln
#

Alright

#

That works

#

__dir__.__self__ was just returning the same method

#

not sure what you meant by that

rugged sparrow
#

i meant that the __dir__ was the bar method from your example. i just wasnt super clear about it

whole kiln
#

Ok, that makes sense now

#

I was trying bar.__dir__.__self__ initially

rugged sparrow
#

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>]
>>> ```
whole kiln
#

Neat, I could see that being useful somehow

rugged sparrow
#

¯_(ツ)_/¯

#

tbh i thought it was what you were asking for lol

whole kiln
#

I had a much simpler question 😄

rugged sparrow
#

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

marsh void
#

hm

#

gc module, never used it

rugged sparrow
#
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

brazen geyser
#

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

sick hound
#

@rugged sparrow when you did del a, a still existed as part of a list returned by getInstances which the interpreter implicitly stored in _

gilded orchid
#

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)

snow beacon
#

From memory there are some libraries and ctypes tricks let you monkey patch builtin types

rugged sparrow
#

@sick hound I didn’t even know that _ was a thing

#

Why does it exist?

sick hound
#

so you can do things like this ```py

2 + 2
4
_ + 1
5```

marsh void
#

Magik

#

@sick hound so it’s like previous thing?

sick hound
#

yep

#

i'm surprised you didn't know about it

marsh void
#

What is the versionadded?

#

3.x?

sick hound
#

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```
marsh void
#

Ok

sick hound
#

i don't have any versions before that installed

marsh void
#

Don’t see use for it

#

at least for me

sick hound
#

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

storm token
#

Why doesn't python have a built in range function that allows for floats? Is there a reason?

fallen heath
#

How would you implement that? Many numbers don't exist as floats. Rounding errors would become a problem. At least that's my guess.

storm token
#

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)

brazen geyser
#

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

marsh void
#

heh, what’s frange?

brazen geyser
#

f for float

#

range for... range

marsh void
#

sounds interesting

brazen geyser
#

if you want more precision there's arange and linspace in numpy

storm token
#

How is there more precision? Pardon me, I'm new to Python and programming in general. Isn't there only floats in python?

brazen geyser
#

idk the underlying implementation details

#

what i do know is...

storm token
#

...

brazen geyser
#

(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]
>>> 
storm token
#

Ah ok. I see

#

!e

print("does this work?")
night quarryBOT
#
No way, José.

Sorry, but you may only use this command within #bot-commands.

brazen geyser
#

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]
>>> 
marsh void
#

@brazen geyser we have talked about this here, it is the way python treats floats

#
>>> import decimal
>>> decimal.Decimal(0.1)
#

try this code

brazen geyser
#

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

marsh void
#

@brazen geyser yeah I know about precise values, but yup, division and multiplication is weird

brazen geyser
#

can you stop pinging me please?

marsh void
#

ok sorry

wind maple
#

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

snow beacon
#

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.

sick hound
#
>>> decimal.Decimal(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')```
#

that is exactly 3602879701896397*2**-55

marsh void
#

🤔

snow beacon
#

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.

sick hound
#

i guess a lot of languages use floats instead of rational numbers

crimson pumice
#

How would rational number be better?

sick hound
#
>>> 0.1 + 0.2
0.30000000000000004```
#

you wouldn't get that

crimson pumice
#

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.

snow beacon
#

With floats, only values with denominators powers of two can be exactly represented. Rationals can represent any denominator

crimson pumice
#

But why use floats then? Is it memory usage?

snow beacon
#

They are a bit more efficient in that regard

#

Because they're less precise.

crimson pumice
#

Do you guys know any like official or unofficial module that has rational numbers? If I need to use rational numbers.

snow beacon
#

fractions module

crimson pumice
#

Or is my best guess just to round it off?

#

Ooh, okay. Thanks.

snow beacon
#

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.

lone ruin
#

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.

rugged sparrow
#

anyone here have any small esoteric challenges they want to throw my way?

calm rampart
#

@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)
brazen geyser
#

well thats disappointing

#

thanks @calm rampart , TIL

calm rampart
#

i'm disappointed that linspace doesn't do a better way (i checked, it doesn't)

brazen geyser
#

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

calm rampart
#

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

storm token
#

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

sick hound
#

it doesn't unless you use it with a float

#

also this is for esoteric python, not actual questions that make sense

#

:P

marsh void
#

haha

grave rover
#

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

distant wave
#

lambda x,p:float(str(x)[:log(x,10)//1+1+p])

grave rover
#
>>> 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

distant wave
#

ugh

grave rover
#

I think you forgot to wrap the index in int()

#

Floordiv will keep it a float

distant wave
#

That's annoying

grave rover
#

Yeah, I don't even know why since it's literally rounding to a whole number

distant wave
#

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))

night quarryBOT
#

@distant wave Your eval job has completed.

3.1415
grave rover
#

Nice

crystal mica
#
lambda x,p:x//1+(x-x//1)*10**p//1/10**p```
#

roundabout

#

but it works

distant wave
#

ooo, found something interesting

crystal mica
#

wait a min this one is posted

zealous widget
#

is this the opposite of code golf

grave rover
#

Not really

#

We're trying to come up with the most unreadable and idiotic way to do something

distant wave
#
>>> a = lambda x,p:x-x%(1/10**p)
>>> a(3.1415, 3)
3.141
grave rover
#

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

distant wave
#

Neither of mine are rounds, they're floors

#

Can make it a round though

grave rover
#

Same here

distant wave
#

If I want to round, I just need to double that % end, then remove it. Makes it kind a long though

crystal mica
#

bast cant you make it shorter with lambda x,p:x-x%10**-p

distant wave
#

...thank you

#

I knew I was forgetting something

crystal mica
#

interesting solution though

distant wave
#
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

grave rover
#

lambda x,p:(lambda m:(lambda v:(v//1+(v%1>=0.5))/m)(x*m))(10**p)

#

Should work too I think

distant wave
#

something like

#

lambda x,p:x&(2**(64-p)) ought to work too

#

Needs to be offset right

grave rover
#

You can't AND floats tho

distant wave
#

ugh

grave rover
#
>>> 0.1 & 0.2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'float' and 'float'```
distant wave
#

Yeah, you can't

grave rover
#

I already tried that :p

distant wave
#

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

zealous widget
#

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

grave rover
#

But does it round properly tho

#

Since this looks like a floor round

zealous widget
#

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

hot crypt
#

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

crystal mica
#

what are you trying to do

snow beacon
#

Flatten a list, I think.

hot crypt
crystal mica
#

only 1 layer?

hot crypt
#

at first, yeah

snow beacon
#

Don't need second line if you swap the for clause order.

#

It also has the added bonus of actually flattening the list properly.

distant wave
#

!e ```python
print([*[1,2,3], *[2,3,4], *[4,5,6]])

crystal mica
#
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

distant wave
#

!e ```python
a = ["foo", "bar", "egg"]
b = [*i for i in a]
print(b)

crystal mica
#

you cant do that

#

xd

distant wave
#

sadness

crystal mica
#

ye i tried that too

snow beacon
#

If you define your own class you can do it with sum

#

I did it in my terrible multiplication program.

hot crypt
#

i dont actually have a use for this, just exploring nested fors in list comprehension 😄

snow beacon
#

I think, at least. It was a while ago.

#

(It wasn't a terrible program, it just did terrible multiplication.)

distant wave
#

I suppose there's itertools.chain

#

itertools.chain(*a)

polar plover
#

or sum

snow beacon
#

Or a for loop

#

sum isn't intuitive to use for this.

#

There are hoops to jump through.

distant wave
#
>>> 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'
polar plover
snow beacon
#

It starts with 0

distant wave
#

oh

polar plover
#

you can give it a start value

snow beacon
#

It's picky about strings as well.

distant wave
#
sum(([*i] for i in a), [])
polar plover
snow beacon
#

It looks prettier if you replace all square brackets with normal ones.

#

Might need an extra comma though

hot crypt
#

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)]```
distant wave
#

I have one of these in my working code, let me find it

crystal mica
#

Yep, you can chain 4-5 for and more but you have to take care of declaration order

hot crypt
#

This multiple for can do really weird things

crystal mica
hot crypt
#
>>> 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]```
crystal mica
#
[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)]]```
hot crypt
#

sorta like a zip? but awful?

crystal mica
#

Credited to the one made / share it

#

it's not a zip, sounds like a weird implementation

hot crypt
#

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]```
crystal mica
#

ah ok, sorry, i did not see it

#

but damn it is cool

hot crypt
#

isn't that for r in range(n) just flexing as you dont really use it anywhere?

#

but yeah it's impressive ^^

wind maple
#

oh lol

#

it's not

hot crypt
#

I understand now, really cool 😃

gilded orchid
#

I'm really hoping the retro-game themed #esoteric-python challenge isn't announced this week

#

Because I won't have internet this week

brisk zenith
#

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)

polar plover
#

I wonder what they could be? I cant really think of anything right now.

brisk zenith
#

i have an idea for september 1st, but a retro game-themed esoteric challenge will require some thinking

polar plover
#

make a retro game, but with restrictions. maybe

crystal mica
#

inb4 2d pokemon

brisk zenith
#

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.

tame crow
#

Write a one-line command prompt game 😄

crystal mica
#

ouch

polar plover
#

@tame crow did that with snake and pygame 😃

#

with out using: eval exec or ;

tame crow
#

Wait what? In one line?

polar plover
#

yes 😃

#

wait, have it here somewhere

tame crow
#

This sounds like something I need to see!

hot crypt
#

i had a one-line pygame game aswell! sort of a jungle speed

polar plover
#
(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])```
crystal mica
#

oh my lord

#

that's pretty impressive

polar plover
#

thx 😃

brisk zenith
#

neat :D

polar plover
#

when pycharm tries and reformat it:

brisk zenith
#

oh dear

polar plover
#

it's like writing a normal program, just with "different syntax" and harder bugs.

#

"there is a bug on line 1" that helps xD

tame crow
#

lmao

#

Still working on running it, fiddled with installation recently

polar plover
#

it basically a tuple with functions. and some tricks to do things like for loops, while loops, variables ect.

gilded orchid
tame crow
#

Anyway, that's pretty crazy @polar plover I thought I was joking about a challenge like that 😄

polar plover
#

thx 😃

brisk zenith
#

i know i'm doing something bad when i have a lambda inside a lambda inside a lambda :D

polar plover
#

why? can we see?

brisk zenith
#

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!"
polar plover
#

a normal function would be better?

brisk zenith
#

of course it would be

#

but i've set myself certain restrictions

polar plover
#

what are they? sounds interesting

brisk zenith
#

the only keyword you can use is lambda.

polar plover
#

hmm, and is there a goal?

brisk zenith
#

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

polar plover
#

list-comps would not be allowed since we use for ?

brisk zenith
#

exactly.

polar plover
#

okay, lets make snake

brisk zenith
#

also, boolean operators like and do count as keywords

polar plover
#

okay

#

now, is just getting a loop somehow. cant use for or while right?

wind maple
#

lambda calculus can express any turing machine

brisk zenith
#

@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)

wind maple
#

so using only lambda is definitely possible

polar plover
#

could use recursion to make a loop, but would hit that recursion limit at some point.

brisk zenith
#

yup.

grave rover
#

Just use map(..., range(...))

#

For a for loop

wind maple
#

you can get around that with trampolines

grave rover
#

While loops will be tougher but if you have an infinite repeating sequence like itertools provides it'll work

sick hound
#

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)]])")

grave rover
#

map(lambda _: print("in for loop"), range(10))

distant wave
#

[print(i) for i in iter(int, 1)]

sick hound
#

no, no keywords except lambda

grave rover
#

You're practically using keywords tbh

sick hound
#

me? I just used exec and a string :P

distant wave
#

iter and int aren't keywords

grave rover
#

but for is

sick hound
#

for and in are

grave rover
#

Also @sick hound yours would fail if the text "for" wasn't allowed anywhere in the code

distant wave
#

hm.

sick hound
#
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)]])")```
grave rover
#

Like I said, just use map(f, range(n))

brisk zenith
#

it should go without saying that things like exec and eval are not allowed

grave rover
#

^

brisk zenith
#

even though your code doesn't technically have keywords, it does use them

grave rover
#

Also where's my events role I wanna host esochallenges too, I even have rewards in the form of steam keys

distant wave
#

infinite lambda:

#

lambda: (lambda x: lambda y: x(y))

brisk zenith
#

that's basically what my function above does

#

call = lambda func: (
    lambda *args, **kwargs: (
        lambda: func(*args, **kwargs)
    )
)
#

just a bit different

marsh void
#

Oh that’s some fun

#

But you know

distant wave
#

yeah, yours passes things through

marsh void
#

Not esoteric enough

rugged sparrow
#

@brisk zenith why bother with the 3 level lambda tho?

wind maple
#

this is a decorator

brisk zenith
#

because it looks nicer to do ```py
call(print)("hello, world!")

than
```py
call(print, "hello, world!")

imo

rugged sparrow
#
lambda func,*args,**kwargs:lambda:func(*args,**kwargs)``` wouldnt this work?
#

thats fair

brisk zenith
#

but yeah, both would work

rugged sparrow
#

yea

#

so whats the end goal of the program?

brisk zenith
#

there isn't any, really. just trying to see how complex i can make it without having massively unreadable code

rugged sparrow
#

aight thats fair

brisk zenith
#

like, right now i'm trying to reconstruct some common keywords (like if and for) using just lambda

rugged sparrow
#

oh yea for while loops you can use iter

#

if you arent counting that as a keyword

brisk zenith
#

it is not a keyword

grave rover
#

ifs can be done with array indexing: [if_false, if_true][test]

brisk zenith
#

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

grave rover
#

wew

#

@brisk zenith wanna work on a codegolf generator based on that? 👀

wind maple
grave rover
#

ono

#

dabeaz

brisk zenith
#

name = input("enter your name: ")

if_(name != "",

    then = (
        call(print)("hello", name)
    ),

    otherwise = (
        call(print)("hello!")
    )
)

actually i prefer this, it's simpler

grave rover
#

and can be replaced by all(), or with any()

brisk zenith
#

sort of

#

not quite

grave rover
#

how so

brisk zenith
#

all and any don't return the object they short-circuit at like and does

grave rover
#

hm

brisk zenith
#

they just return true or false

rugged sparrow
#

hmm i wonder how a while could be structured to look/function normally

distant wave
#

[*iter(lambda: print("Hi"), 1)]

#

is a while

rugged sparrow
#

thats basically a while True

#

need a while (cond)

brisk zenith
#

remember guys, None, True, and False are all keywords too

#
true = 0 == 0
false = 0 != 0
none = print("", end="")

easy to deal with though

rugged sparrow
#

none = [].sort()

#

its shorter

grave rover
#
while = lambda check, then_stmt: list(map(if_(check, then_stmt), itertools.repeat([0])))

while(v == 2,
      then( ... )
)
brisk zenith
#

mart, that v == 2 check will only be executed once

#

not at each loop

#

it's tricky to deal with that

distant wave
#

stop the loop with next(iter([]))

rugged sparrow
#

while = lambda check_func, then_stmt: list(map(if_(check_func(), then_stmt), itertools.repeat([0])))

distant wave
#

It throws StopIteration, which causes the expansion to end

grave rover
#

oh yeah

distant wave
#
while = lambda x: [*iter(lambda: [lambda: next(iter([])), lambda: print("hi")][x](), 1)]
rugged sparrow
#
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)]
distant wave
#

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

brisk zenith
#

@sonic ginkgo i saw your fork of the python shenanigans this morning and i love it

sonic ginkgo
#

@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

brisk zenith
#

nope

#

i last checked like 12 hours ago

sonic ginkgo
#

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

brisk zenith
#

neat :D

hot crypt
#

used it as part of a TTIE project, here's the same code but as an image

dull leaf
#

how are you supposed to read the code from the image?

hot crypt
#

parsing the bytes through a custom algorithm

#

(that i lost)

#

it was basically some shifts and xor-s, nothing too complicated

snow beacon
#

I think Discord compresses images a little

distant wave
#

It definitely does

zealous widget
#

i've seen some of my uploaded gifs become real hard to see after uploading here

brisk zenith
#

@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!"))
    )
marsh void
#

This like working?

wind maple
#

can it do pattern matching and/or fallback or is it just if/else

brisk zenith
#

well, did you see my pattern matching shenanigans from before?

wind maple
#

idr

sonic ginkgo
#

@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

brisk zenith
#

oh yeah i could make that alternate if i wanted

sonic ginkgo
#

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

brisk zenith
#

@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

wind maple
#

oh slices

#

can it do ranges

brisk zenith
#

yes

#
valid_python_version = (
    match (amount=3)
        [3, 6:7, :] (True)
        [:, :, :] (False)
)
wind maple
#

what about ORs