#esoteric-python

1 messages ยท Page 57 of 1

lusty vector
#

Ah. I did manage to know that it used recursion though

#

Chibli, it appears so. <2 letters long and it returns a 1

viral hedge
#

Or well, True / False since it's a bool

buoyant agate
#

there's 2 exit conditions, <2 characters or the first and last character are not the same

lusty vector
#

Okay. Next one please. ๐Ÿ˜ƒ

tropic gulch
#

๐Ÿ˜ป

sick hound
#
if a == True:
    a = True
elif a == False:
    a = True```
#

the gore

unique shoal
#

mp = lambda s: reduce(lambda x, y: x+(y&1), map(s.count, set(s)), 0) < 2

(as with many traditional golfing problems, this one relies on the oft missed reduce builtin)

sick hound
#

Can i ask how code golfing works?

unique shoal
#

make it as short as you possibly can

#

that's really all there is to it

brisk zenith
#

yeah

sick hound
#

i am not able to process that already, how to make it shorter?

unique shoal
#

depending on who you talk to whitespace may or may not count

brisk zenith
#

remove whitespace, shorten variable names, sacrifice speed for smallness

sick hound
#

and the space between lambda x, y isn't neccessary, right?

unique shoal
#

it is not

dense spire
#

the whole lambda isn't neccessary.

brisk zenith
#

none of the spaces are

unique shoal
#

the platform I wrote this for didn't count it against me

brisk zenith
#

bar the one after the lambda

lusty vector
#

I donno what reduce or map does. So not gonna try

buoyant agate
#

from functools import reduce

sick hound
#

map applies a function to each item in an iterable

#

reduce takes a function that takes two arguments and does something like this:
reduce(func, [1, 2, 3, 4]) -> func(func(func(1, 2), 3), 4)

misty trellis
#

So can I just ask for a gold python of something just for sheer fun?

brisk zenith
#

oh fancy

#

write a function to determine whether a given number is prime or not prime. return a bool

misty trellis
#

What's the shortest python code you can make to encode a str in Caesar cipher

brisk zenith
#

f=lambda n:all(n%q for q in range(2,n)) this is the shortest i can do for my prime one

sick hound
#

yeah thats probably the shortest you can get

#

well 6 ams a good time as any to sleep i guess

brisk zenith
#

haha

viral hedge
#

These lambdas have me stumped in Lucys snippet

buoyant agate
#

I think I wrote a golf caesar cipher at one point, gonna try find it

unique shoal
#

I've got an expanded form I used to reason it out for myself after I found it and couldn't remember what it did, if you're interested

brisk zenith
#

i read caesar salad

sick hound
#

I am lucy

buoyant agate
#
def shift(s: str, key: int = 13) -> str:
    return ''.join(chr((ord(c) - (65 if c.isupper() else 97) + key) % 26 + (65 if c.isupper() else 97)) if c.isalpha() else c for c in s)```
lusty vector
#

No. You are not lucy ๐Ÿ˜›

brisk zenith
#

typehinting in golf

#

why not use a lambda? :D

unique shoal
#
def parity_reduction(a, b):
    return a + (a & b)

def can_make_palindrome(string):
    return reduce(parity_reduction, [s.count(x) for x in set(x)], 0) < 2```
@viral hedge @sick hound
buoyant agate
#

look, you can golf it more if you want, that's what I had

brisk zenith
#
f=lambda s,k:''.join(chr((ord(c)-(65 if c.isupper()else 97)+k)%26+(65 if c.isupper() else 97))if c.isalpha()else c for c in s)```
perhaps this works
sick hound
#

thanks lacy

viral hedge
#

Im gonna have to sit down with that one when the coffee kicks in ๐Ÿ˜…

brisk zenith
#

im sure you can squish more whitespace from it

lusty vector
#

What is Caesers cipher?

buoyant agate
#

You encrypt a string using an offset between 1 - 25, let's say the offset is 1, A -> B, B -> C ... Z -> A All letters are shifted 1 to the right,

#

And then decrypting is the same but to the left (subtract)

tropic gulch
#

okay, so upper/lowercase is prserved, and each of them is rotated separately, like y + 3 = b and Y + 3 = B ?

#

and all non-alphabetic characters stay as they are

#

Okay, done in 110 bytes.

#
f=lambda s,k:"".join(chr([ord(c),(ord(c)+k-97)%26+97,(ord(c)+k-65)%26+65][c.isalpha()+c.isupper()])for c in s)
#
>>> f("Hello, World!", 3)
'Khoor, Zruog!'
#

Anybody beating that? ๐Ÿ˜Ž

buoyant agate
#

You could probably do o=ord;f=...

brisk zenith
#

not in a lambda

sick hound
#
o=ord;f=lambda s,k:"".join(chr([o(c),(o(c)+k-97)%26+97,(o(c)+k-65)%26+65][c.isalpha()+c.isupper()])for c in s)```
wind maple
#

def f(s,k): is shorter than a lambda

buoyant agate
#

You still need to return though

tropic gulch
#

but with def you need return

#

ninja'd >_>

brisk zenith
#

haha

wind maple
#

right

tropic gulch
#

yeah, o=ord looks good

#

thought about that, but haven't added it yet because I wondered if there might be a way to use just one instead of 3

brisk zenith
#

why not store 65 and 97 in one-letter variables?

buoyant agate
#

I don't think it actually saved any characters in this case

tropic gulch
#

6565 is shorter than a=65aa

cunning wave
#

So we can post any bad python here?

tropic gulch
#

only the best bad Python though

cunning wave
#

Hm

brisk zenith
#

hm

cunning wave
#

id(MyClass()) == id(MyClass))

Will always return true

#

Is that good ?

brisk zenith
#

no

cunning wave
#

:(

sick hound
#
class A:
 def __new__(_):return A```
buoyant agate
#

What have you done to make that happen?

cunning wave
#

Nothing it just worked

buoyant agate
#
>>> class A: pass
>>> id(A()) == id(A)
False```?
cunning wave
#

HUH

#

it worked for me

#

When I did it last time

sick hound
#
def id(a):return 0```
viral hedge
#

isn't you parenthesis misplaced wattle?

sick hound
#

No, nix's parenthesis misplaced

viral hedge
#

^That's the one

cunning wave
#

I remember reading that on a GitHub repo about python fuckups too

viral hedge
#

Or rather, 1 too many

cunning wave
#

Oh did I missplace?

sick hound
#
id(MyClass()) == id(MyClass) # extra bracket -> )```
cunning wave
#

I type on mobile

#

Woopsie

#

It wasn't id

#

Ooh

#

It's hash

#

hash(MyClass()) == hash(MyClass())

wind maple
#

This is a CPython optimization

#

And I also think it's repl-only

slim pecan
#

that definitely won't always be true though

cunning wave
wind maple
#

it allocates the same space twice

#

For whatever reason

#

I think it's just that hash() creates a "scope"

#

but the is statement doesn't because it's an expression

cunning wave
wind maple
#

Also a CPython optimization

#

in pypy that behaved differently IIRC

#

The range was larger or something

#

When it turns a = 257; b = 257 into a code object it sees that the value is the same for both and uses the same object for both

#

But it can't do it when you define them separately

cunning wave
#

IMPLICIT IN PYTHON

#

Unacceptable

wind maple
#

more implicit is more than implicit

#

Remind me to demonstrate what I mean

cunning wave
#

Demonstrate what you mean @wind maple

wind maple
#

I'm watching a talk

slim pecan
#

What talk is it?

cunning wave
wind maple
brisk zenith
#

@wind maple ```py
def _exec_code(code, *args, **kwargs):
"""Execute a CodeType object with args and kwargs."""

# We re-assign the bytecode of this empty
# function with the CodeType object so that
# it can be executed in a normal manner.
util = lambda *args, **kwargs: None
util.__code__ = code

return util(*args, **kwargs)

wind maple
#

but why

brisk zenith
#

so the code can be executed easily :P

misty trellis
#

You did the Caesar quite well now can you evalute a grid of Conway's game of Life in the uglisest shortest code as possible?
(You can use whatever data type for the grid. Go crazy)

brisk zenith
#

use a set :^)

#

interesting challenge would be to use an int for the grid

#

very possible

misty trellis
#

One number? MHM

#

Yea

brisk zenith
#

yup

#

use the int as an array of 1s (alive) or 0s (dead)

#

10010110

misty trellis
#

Yeah but conways is 2d

brisk zenith
#

add a meta-byte at the end which specifies the width of the grid

tight hemlock
#

64 bit ints -> 8x8 grid

brisk zenith
#

so a width of 2 would allow the program to know that 10010110 would become

10
01
01
10```
#

or that too yeah

misty trellis
#

Yeah and now just from that int create a new int of the new gen

brisk zenith
#

sure

#

bitwise operations

tight hemlock
#

lots of bitwise operators

brisk zenith
#

yeah

#

lots

#

i'mma give it a go

misty trellis
#

Gl

brisk zenith
#
if __name__ == '__main__':
    game = GameOfLifeWithAnIntAsTheGridDotPHP.from_array([
        [0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 1, 1, 1, 1]
    ])

    print(game.grid)  # 15
    print(f"{game.grid:064b}")  # 0000000000000000000000000000000000000000000000000000000000001111
light patrol
#

what is this

brisk zenith
#

hell

light patrol
#

what is the purpose of this channel

#

how can something be 'barely' python

brisk zenith
tight hemlock
#

read channel topic

light patrol
#

no, i can read

tight hemlock
#

also

light patrol
#

thanks for helping me!

tight hemlock
#

reee using python for bit manipulations

brisk zenith
#

using python for bit manipulations

#

:^)

light patrol
#

whats bad about that

brisk zenith
#

python

tight hemlock
#

python is not good at bit stuff

light patrol
#

so

brisk zenith
#

python is just so high-level that it's impractical to do bit-manipulation

light patrol
#

i still do it ๐Ÿ˜Ž

brisk zenith
#

same :D

tight hemlock
#

yeah with the type dynamically changing and resizing and all

#

you can never be sure the bit manipulaitons are going to do what you want them to do

light patrol
#

thank god python isn't a strong typed language

brisk zenith
#

it can be if you modify the bytecode :^)

tight hemlock
#

it is strongly typed

#

its not statically typed

light patrol
#

that is what i meant

brisk zenith
#

yeah

#

static typing might actually be possible with bytecode modifications, now that i think of it

#

(this is why the channel's called barely-python btw)

light patrol
#

but hence it is still python

#

this is not quantum physics - one cannot be python and barely python at the same time

tight hemlock
#

yes

#

barely

light patrol
#

it is either python or not python

#

can ice cream be bare?

#

can you have barely-ice cream

#

no.

tight hemlock
#

yes

light patrol
#

what

brisk zenith
#

modifying the python bytecode so that it acts like not-python is pretty barely-python to me

buoyant agate
#

Best so far is probably type hinting all your variables and having a linter yell at you if it is wrong

tight hemlock
#

also python vm languages

brisk zenith
#

yeah

misty trellis
#

Lol nice progress juanita

brisk zenith
#

thanks haha

light patrol
#

what is that in your profile picture

tight hemlock
#

mine?

brisk zenith
#

whose?

light patrol
#

yours

#

i think rags' is pretty obvious.

tight hemlock
#

i'm not sure whats in mine

#

so

brisk zenith
misty trellis
#

OMG

light patrol
#

i like how you have that image on demand

brisk zenith
#

hell yeah

tight hemlock
#

oh wow i was thinking its like a cell microscope closeup or something

light patrol
#

@tight hemlock theres hella shit in your profile picture

brisk zenith
#

i should change it because nobody knows what it is until i tell them haha

misty trellis
#

Wow this is too offtopic

#

Btw

light patrol
#

don't change it, juan

brisk zenith
#

it's barely even python, i guess you could say

misty trellis
brisk zenith
#

GOOD

misty trellis
#

ONE*

#

YEE

light patrol
#

wait juan

#

is that your alpaca

wind maple
#
>>> class CinMeta(type):
...     def __lshift__(self, other):
...         print(other, end='')
...         return self
...
>>> class cin(metaclass=CinMeta):
...     pass
...
>>> cin << "test" << 123 << '\n'
test123```
light patrol
#

or is it off google

brisk zenith
#

nope, it's one of my friends' alpacas

light patrol
#

i see

brisk zenith
#

@wind maple but does it assign? :^)

misty trellis
#

Guys offtopicccccc

wind maple
#

assign what

light patrol
#

can we not turn this into like C

brisk zenith
#
cin >> varname;```would be cin
misty trellis
#

Why not

#

Lmao

wind maple
#

trivial to imlpement

light patrol
#

so don't.

#

move on.

#

noone needs that.

brisk zenith
#

i've already done it

wind maple
#

You're in the wrong channel lad

light patrol
#

.

wind maple
#

This is the "awful hacks" channel

brisk zenith
misty trellis
#

"I don't want to code in C"

Goes to python.
"Let's program C in Python!"

light patrol
#

i thought it was just the 'hacks' channel

wind maple
#

I have to say this is hot garbage

brisk zenith
#

@misty trellis very yes

light patrol
#

is that a positive

wind maple
#

cin >> undefined isn't valid in C++ either

brisk zenith
#

it's garbage to begin with, so hot is an improvement

#

yes i know, i implemented that on purpose

#

because this is still python

wind maple
#

does it have cin semantics or is it just input

brisk zenith
#

it allows for c++ style but not the exact same semantics

light patrol
#

yes but juan

#

do you have the book

#

the c++ programming language third edition by bjarne stroustrup, the creator of c++

#

rrp $50 holy shit

#

i got it for like $8

brisk zenith
#

@wind maple i was planning to figure out a way of making them auto-cast to their typehinted values, but __annotations__ is evaluated at runtime. i have ideas though

tight hemlock
#

a tour of C++ edition 2 coming out soon updated for C++17 and some of C++20, if anyone wants to get into C++ right now

light patrol
#

how old is this book

tight hemlock
#

oh already out

light patrol
#

no, i meant mine

tight hemlock
#

an year or two? not v old

#

an year i think

#

they're both by bjourne btw

light patrol
#

...

#

published june 1997

#

this book is older than me

tight hemlock
#

thats the first edition

light patrol
#

third

#

this is the third edition

tight hemlock
#

third edition was 2013

light patrol
tight hemlock
#

it contains C++11 info, it cant be published 1997

brisk zenith
#

this is barely even barely-python

light patrol
#

the third edition, dude

tight hemlock
#

oh whoops confused 4 and 3

brisk zenith
#

trusts a single source

#

:^)

tight hemlock
#

3rd is published 2000

light patrol
#

june 1997

brisk zenith
#

i was published in 2002

light patrol
#

ok

#

yes youre correct

#

february 2000

#

is this book even reliable anymore?

#

took 13+ years for a new edition to be published

tight hemlock
#

yes it is

#

new version released because modern c++ had considerably changed

light patrol
#

therefor

#

is my book reliable?

#

what changes had to be?

tight hemlock
#

new language editions came out, some features and patterns became standard

#

btw

#

#ot

brisk zenith
#

thank you

light patrol
#

technically speaking this is barely python

brisk zenith
#

no

#

this is not python

light patrol
#

this is python in a thinly dispersed or scattered way

brisk zenith
#

no, it really isn't. please move to offtopic

viral hedge
#

I once tried to shorten my code for a machine learning task that only allowed x amount of characters. Does this belong here? py from sklearn.neighbors import KNeighborsRegressor as kn;from sklearn.model_selection import train_test_split as tts;import pandas as p;from numpy import array as a;d = p.read_csv("Flaveria.csv");d.iloc[:, 0] = d.iloc[:, 0].apply(lambda n: {"L":0,"M":2,"H":3}.get(n));d = p.concat([d.drop("species", axis=1),p.get_dummies(d["species"])], axis=1);X, x, Y, y = tts(a(d.loc[:, d.columns != "Plant Weight(g)"].values), a(d["Plant Weight(g)"].values), test_size=0.15);print(kn(n_neighbors=3).fit(X, Y).score(x, y))

slim pecan
#

I am both amused and horrified

viral hedge
#

I probably could have used iloc in pandas to shorten it a bit more, but i met the requirements feelskawaiiman

sharp canyon
#

Alright, dumb question time from Hemlock. ; just signifies end of line as it would in most other languages?

tropic gulch
#

yep

slim pecan
#

yeah it's usually the first rule you break when you golf

#

using ;

sharp canyon
#

Does using ; in regular code break things in regular Python code or is it just frowned upon because it's not needed?

brave bison
#

i use ; in c++

slim pecan
#

it's a PEP8 violation

sharp canyon
#

Gotcha

slim pecan
#

otherwise it's fine, yeah

#

this isn't a C++ channel though l33t :P

sharp canyon
#

Sudden urge to turn my screen name to "PEP8 is my bible" for a bit...

brave bison
#

i use "" instead of '' for strings

sharp canyon
#

I mean you can use either

brave bison
#

thought pep 8 is only '' for strings

sharp canyon
#

I thought it was a matter of what the string was for. If it's something the user is going to see you use double quote marks, if it's just an internal string it's single?

#

Either way, not a big deal

viral hedge
#

Depends on keyboard layout as well id assume

slim pecan
#

I use ""

#

'' is weird to me

#

I mean, you wouldn't use 'text' to quote someone in English

viral hedge
#

' is odd for me to type since i have to use my right pinky to hit it, while " is just shift + 2

brave bison
#

u have a weird keyboard

viral hedge
#

Scandinavian layout

slim pecan
#

it's a non-american keyboard

sharp canyon
#

That's normal for non US keyboards, l33t

slim pecan
#

mine is like that too

brave bison
#

im in europe and everyone uses american layout

sharp canyon
#

What part of Europe, though

slim pecan
#

almost nobody uses american layout in europe

#

lol

sharp canyon
#

English speaking part?

brave bison
#

no

#

nobody speaks english basically

slim pecan
#

Where's that, romania or somewhere like that?

brave bison
#

yes

sharp canyon
#

Latvia. Under the benevolent rule of Dr. Doom

#

Either way, so golfing is pretty much just a crap ton of abusing aliasing, lambdas and other such tricks?

viral hedge
sharp canyon
#

How do you access the grey characters on those keys?

brave bison
#

weird and unnatural

sharp canyon
#

Alt?

viral hedge
#

alt

sharp canyon
#

Cool

viral hedge
#

It's just what you're trained to use.

#

Mine makes sense to me, just as yours make sense to you (even though things like <> and {} are slightly odd)

brave bison
#

american layout actually makes common sense

slim pecan
#

it's usually right alt I think, yeah

sharp canyon
#

I'd argue the point more, l33t, but this isn't off-topic

slim pecan
#

yeah

#

and it's not weird because you're not used to it :P

wind maple
#

PEP8 doesn't actually forbid the use of semicolon

#

What it does say is "don't cram stuff you don't need to together"

sharp canyon
#

Seems like most linters will frown on it

#

PyCharm's default certainly does

viral hedge
tropic gulch
#

Actually semicolons don't give you an advantage in golf normally

#

Only inside indented blocks

#

Because both a linebrak and a semicolon are one character

#

But it's more handy to oneline stuff usually

#

as long as it's not too long at least.

sharp canyon
#

Can you give a basic example of how indented stuff is handled in golf? I've always been confused by that since Python is based on whitespace

tropic gulch
#

If you just have one indentation level, you can inline it

#

once you get multiple, you have to split all but the innermost on separate lines

viral hedge
#

I assume, that when you start writing golf code with multiple indentations you may want to rethink your approach?

tropic gulch
#
for i in range(42):x=i**2print(x)

for i in range(42):
 if i%2==0:x=i**2;print(x)

for example, IIRC

#

sometimes netsed loops/conditions are unavoidable

#

and the cost of one character per indentation level might be lower than refactoring

sharp canyon
#

Gotcha

brave bison
#

bot.help()

slim pecan
#

This isn't #bot-commands

brave bison
#

bot.pep()

#

nvm

slim pecan
#

@brave bison Go to #bot-commands

slim pecan
#

@fast torrent Why are you spamming?

fast torrent
#

Sry won't happen again

slim pecan
#

Good squishy

sick hound
#
from ctypes import *;print(cast(id(7106412),POINTER(c_char))[24:27].decode())```
calm rampart
#
7106412 .to_bytes(3,'big').decode()```
bitter comet
#

Has anyone worked with SLAM stuff before?

pine edge
#

python gore

#

(id(1+1)==id(1+1))^(id(10**5+1)==id(10**5+1)) and id(100000000000)==id(100000000000)

#

anyone who can adequately explain why this returns true earns my respect

#

i wrote it and i only have a vague idea of why

calm rampart
#

@pine edge because of constant folding.

pine edge
#

that explains the second and third booleans, but why does the expression 1+1 return a constant object

calm rampart
#
 1           0 LOAD_NAME                0 (id)
             2 LOAD_CONST               0 (2)
             4 CALL_FUNCTION            1
             6 LOAD_NAME                0 (id)
             8 LOAD_CONST               0 (2)
            10 CALL_FUNCTION            1
            12 COMPARE_OP               2 (==)
            14 LOAD_NAME                0 (id)
            16 LOAD_CONST               1 (100001)
            18 CALL_FUNCTION            1
            20 LOAD_NAME                0 (id)
            22 LOAD_CONST               1 (100001)
            24 CALL_FUNCTION            1
            26 COMPARE_OP               2 (==)
            28 BINARY_XOR
            30 JUMP_IF_FALSE_OR_POP    46
            32 LOAD_NAME                0 (id)
            34 LOAD_CONST               2 (100000000000)
            36 CALL_FUNCTION            1
            38 LOAD_NAME                0 (id)
            40 LOAD_CONST               2 (100000000000)
            42 CALL_FUNCTION            1
            44 COMPARE_OP               2 (==)
       >>   46 RETURN_VALUE```
#

the entire expression is evaluated at compile time

#

well, the entire each int expression

pine edge
#

wait so if all of those are loaded as constants then why

#

not (id(10**5+1)==id(10**5+1))

calm rampart
#

er

#

wait

#

i didn't notice the xor part, and it returns false for me

#

however, in your case, if it does return true, I can still explain

#

the optimization isn't, for whatever reason, happening to 10**5+1

pine edge
#

that's kind of a cop out but i'll allow it

#

๐Ÿ‘

calm rampart
#

but id(1+1) is still constant because all integers with values between 0 and 256 are interned

#

even if it's not constant-folded

pine edge
#

yeah i remember that comment in the cpython source

calm rampart
#

between -5 and 256.

#

and the 100000000000 is 100000000000 because all integer literals with the same value in the same source code unit get the same constant object regardless

pine edge
#

i didn't know about the literal scan thing, that's kinda neat

#

ok you can do some serious fucking spooky action at a distance with that literal scan thing

#

any two parts of code can use the gc module to interact via seemingly disconnected literal values

#

more observations: id(9001)==id(eval("9001")) is false because evaluation occurs somewhere else, but id(eval("9001"))==id(eval("9001")) works, because apparently consecutive eval calls happen in the same parser'

tropic gulch
novel vine
#

So meta programming is possible in C++ (where things evaluate at compile time. Essentially. ) is that also possible in python on a large scale?

brisk zenith
#

i'd like this, it could make for some interesting AST fuckery

#

can i claim this channel to be my home on this server? i just belong here. :P

solar osprey
#

what

#

what the hell

#

what

#

uh what

#

what's going on there

#

i don't understand anything that's being posted in this channel

pine edge
#

this is extremely rediculous

brisk zenith
#

@ashen rivet you're really not missing out on anything. most of the stuff you see here should not be used in your genuine projects :D

unique shoal
#

juan you still have to help ppl don't spend ALL your time here

#

one might call this place the opposite of helping people

sick hound
#

golfing is stupid

#

fuck golfing

#

goes against all common sense and logic

viral hedge
#

That's the point

sick hound
#

@brisk zenith post some challenges :p

calm rampart
#

hey maybe i should clean up my __build_class__ for allowing nested classes to inherit from the containing class and post it in here

brisk zenith
#

@sick hound
golf challenges?

  • tictactoe
  • connect 4
  • image to ascii: input the filename and dimensions in chars
  • random maths quiz - gradual difficulty increase, scoring, persistent leaderboard
  • ascii sierpinski triangle: input amount of iterations
#

i'll be really happy if somebody knows a way to execute code at "compile time" (before AST evaluation)

calm rampart
#

I could swear that there was some trick demonstrated on the python mailing list or something where you define an encoding that transforms the source of python files

#

maybe you could do something with importlib

brisk zenith
#

hmm

novel vine
#

dont give Juan ideas

brisk zenith
#

haha

#

the moral of this channel right there

tropic gulch
#

I just found this somewhere in my chat history...

#
(lambda _, __, ___, ____, _____, ______, _______, ________:
    getattr(
        __import__(True.__class__.__name__[_] + [].__class__.__name__[__]),
        ().__class__.__eq__.__class__.__name__[:__] +
        ().__iter__().__class__.__name__[_____:________]
    )(
        _, (lambda _, __, ___: _(_, __, ___))(
            lambda _, __, ___:
                chr(___ % __) + _(_, __, ___ // __) if ___ else
                (lambda: _).func_code.co_lnotab,
            _ << ________,
            (((_____ << ____) + _) << ((___ << _____) - ___)) + (((((___ << __)
            - _) << ___) + _) << ((_____ << ____) + (_ << _))) + (((_______ <<
            __) - _) << (((((_ << ___) + _)) << ___) + (_ << _))) + (((_______
            << ___) + _) << ((_ << ______) + _)) + (((_______ << ____) - _) <<
            ((_______ << ___))) + (((_ << ____) - _) << ((((___ << __) + _) <<
            __) - _)) - (_______ << ((((___ << __) - _) << __) + _)) + (_______
            << (((((_ << ___) + _)) << __))) - ((((((_ << ___) + _)) << __) +
            _) << ((((___ << __) + _) << _))) + (((_______ << __) - _) <<
            (((((_ << ___) + _)) << _))) + (((___ << ___) + _) << ((_____ <<
            _))) + (_____ << ______) + (_ << ___)
        )
    )
)(
    *(lambda _, __, ___: _(_, __, ___))(
        (lambda _, __, ___:
            [__(___[(lambda: _).func_code.co_nlocals])] +
            _(_, __, ___[(lambda _: _).func_code.co_nlocals:]) if ___ else []
        ),
        lambda _: _.func_code.co_argcount,
        (
            lambda _: _,
            lambda _, __: _,
            lambda _, __, ___: _,
            lambda _, __, ___, ____: _,
            lambda _, __, ___, ____, _____: _,
            lambda _, __, ___, ____, _____, ______: _,
            lambda _, __, ___, ____, _____, ______, _______: _,
            lambda _, __, ___, ____, _____, ______, _______, ________: _
        )
    )
)
#

IIRC it was a Hello World or something like that...

#

And here's a nice thing I wrote once to calculate some probability...

#
>>> from functools import lru_cache
>>> f=lru_cache(maxsize=None)(lambda x:1 if x==0 else sum((1-f(i-1))/(2500-i) for i in range(x)))
>>> print(*("{:>4}: {:10.4%}".format(x, f(x)) for x in [1, 10, 100, 200, 500, 1000, 1500, 2000, 2500]), sep="\n")
   1:    0.0400%
  10:    0.3602%
 100:    3.9631%
 200:    7.9663%
 500:   19.9759%
1000:   39.9920%
1500:   60.0080%
2000:   80.0240%
2500:  100.0400%
#

Guess what? I accidentally rewrote an approximation for x/2500 ๐Ÿ˜›

brisk zenith
#

oh fancy :D

#

i love that top one

#

bytecode mods and what i'll now refer to as "lambdascores"

tropic gulch
#

If I may interject for a moment, what you're referring to here as lambdascores are actually underscore lambdas, or as I've recently taken to calling it, underscores plus lambdas.

#

๐Ÿ˜‰

brisk zenith
#

haha good one

tropic gulch
#

ยฏ_(ใƒ„)_/ยฏ

novel vine
#

AttributeError: 'function' object has no attribute 'func_code'

Process finished with exit code 1

#

@tropic gulch lambda machine broke

wind maple
#

python2 code

#

replace func_code with __code__ and it should work

brisk zenith
#

^

#

sorry, this*

wind maple
#

Here's the blogpost by the author

#

It's pretty simple in reality

#

it just looks super confusing

brisk zenith
#

yeah, i've done something like it before

#

i wonder if it's possible to fuck up python so badly that pointers are possible

novel vine
#

AttributeError: module 'os' has no attribute 'wr_it'

#

weird must've missed something with find and replace worked now

tight hemlock
#

I am very much enjoying this channel. Code folding was something I wasnt aware python did. Also compilation units are neat to think about

#

@novel vine C++ is AoT compiled so metaprogramming has the advantage of making cost-free abstractions at compile time and shipping expanded code to everyone else. Metaprogramming in Python wouldnt be useful because python is compiled and immediately run so metaprogramming has no advantage at all

#

everyone has to compile things anyway

novel vine
#

yes but can it be done

tight hemlock
#

metaprogramming? yes. anything significant compile time? not that i know of

#

well

#

idk how metaclasses are implemented

#

so you'll have to check that

brisk zenith
#

i don't do this stuff because it's useful, it's just fun :D

broken agate
#

what's the biggest golf ever performed ๐Ÿค”

brisk zenith
#

define 'biggest'

broken agate
#

longest

fast torrent
#

What is code golf?

brisk zenith
#

writing your code to be compact

#

fewest bytes as possible

fast torrent
#

So like a fizzbuzz code.

brisk zenith
#

f=lambda n:all(n%q for q in range(2,n)) <- prime testing function

fast torrent
#

@brisk zenith that makes primes? Cool!

#

Never understood lamdas use case....

brisk zenith
#

it doesn't make primes, it tests if a number is prime

#

i.e f(7) would return True

fast torrent
#

Ok

#

Makes sense

tight hemlock
#

[*filter(lambda n:all(n%q for q in range(2,n)),range(x))]

#

this one makes primes^

brisk zenith
#

not a function though :D

tight hemlock
#

f = lambda x: [*filter(lambda n:all(n%q for q in range(2,n)),range(x))]

brisk zenith
#

68 bytes

#

not bad

tight hemlock
#

if you dont mind returning an iterator instead of a list (which is perfectly fine) its 65

brisk zenith
#

def f(n):r=range(2,n);return{*r}-{b*x for b in r for x in r} was Someone's best (60)

tight hemlock
#

oh i forgot lambdas actually longer isnt it

brisk zenith
#

depends

#

on def you need a return

#

lambdas implicitly return

tight hemlock
#

ah right fair enough

brisk zenith
#

f=lambda n:[p for p in range(2,n)if all(p%q for q in range(2,p))] was my best (65)

tight hemlock
#

wait

brisk zenith
#

0 and 1 are not prime :(

tight hemlock
#

dumb

#

petition to change 0 and 1 to primes

brisk zenith
#

lmao

buoyant agate
#
def f(x):return x
f=lambda x:x```
viral hedge
#
f=lambda n:[2,3,5,7,11][n]``` Totally works for all primes, but don't test it past first 5 ![Kappa](https://cdn.discordapp.com/emojis/307260877730480128.webp?size=128 "Kappa")
brisk zenith
#

lmao

buoyant agate
#

I guess you have to use a function because of r=range(2,n)

brisk zenith
#

yup

#

(lambdas are functions too >.>)

buoyant agate
#

Yea, but you can't define variables in it

brisk zenith
#

still a function, just only allows a single statement

#

i really really want a way to modify python's AST at compile-time, honestly

buoyant agate
#

To do what?

brisk zenith
#

to fuck with stuff :D

#

one idea is making
strjoin = ฮป *args: "".join(args) valid syntax for lambda functions

dense spire
#

haha

brisk zenith
#

hmmm

#

oooh i have an interesting idea

#
ฮป (num_one, num_two) <- num_one + num_two

# as an alternative to:

lambda num_one, num_two: num_one + num_two```i could make this work
north drum
vague gust
#

you just want the lambda symbol don't you

brisk zenith
#

YES

#

lemme see what i can do

sick hound
#
code = code.replace('ฮป', 'lambda')```
#

@brisk zenith

brisk zenith
#

lmao, not quite

vague gust
#
lambdef: 'lambda' [varargslist] ':' test
lambdef_nocond: 'lambda' [varargslist] ':' test_nocond

#

change these lines in Grammar/Grammar

sick hound
#

@brisk zenith ```py
import inspect

def ฮป(func):
lines = inspect.getsource(func).replace('ฮป', 'lambda').splitlines()
code = lines[1] + '\n' + '\n'.join(lines[3:-1])
print(code)
exec(code)
return eval(func.name)

@ฮป
def test():
'''
return ฮป x: x + 1
'''```

brisk zenith
#

ew

#

also @vague gust i know it's that easy, but i want to make a module out of it :D

vague gust
#

k e k

brisk zenith
#

but if there was a way to modify the AST before code is executed, that would be interesting too

calm rampart
#

@brisk zenith make an import loader that reads the file, compiles to AST, calls your hook, then compiles the rest of the way

brisk zenith
#

hmm

snow nebula
#

you'd have to parse yourself, with your own rules and then translate your ast to the python ast

calm rampart
#

well, not necessarily, if your input language is syntactically valid python

viral hedge
#
myfile = open("somedoc.txt", "r")
fileiterator = myfile.__iter__()

while 1:
    savefile = open("savehere.txt", "a")
    try:
        value = fileiterator.__next__()
    except:
        print("oopsie / done")
        break
    else:
        if value:
            if not value[0] == "#":
                savefile.write(value)
    finally:
        savefile.close()
myfile.close()``` ![GWslippyPeepoL](https://cdn.discordapp.com/emojis/407618465508098049.webp?size=128 "GWslippyPeepoL")
wind maple
#

This is a for loop

sick hound
#

Does weird regex count

#

I have (?<=")/[^"j]+\d(?=")

#

more 'not python' than 'barely python' id say

last bramble
#

there is a regex module in python

#

and it should be the go-to for any string parsing

tropic gulch
#

That regex is far from being weird

sick hound
#

^ that as well, it's straightforward enough -- weird regex would have lookarounds in the middle of it and backreferences and conditionals out the ears and maybe recursion and who knows what else

#

magikarp, regex still isn't python lol

fast torrent
#

0 and 1 are perfect primes ecks dee

warm shell
#

R ther code blocks on discord mobile

#

???

novel vine
#

not on iOS probably on Android

sick hound
#

I mean there are codeblocks, just no highlighting -- on both, I assume

novel vine
#

ios quotes aren't supported to make codeblocks

#

โ€˜โ€™โ€™ see โ€˜โ€™โ€™

tight hemlock
#

You're not using the right symbol

#

You're trying to use smart quotations instead of backticks

novel vine
#

test

#

Oh. So I was. Lol

brisk zenith
#

TIL lambdas use the same cpython opcodes as literals

brisk zenith
#

hey @sick hound you seem to know bytecode stuff, c'mere :P

sick hound
#

Hi

brisk zenith
#
ฮป (num_one, num_two) <- (-num_one + num_two) / 2 + -num_two

so i'm working on making this stuff actually valid code, and i know exactly how to do it except one thing. obviously i need to separate the bytecode that is the (-num_one + num_two) / 2 + -num_two section (the lambda content), but i can't seem to find a consistent way to identify which UNARY_NEGATIVE is referring to the one at <- the above line produces the following bytecode:

 82           0 LOAD_GLOBAL              0 (ฮป)
              2 LOAD_GLOBAL              1 (num_one)
              4 LOAD_GLOBAL              2 (num_two)
              6 CALL_FUNCTION            2
              8 LOAD_GLOBAL              1 (num_one)
             10 UNARY_NEGATIVE
             12 LOAD_GLOBAL              2 (num_two)
             14 BINARY_ADD
             16 UNARY_NEGATIVE                      <- in this case, it is here
             18 LOAD_CONST               1 (2)
             20 BINARY_TRUE_DIVIDE
             22 LOAD_GLOBAL              2 (num_two)
             24 UNARY_NEGATIVE
             26 BINARY_ADD
             28 COMPARE_OP               0 (<)
             30 STORE_FAST               0 (a)

though i just realised it would be way easier to force the programmer to put parentheses around the statement (so it would become ฮป (num_one, num_two) <- ((-num_one + num_two) / 2 + -num_two) in this case)

sick hound
#

Uhh... That's not going to be easy

brisk zenith
#

haha

#

go figure

#

i feel like forced paretheses is the best option

sick hound
#

That probably is the best option

brisk zenith
#

yeah okay, i'll see what i can do ^-^

#

right, got it planned out

sick hound
#

With parenthesis it will be easy because the UNARY_NEGATIVE in the <- will be immediately before the COMPARE_OP

brisk zenith
#

yup

#

so i'd just need to look for

UNARY_NEGATIVE
COMPARE_OP
POP_TOP```
*or* if it's assigned to a variable,

UNARY_NEGATIVE
COMPARE_OP
STORE_FAST```

#

easy enough ^-^

sick hound
#

...What if you're passing it to a function

brisk zenith
#

let's see

sick hound
#
>>> dis.dis('foo(ฮป (num_one, num_two) <- ((-num_one + num_two) / 2 + -num_two))')
  1           0 LOAD_NAME                0 (foo)
              2 LOAD_NAME                1 (ฮป)
              4 LOAD_NAME                2 (num_one)
              6 LOAD_NAME                3 (num_two)
              8 CALL_FUNCTION            2
             10 LOAD_NAME                2 (num_one)
             12 UNARY_NEGATIVE
             14 LOAD_NAME                3 (num_two)
             16 BINARY_ADD
             18 LOAD_CONST               0 (2)
             20 BINARY_TRUE_DIVIDE
             22 LOAD_NAME                3 (num_two)
             24 UNARY_NEGATIVE
             26 BINARY_ADD
             28 UNARY_NEGATIVE
             30 COMPARE_OP               0 (<)
             32 CALL_FUNCTION            1 # not POP_TOP or STORE_FAST!
             34 RETURN_VALUE```
brisk zenith
#

so then look for CALL_FUNCTION :P

#

it'll either end with POP_TOP, STORE_FAST or CALL_FUNCTION

#

so we can check for any of those

sick hound
#
>>> dis.dis('foo(ฮป (num_one, num_two) <- (num_one if lol(num_one < -num_two) else num_two))')
  1           0 LOAD_NAME                0 (foo)
              2 LOAD_NAME                1 (ฮป)
              4 LOAD_NAME                2 (num_one)
              6 LOAD_NAME                3 (num_two)
              8 CALL_FUNCTION            2
             10 LOAD_NAME                4 (lol)
             12 LOAD_NAME                2 (num_one)
             14 LOAD_NAME                3 (num_two)
             16 UNARY_NEGATIVE
             18 COMPARE_OP               0 (<)
             20 CALL_FUNCTION            1 # Oh no
             22 POP_JUMP_IF_FALSE       28
             24 LOAD_NAME                2 (num_one)
             26 JUMP_FORWARD             2 (to 30)
        >>   28 LOAD_NAME                3 (num_two)
        >>   30 UNARY_NEGATIVE
             32 COMPARE_OP               0 (<)
             34 CALL_FUNCTION            1 # This is where the lambda actually ends
             36 RETURN_VALUE```
brisk zenith
#

yeah, we'd still be looking for py UNARY_NEGATIVE COMPARE_OP CALL_FUNCTION

#

it seems like it'll always be py UNARY_NEGATIVE COMPARE_OP (POP_TOP | STORE_FAST | CALL_FUNCTION)

sick hound
#

But what if there's a UNARY_NEGATIVE COMPARE_OP (POP_TOP | STORE_FAST | CALL_FUNCTION) in the lambda

brisk zenith
#

hmm

#

you see, i was thinking we could look for the last occurrence on that line, but then py ฮป (num_one, num_two) <- ( num_one < -num_two )wouldn't be possible

#

any ideas to prevent that?

sick hound
#

...Completely forget about doing this with Python code objects and use inspect.getsource and just do string substitution and then recompile the code instead? That's probably the easiest way

brisk zenith
#

but that's boring :(

sick hound
#

Find the LOAD_GLOBAL ฮป, then iterate through the instructions keeping track of how much the stack has changed since after the function call with the LOAD_GLOBAL ฮป

brisk zenith
#

hmm

sick hound
#

UNARY_NEGATIVE COMPARE_OP (POP_TOP | STORE_FAST | CALL_FUNCTION) is only the end of the function if the stack has changed by exactly 1

brisk zenith
#

hmm

#

does that actually work though?

sick hound
#

It should

brisk zenith
#

it might be hard to keep track of the stack though

#

hmm

#

i have an idea

sick hound
#

how in the hell

#

do i get a webhook in discord to work with monday.com

#

i am so frustrated over this issue

#

i keep on getting error code 400

fast torrent
#

@sick hound what are you trying to do?

#

Can you show us your code and the error?

sick hound
#

there is no code

#

its barely_python

#

im trying to get a webhook to work

#

but it keeps on spitting error code 400

brisk zenith
#

that's better suited for an off-topic channel, because this channel is for things that are python but are almost not

red totem
#

I have this weird problem. It's game-dev related. I have a gaming map serialisation format that goes as follow:

  • 32 bytes of hash
  • deflated json with map data

The hash is a signature of the uncompressed json data to keep integrity.

Now I need to add some additional data into the map, by adding a header of some sort, but to keep it backwards-compatible. How do I do that without having a magic 32 bytes that tells deserialiser 'hey this is not a real hash, the header including actual hash follows'?

slim pecan
#

This is a channel for, eg, code golf

#

It sounds like you want one of the help channels

#

unless you're not working in python at all

red totem
#

those are python related, this one is bare algorithm problem

slim pecan
#

Okay, but this still isn't a help channel

#

You'll have better luck in a help channel

red totem
#

k, what this channel is for then?

slim pecan
red totem
#

I've read this, I meant what besides solving problems can be discussed here?

slim pecan
#

We put it way down here in the special section so it wasn't like, front and centre of our experience

#

Well, it's just a discussion channel, so everything related to that I guess

#

But since it's so specific and covers divisive topics, you won't find most of our users in here

#

that's why you want a help channel

red totem
#

k

runic barn
#

hey guys

#

can someone tell me how to transfer files to a vps in windows

#

like can i just plug in an external drive

sick hound
#

wouldnt you just use winscp or filezilla or something

runic barn
#

yeah but i would really just rather use hard drive

#

is there some way to just let it connect

#

i thought i did it a year ago

#

WAIT

#

is a remote desktop connection different than a VPS?? @sick hound

sick hound
#

yeah kinda

runic barn
#

ohhh i'm an idiot

#

thanks dude

#

you connect to the vps through rdc

#

and then i can transfer files through rdc right??

sick hound
#

maybe

runic barn
#

ohhh

#

i was using vps on a chrome tab

#

cause Vultr gave me that

#

you know what i mean

vague gust
#

@runic barn Please add a nickname which complies with our nickname policy

#

Your current one includes noisy unicode characters, removing those symbols from the end of your nickname will do

runic barn
#

okay

#

sorry

#

fixed

vague gust
#

No problem, thank you!

brisk zenith
#

it seems like people are mistaking "barely-python" to "not-python", and that's not a good

calm rampart
#

for the scary side of python ๐Ÿ˜›

brisk zenith
#

haha

urban zenith
#

It should be renamed #vscode-vs-pycharm

calm rampart
#

the idea being that most anything you would discuss in here would be horrifying to find in a production program

novel vine
#

why not just generic code-gore

brisk zenith
#

because then stuff like Hy and ClojurePy wouldn't fit so much into it

#

perhaps python-gore though

#

(code-gore also suggests other language-gore is allowed)

runic barn
#

hey @sick hound

#

so i set up a RDP

#

i'm transfering like 600 mb across to a vps

#

in japan

#

and estimated time is like over an hour

#

is that normal

unique shoal
#

(take it to off topic y'all)

sick hound
#

yeah you should ask that question in one of the offtopic channels maybe

#

but probably?

brisk zenith
brisk zenith
#

does anyone have any knowledge about the cpython implementation? haha i'm just pissing around

brisk zenith
#

actually never mind i figured it out :D

#
>>> juan
<built-in function juan>
>>> print(juan.__doc__)
Return the base-juan representation of an integer.

   >>> juan(7)
   '0j1111111'
>>> juan(69)
'0j111111111111111111111111111111111111111111111111111111111111111111111'
>>> 
brisk zenith
#
>>> hex(12)
'0xc'
>>> bin(12)
'0b1100'
>>> juan(12)
'0j111111111111'
>>> juan(-3)
'-0j111'
>>> 
#

my own builtin function :^)

#

only had to modify 3 files though

jade dust
#

cool

#

Did you write it in C, or python?

sick hound
#

If it's builtin then it's written in C

#

If it was in python then it would be <function juan at 0xsomewhere>, not <built-in function juan>

misty trellis
#

This is cool

tropic gulch
#

It's called base 1 though. Not base Juan, even if you named it like that ๐Ÿ˜›

wind maple
#

Woosh

tropic gulch
#

Btw, you can test whether a number in base 1 representation is a prime number using regular expressions...

brisk zenith
#

although wouldn't it actually be 0s instead of 1s? that makes it so much easier, ill change it when i get home

#

uhh hey @vague gust look up i did a thing

cunning wave
#

@brisk zenith I got a thing you can do, build built-in s for common encryptions using the Linux kernel level crypto API

brisk zenith
#

hmm

#

id prefer to make a module out of it because built-in python features are supposed to be cross-platform

wind maple
#

it can be any character it doesn't matter

#

Also I'd still do

#

0 1 11 111 1111

brisk zenith
#

yeah, fair

#

because 0000 indicates that it's 0

sick hound
#

how knows some good code golfing sites for python

sick hound
#
def __repr__(self):
    return '<built-in function juan>'

@sick hound pypeek

brisk zenith
#

haha

novel vine
#

lul

sick hound
#

Wait... oh

brisk zenith
#

do you doubt my built-inness?

novel vine
#

Yes

sick hound
#

i believe it

jade dust
#

source or it didn't happen

sick hound
#

you need to start making PRs to get juan highlighted in the big editors though

novel vine
#

PR to give bool a 3rd state

#

True False Juan

jade dust
#
def __eq__(self, other):
    return random.choice([True, False])
jade dust
#

haha I have no idea what it does

#

idk C.

#

It's cool that you were able to do that

sick hound
#

Wow

brisk zenith
#

idk C either, i just know a bit of C++ and became a neanderthal while i coded it

calm rampart
#
negative = PyLong_AsSsize_t(a) < 0;``` - wait, these functions are limited to C integer range?
brisk zenith
#

i changed that

#

cause the previous one didn't work with a bit size of 0

#

but i should probably change it back and make a special case

sick hound
#
>>> bin(9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999)
'0b100101101001111010110111110001000111100001011001111001110100001110011111011001000100101011100101101001001011000110110011001001010110010111110110110110111010111001110111101110010001011011011000111010010101111111010101100000101011101010110111011101001001100011010101100011001101101101110010101100011000111110000101010101001111101011010011000011100101011000001111000010000000100011000111001111100111000101111010110000001011001000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111'```
brisk zenith
#

interesting

calm rampart
#

oh nevermind

#

it stores the sign bit with the length, apparently.

sick hound
#

@tropic gulch btw say "one" and "juan" out loud together

tropic gulch
tropic gulch
#

exit(1)

#

ยฏ_(ใƒ„)_/ยฏ

#

0 is okay, everything else is bad.

#

which bad is up to the application

#

I don't think there are any "standard" codes common to many applications

snow nebula
#

posix has some standardised exit codes

tropic gulch
#

but that applies only to Bash

#

other answers further down seem to confirm that there is no "global" standard meaning

viral hedge
wind maple
#

Good talk

#

Also none of this is barely-python

#

except maybe the async init metaclass

viral hedge
#

Not even he frame hacking and that^?

wind maple
#

I mean

#

Maybe when you see it for the first time?

viral hedge
#

Guess I truly only know half of python then.

wind maple
#

It's useful though

sick hound
#

list(map(list, set(map(tuple, it))))

#

found this ๐Ÿค”

brisk zenith
#

oh dear

calm rampart
#

[[*x] for x in {(*y,) for y in it}]

brisk zenith
#

ouch :D

sick hound
#

it ?

viral hedge
#

Referring to what wright found

sick hound
#

it = iterable probably

crisp pendant
#
with open('settings.json') as f:
    vals = json.load(f)
settings = lambda: ...
settings.__dict__.update(**vals)
slim pecan
#

oof, monkey-patching the Ellipsis singleton

#

wait no, the lambda

crisp pendant
#

Since pass doesn't work xD

calm rampart
#

just use None

sick hound
#

pass is a statement

slim pecan
#

surely you could just have used object() or type() :P

calm rampart
#

lambda: None

#

that's the same as def f(): pass

crisp pendant
#

That's true

#

I think object or type would have been the best, but then I couldn't post it here

calm rampart
#

def settings(): pass

#

I think there's a pep 8 about never assigning a lambda to a variable

crisp pendant
#

Oh really?

calm rampart
#

because you should be using def instead

crisp pendant
#

that's interesting

calm rampart
#

yep "Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier."

sick hound
#
Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier.

Yes:

def f(x): return 2*x
No:

f = lambda x: 2*x```
crisp pendant
#

I just didn't want to use the [] because my fingers were tired

#

Good to know. I don't do it often, but I have done it.

#

I.E just now

arctic bridge
#

Midnight takes your heart and your soul
While your heart is as high as your soul
Put your heart without your soul into your heart

Give back your heart


Desire is a lovestruck ladykiller
My world is nothing 
Fire is ice
Hate is water
Until my world is Desire,
Build my world up
If Midnight taking my world, Fire is nothing and Midnight taking my world, Hate is nothing
Shout "FizzBuzz!"
Take it to the top

If Midnight taking my world, Fire is nothing
Shout "Fizz!"
Take it to the top

If Midnight taking my world, Hate is nothing
Say "Buzz!"
Take it to the top

Whisper my world
plain pawn
#

sweet, someone finally implemented it

crisp pendant
#
from functools import reduce
dict1 = {1: (1, 2), 2: (3, 4, 5)}
dict2 = {2: (6, 7), 3: (8, 9)}

y = reduce(lambda x, y: {**x, **y},
    map(
      lambda k:{k:
        dict1.get((k), ()) + dict2.get((k), ())
      },
      {**dict1, **dict2}
      )
)

print(y)

Posting this here too because I wasted way too much time on this

sick hound
#

What does that even do

wind maple
#

merge the dictionaries

crisp pendant
#

The values to be specific

wind maple
#

non-destructive merge

crisp pendant
#

Look in help channel 5

sick hound
#
y = dict((k, dict1.get(k, ()) + dict2.get(k, ())) for k in {**dict1, **dict2})```
wind maple
#

That's a destructive merge

#

isn't it

sick hound
#

no

#

it's the same thing

wind maple
#

oh I

#

smh dict1.keys() | dict2.keys()

crisp pendant
#
y = {key: dict1.get(key, ()) + dict2.get(key, ()) for key in {**dict1, **dict2}}
#

I did that earlier in the chat

#

I just wanted to see how over the top I could make it while staying on one line and not being redundant

sick hound
#
(lambda types:types.FunctionType(types.CodeType(0, 0, 0, 3, 64, b'd\x00d\x01\x84\x00e\x00j\x01\x83\x00e\x02j\x01\x83\x00B\x00D\x00\x83\x01S\x00', (types.CodeType(1, 0, 2, 6, 67, b'i\x00|\x00]\x1e}\x01t\x00j\x01|\x01f\x00\x83\x02t\x02j\x01|\x01f\x00\x83\x02\x17\x00|\x01\x93\x02q\x04S\x00', (), ('dict1', 'get', 'dict2'), ('.0', 'k'), '', '', 1, b'\x06\x00'), ''), ('dict1', 'keys', 'dict2'), (), '', '', 1, b''),{**globals(),**locals()})())(__import__('types'))```
#

@crisp pendant

crisp pendant
#

rediculous

novel vine
#

Thatโ€™s beautiful

#

@brisk zenith quality code honestly

brisk zenith
#

ooh lemme decode this

#

yes i understand it

#

interesting code right there pastebean

brisk zenith
#
    moves = [
        (
            lambda x_offset, y_offset: (
                lambda x, y: (x + x_offset, y + y_offset)
            )
        ).__call__(x_offset, y_offset)
        for x_offset in (-1, 0, 1)
        for y_offset in (-1, 0, 1)
        if (x_offset or y_offset)
    ]

fun :D

#

this generates a list of lambdas which can each be called to return a unique point around a given (x, y) coordinate

#

giving (10, 10) to each of these lambdas will return:

(9, 9)
(9, 11)
(10, 9)
(10, 10)
(10, 11)
(11, 9)
(11, 11)
#

except (10, 10) shouldn't be there

#

hmm

#

edited, now it gives the expected result: py (9, 9) (9, 10) (9, 11) (10, 9) (10, 11) (11, 9) (11, 10) (11, 11)

whole kiln
#

I'm thinking of another term for clearing a bit i.e. setting it to 0. Can anyone remind me? All I remember is that it was a bit unintuitive of a word because outside of programming, it had a different but related meaning

calm rampart
#

@whole kiln I've sometimes seen "reset" used for it

whole kiln
#

Thanks, but I'm sure that's not what I was thinking of

#

going to try to look in the assembly book I read it in

#

god knows which chapter its in

#

I was thinking of assert

#

and it means the opposite

#

setting the value to one

sick hound
#

what means the opposite?

whole kiln
#

Initially I thought the word I was thinking of meant to set something to 0

#

But I found that I was thinking of 'assert', and it means setting something to 1

sick hound
#

ah i see, but i can't say I've heard that meaning of assert myself

whole kiln
#

Yeah, I was confused at first too

#

From the book:

#
As a rule, computers read memory much more slowly than they access internal registers. This is
because reading a single value from memory involves four separate steps:
1. Place the address of the value you want to read on the address bus.
2. Assert (change the value of) the processorโ€™s RD
 (read)
 pin.
3. Wait one clock cycle for the memory chips to respond.
4. Copy the data from the data bus into the destination operand.```
sick hound
#

oh i see, interesting

whole kiln
#

When I think of assert, I think of test cases

#

the definition doesn't line up with that

#

Cause for test cases it's a check rather than changing any value

sick hound
#

yeah when i was trying z80 asm (for my calculators lol) i remember the terms "set" and "reset" being used, nothing else

#

oh no but we've fallen into the "not python" trap

sick hound
#

base one is so epic

brisk zenith
#
def likes(names):
    return {
        len(names) == 0: "no one likes this",
        len(names) == 1: "%s likes this",
        len(names) == 2: "%s and %s like this",
        len(names) >= 3: "%s, %s and %s like this"
    }[True] % tuple(
        names if len(names) <= 3
        else names[:2] + ["%d others" % (len(names) - 2)]
    )

codewars? more like codegores :^)
(i was forced to use 2.7 for this, that's the real code gore haha)

whole kiln
#

what in gods name

brisk zenith
whole kiln
#

fortunately/unfortunately I don't think I have any OC code gore ๐Ÿ˜ฆ

#

maybe if I consider my tendency to write one-liners when I was starting out

#

yeah... py return list(map(lambda m: Exchange.Market( m["MarketName"], Exchange.Currency( m["MarketCurrency"], m["MarketCurrencyLong"], None), Exchange.Currency( m["BaseCurrency"], m["BaseCurrencyLong"], None), None), markets))

brisk zenith
#

:D

whole kiln
#

I have a worse one py return next((Exchange.Currency(symbol, name, precision) for symbol, name, precision in g.db.cursor.fetchall() if re.search((name if g.config["search_currency_name"] else "") + r"\s*?[(\[{]+?\s*?" + symbol + r"\s*?[)\]}]", text, re.IGNORECASE)), None)

#

that's it from me

brisk zenith
#

ooh regex gore :^)

viral hedge
#

The only code gore I can give from my early days is code indented 8-10 times

#

:(

whole kiln
#

is that regex gore?

#

if you look at the regex alone

#

yeah i guess it's pretty gorey

dense spire
#

let's face it, all regex is gore

slim pecan
#

How about RFC 822?

dense spire
#

is that the email one

slim pecan
#

yeah

#

too big for discord

dense spire
#

yeah looks great, I would take it on a dinner date we could have sex

#

jk it makes me want to kill people.

slim pecan
#

comment from SO:

The regular expression to validate email addresses (possibly multiple in to:, cc: and bcc: form) (from RFC 822) is pretty beefy; definitely the longest non-trivial regular expression that I have seen. Unfortunately, it seems that there are a lot of sites out there on the internet that do not use this regular expression or an equivalent validation as I have encountered far too many sites that do not accept myemailaddress+yourstupidsite@gmail.com as a valid email address.
dense spire
#

a fair point

#

that should totally be supported

calm rampart
#

the regex to validate a single proper email address is much shorter

#

people latched onto the fact that the grammar element that one validates is called "address" whereas the one normal people think of as an email address is called "addr-spec"

#

just like the HTML tag regex parsing thing, people jumped to do "I don't feel like you should be using a regex for this, so I'll just make up whatever reason why it's 'impossible' without regard to accuracy"

brisk zenith
#

i use regex for parsing html when i'm too lazy to set up a venv/pipenv lmao

calm rampart
#

regex for an addr-spec is only a few hundred characters long.

#

(addr-spec in RFC 822/5322, mailbox in RFC 821/5321)

coral plank
#

anyone know how to get a mongo.py to appear in a terminal window from a tmux

tmux new -s mongod -d "/bin/bash"
tmux new -s mongo -d "/bin/bash"
tmux new -s gui -d "/bin/bash"
tmux new -s controller -d "/bin/bash"
#tmux new -s plot -d "/bin/bash"
#tmux new -s plot2 -d "/bin/bash"
tmux run-shell -t "mongod" "mongod"&
tmux run-shell -t "mongo" "python /home/pi/Desktop/EmbeddedFlaskServer/mongo.py"&
#tmux attach -t mongo
sleep 2

#tmux run-shell -t "plot" "python /home/pi/Desktop/EmbeddedFlaskServer/plotPID.py"&
#tmux run-shell -t "plot2" "python /home/pi/Desktop/EmbeddedFlaskServer/plotPID2.py"&
tmux run-shell -t "controller" "python /home/pi/Desktop/EmbeddedFlaskServer/controller.py"&
tmux run-shell -t "gui" "python /home/pi/Desktop/EmbeddedFlaskServer/gui.py"
tmux run-shell -t "gui" "python /home/pi/Desktop/EmbeddedFlaskServer/stop.py"
pkill -f controller.py
pkill -f mongo.py
mongod --shutdown
tmux kill-server```
mongo runs but doesnt appear when you attach to the mongo window
and doesnt show in jobs or bg
sick hound
#

ask in a help channel, @coral plank

#

or in one of the general-programming servers actually

coral plank
#

was told its not directly python related

sick hound
#

this channel's for sharing bad python

#

as above

coral plank
#

oh lol

#

which channel should i ask or maybe a server recommendation but the programming discord is useless

viral hedge
#

Probably off topic channels?

crisp pendant
#
print(f"That's {input('How are you?: ')}" if not print(f'Hello, {input("What is your name?: ")}') else "")
jade dust
#

Change any python code into one line by abusing lambdas

brisk zenith
#

ooh yeah i saw that once, really interesting. i don't think it can handle async yet though

blazing basin
#

writing those single-line python apps manually is a lot of fun

#

it's like writing functionally

brave bison
#

(lambda __g: [None for __g['f'], f.name in [(lambda x: (lambda __l: [(__l['x'] * 4) for __l['x'] in [(x)]][0])({}), 'f')]][0])(globals())

strange flame
#

hi

#

i have a question a bit unrelated to python

#

if someone could answer me please

novel vine
misty trellis
#

I just use
\w@\w.\w

#

Is that that bad

tropic gulch
#

it doesn't cover - at least, so yeah, it will fail on many common addresses. also . is any character in regex, unless escaped

calm rampart
#

i wrote a program to generate the proper regex for validating an email addr-spec

#
atext = '[-0-9A-Z!#-\'*+/=?^-~]' # Lowercase included in ^-~
atom = atext + '+'
dot_atom = atom + '(?:\\.' + atom + ')*'
# RFC 822 allowed quoted-strings in place of atoms
qtext = '[] !#-[^-~]'
qpair = '\\\\[ -~]'
qcontent = '(?:' + qtext + '|' + qpair + ')'
quoted_string = '"' + qcontent + '*"'
# RFC 5321 and 5322 differ on the semantics of whitespace within quoted-strings
let_dig = '[0-9A-Za-z]'
ldh_str = '[-0-9A-Za-z]*' + let_dig
subdomain = let_dig + '(?:' + ldh_str + ')?'
dot_domain = subdomain + '(?:\.' + subdomain + ')*'
# dot_domain = dot_atom in RFC 5322
dtext = '[]!#-[^-~]'
domain_literal = '\\[[^' + dtext + '*\\]'
# RFC 5321 requires valid IP address here
local_part = '(' + dot_atom + '|' + quoted_string + ')'
domain = '(' + dot_domain + '|' + domain_literal + ')'
addr_spec = local_part + '@' + domain

# (
#  [-0-9A-Z!#-'*+/=?^-~]+(?:\.[-0-9A-Z!#-'*+/=?^-~]+)*
# |
#  "(?:[] !#-[^-~]|\\[ -~])*"
# )@(
#  [0-9A-Za-z](?:[-0-9A-Za-z]*[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:[-0-9A-Za-z]*[0-9A-Za-z])?)*
# |
#  \[[^[]!#-[^-~]*\]
# )
# Total 188 characters```
whole kiln
#

some regex gore/porn

#
private static readonly Regex _Regex = new Regex(
            @"(?:{field}(?<fname>.*?)\{\}(?<fvalue>.*?)(?:\{\}(?<finline>.*?))?(?=$|{(?:field|author name|author icon|author url|thumbnail|title|url|color|description|image|footer text|footer icon|submit)}))|{(?<action>author name|author icon|author url|thumbnail|title|url|color|description|image|footer text|footer icon|submit)}(?<value>.*?)(?=$|{(?:field|author name|author icon|author url|thumbnail|title|url|color|description|image|footer text|footer icon|submit)})",
RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);```
brisk zenith
#

not even python ๐Ÿ‘€ :D

buoyant agate
#

Is that for an embed?

whole kiln
#

yeah

#

was originally implemented with pretty ugly code

#

i did my best at the time to improve it

misty trellis
#

It's so barely python it's not even written in python

whole kiln
#

just remove the top and bottom and no one will know the difference ๐Ÿ˜‰

sick hound
#

@brave bison py os = __builtins__.__getattribute__('__import__').__call__('os') i = ("this is even more descriptive",).__getattribute__('__iter__').__call__() s = '' while True: try: s = s.__getattribute__('__add__').__call__(i.__getattribute__('__next__').__call__().__getattribute__('__str__').__call__()) s = s.__getattribute__('__add__').__call__(' ') except __builtins__.__getattribute__('StopIteration'): break s += '\n' os.__getattribute__('write').__call__(1, s.encode())

brave bison
#

thats not what i wrote

sick hound
#

i know

#

it's what I wrote

brave bison
#

mine was 1 line

sick hound
#

that code is not yours

#

that code is mine

#

and I wrote it

#

you did not write it

#

you are not me

brave bison
#

ill make it more barely python

#

(lambda __operator, __g, __contextlib, __y: [[[(lambda __after: __y(lambda __this: lambda: (lambda __break: (lambda __out: (lambda __ctx: [__ctx.__enter__(), __ctx.__exit__(None, None, None), __out[0](lambda: __this())][2])(__contextlib.nested(type('except', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: __exctype is not None and (issubclass(__exctype, __builtins__.__getattribute__('StopIteration')) and [True for __out[0] in [(__break())]][0])})(), type('try', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: [False for __out[0] in [([[(lambda __after: __after()) for __g['s'] in [(s.__getattribute__('__add__').__call__(' '))]][0] for __g['s'] in [(s.__getattribute__('__add__').__call__(i.__getattribute__('__next__').__call__().__getattribute__('__str__').__call__()))]][0])]][0]})())))([None]))(__after) if True else __after())())(lambda: [(os.__getattribute__('write').__call__(1, s.encode()), None)[1] for __g['s'] in [(__operator.iadd(__g['s'], '\n'))]][0]) for __g['s'] in [('')]][0] for __g['i'] in [(('this is even more descriptive',).__getattribute__('__iter__').__call__())]][0] for __g['os'] in [(__builtins__.__getattribute__('__import__').__call__('os'))]][0])(__import__('operator', level=0), globals(), __import__('contextlib', level=0), (lambda f: (lambda x: x(x))(lambda y: f(lambda: y(y)()))))

#

its a one liner now

sick hound
#

how did you do that?

brave bison
#

with this one liner that converts a script into a 1 liner

#

oh too big for discord

#

this is the true power of python

sick hound
#
(lambda f:f(f))(lambda y:lambda f:lambda:f(y(y)(f)))(lambda f:lambda n:f()(n-1)*n if n else 1)()```
#

This is factorial

charred steeple
viral hedge
#

i like the testimonials

charred steeple
#

probably the only good bit

tropic gulch
#

o_O

#

it supports cout << "Hello, C++!" << endl;

cunning wave
#

juan supports that too

tropic gulch
#

@brisk zenith someone was faster than you ๐Ÿ‘†

cunning wave
#

oof

whole kiln
#

but does it support it with std:: ?

sick hound
#

Nope, there's actually an open issue asking for that

#

I don't see how it'd work bc syntax error

brisk zenith
#

yup

whole kiln
#

rip my hopes and dreams

sick hound
#

well

#

technically you could do stdหห

#

which is a cheaty ห

next linden
#

thought i should ask a question here about the julia language

#

anybody know if it's worth learning or worth my time

#

apparently it's easy like python but fast like C

sick hound
#

this channel is for sharing bad python code

wind maple
#

I guess yes

whole kiln
#

it's not limited to that

unique shoal
#

it's definitely not about Julia

#

other languages go to off topic y'all

next linden
#

where is off topic

#

@unique shoal

next linden
#

ok thanks

sick hound
#

np

tight hemlock
#

@next linden it's a maths language essentially

#

Meant as a glorified matrix calculator

next linden
#

@tight hemlock does it make web apps easier to make?

unique shoal
#

oi, off-topic

wooden mirage
#

hey, i'm trying to convert binary to text. i've got def binary(text): ''.join(format(ord(i), 'b') for i in text) to convert it to binary but i do not have an idea how to reverse this process. the SO has answers including very long solutions using other modules etc. someone able to write a short converter?

wind maple
#

No way to reverse it unless you pad them

#

And then split the binary into chunks

#

and decode those

#

Though idk why you're in this channel

tropic gulch
#

๐Ÿ˜ฎ

#

I didn't know format was a builtin

wooden mirage
tropic gulch
#

But yeah, your formatting there is irreversible because the binary representations of each character in text can have variable length and boundaries are not detectable.

wooden mirage
#

oh ok ;')

regal olive
#

!kick vortex962

slim pecan
#

Need a hand?

sick hound
#
while int('%(foo)s' % {'foo': 2}) + int('%(bar)s' % {'bar': 2}) == int('%(foo)s' % {'foo': 2}) * int('%(bar)s' % {'bar': 2}):
    print("".join([chr(i) for i in [int('%(foo)s' % {'foo': 9}) * int('%(bar)s' % {'bar': 8}),int('%(foo)s' % {'foo': 10}) * int('%(bar)s' % {'bar': 10}) + int('%(foo)s' % {'foo': 1}),int('%(foo)s' % {'foo': 9}) * int('%(bar)s' % {'bar': 12}),int('%(foo)s' % {'foo': 9}) * int('%(bar)s' % {'bar': 12}), int('%(foo)s' % {'foo': 11}) * int('%(bar)s' % {'bar': 10}) + int('%(foo)s' % {'foo': 1}), int('%(foo)s' % {'foo': 8}) * int('%(bar)s' % {'bar': 4}),int('%(foo)s' % {'foo': 11}) * int('%(bar)s' % {'bar': 8}) - int('%(foo)s' % {'foo': 1}),int('%(foo)s' % {'foo': 11}) * int('%(bar)s' % {'bar': 10}) + int('%(foo)s' % {'foo': 1}),int('%(foo)s' % {'foo': 11}) * int('%(bar)s' % {'bar': 10}) + int('%(foo)s' % {'foo': 4}),int('%(foo)s' % {'foo': 9}) * int('%(bar)s' % {'bar': 12}),int('%(foo)s' % {'foo': 10}) * int('%(bar)s' % {'bar': 10}),int('%(foo)s' % {'foo': 8}) * int('%(bar)s' % {'bar': 4}) + int('%(foo)s' % {'foo': 1}),] ]))
    break
sick hound
#

which can be easily made even worse

novel vine
#
bytes([(True << (True ^ True << True) ^ True << (True << True ^ True << (True << True))), (True ^ True << (True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << (True << True) ^ True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << (True << True) ^ True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True ^ True << True ^ True << (True << True) ^ True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << (True << True) ^ True << (True ^ True << True) ^ True << (True ^ True << (True << True))), (True << (True ^ True << (True << True))), (True ^ True << True ^ True << (True << True) ^ True << (True << (True << True)) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True ^ True << True ^ True << (True << True) ^ True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << True ^ True << (True << (True << True)) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << (True << True) ^ True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << (True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True ^ True << (True ^ True << (True << True)))]).decode()
whole kiln
#

neat

novel vine
#

(shamelessly stolen from @brisk zenith)

brisk zenith
#

haha, that's something i made on my first day on this server. good fun

whole kiln
#

Doing various challenges on hackerrank. Came across a regex one that had me stumped for like 10 min

#

the solution was nested lookaheads

#

I needed to find digits that alternate

#

(?P<d>\d)(?=\d(?=(?P=d)))

tropic gulch
#

huuuuuuuhh?

whole kiln
#

๐Ÿ™ƒ

#

basically check if the digit 2 places past the current digit is the same as the current digit

tropic gulch
#

๐Ÿค”

whole kiln
#

like 515789

#

the 5 would be alternating

tropic gulch
#

I get it

#

just...

#

maybe pure regex isn't the best solution here...

whole kiln
#

?

tropic gulch
#

I mean sure it works, and it's quite elegant once you know what the hell you are doing there, but

#

the wtf is strong in this one

#

ยฏ_(ใƒ„)_/ยฏ

whole kiln
#

it's only that bad cause I am not allowed to modify the code that calls the regex

#

initially I didn't have a nested lookahead

#

I just did (?P<d>\d)\d(?=(?P=d))

#

but re.findall returns non-overlapping matches

#

so I had to make sure only one char was being matched

#

otherwise it would not process every second character