#esoteric-python

1 messages · Page 82 of 1

marsh void
#

I mean, it is cool isn't it? @gilded orchid

gilded orchid
#

yeah it's cool

#

it's just something you'd never see in a million years outside of #esoteric-python

#

I'm kinda curious how the hooking into encoding works

#

does it just give the source code and you can do whatever you want to it before it's ran?

brisk zenith
#

@marsh void how does that work?

marsh void
#

yep.

#

you just need to pip install pyxl or something

brisk zenith
#

okay great but how does that work? :D

marsh void
#

well it hooks custom encoding through site module which is imported on initialization

#
import codecs


def search_function(encoding):
    if encoding != 'pyxl': return None

    import encodings
    from pyxl.codec.transform import pyxl_decode, PyxlIncrementalDecoder, PyxlStreamReader

    # Assume utf8 encoding
    utf8=encodings.search_function('utf8')
    return codecs.CodecInfo(
        name = 'pyxl',
        encode = utf8.encode,
        decode = pyxl_decode,
        incrementalencoder = utf8.incrementalencoder,
        incrementaldecoder = PyxlIncrementalDecoder,
        streamreader = PyxlStreamReader,
        streamwriter = utf8.streamwriter)


codecs.register(search_function)``` here's how pyxl.codec.register looks
#

then, after installing, it writes a pyxl.pth file into python's source with the following content: py import pyxl.codec.register

#

@brisk zenith

#

Yet I smell PEP8 violation here with the keyword argument style haha

#

Wait if I want {}; python I'll have to rewrite the tokenizer right haha

marsh void
#

@gilded orchid hey, sorry for the late response, you can look above and at the source of pyxl_decode function on GitHub for further explanation.

sick hound
#

Also if you dont want to mess with hooking things etc., BRM provides the same functionality with an IMHO better API

marsh void
#

well yeah

#

BRM is neat

marsh void
brazen geyser
#
k = lambda: (
  print('line 1'),
  print('line 2'),
  print('line 3'),
)
#

doesn't have to be a tuple either, you can use parentheses to split just about any expression into multiple lines

#
lambda x, y, z: (
  3*x + 7*y +
  8*z**3
)
#

even strings can be implicitly concatenated across multiple lines

lambda name, age, place: (
  f'Hello, my name is {name}. '
  f'I am {age} years old. '
  f'I am from {place}.'
)
marsh void
#

@brazen geyser what if I want a try/except or some understandable while/for

#

what's that meta anagram thing tho haha

rugged sparrow
#

@marsh void that stuff requires some boilerplate but its still do-able

marsh void
#

nahh

#

I want normal multi line lambdas haha

#

Lambda is by definition a function without a name technically

rugged sparrow
#
_while=lambda f:[*iter(f,())]```
#

runs f until it returns ()

#
_try=lambda t,a=(),k={},f=lambda a:a,e=(Exception,),r={}:r.get('r',type('',(__import__('contextlib').ContextDecorator,),{'__enter__':r.clear,'__exit__':lambda s,*a:issubclass(a[0]or map,e)and[r.update(r=f(a))]})()(t)(*a,**k))``` my try lambda pattern
marsh void
#

but why

rugged sparrow
#

could use those to have fully functioning mulitline lambdas with all features you want

marsh void
#

I am writing my own python and rust-inspired language btw

#

which translates to python

#
lambda a: int, b: int -> {a + b}``` here's kind of syntax I have in mind
rugged sparrow
#

hmm

#

i wonder if i might be able to get something similar in normal python

#

like lambda a, b:0 > 'code'

marsh void
#

I mean

rugged sparrow
#

or i just hook the compiler using a .pth

marsh void
#
lambda (string: str, x: int) -> {
    string *= x;
    return string;
}``` it's actually this
rugged sparrow
#

ah ok

#

yah know i would like type hints on lambdas

marsh void
#

that's why I am making my thing

#

it's going to be some smart def function when transpiled though

rugged sparrow
#

neat

proper vault
#

please get rid of the lambda keyword

#

just use like \ or sth

vestal solstice
#

Л

#

marsh void
#

Λ

proper vault
#

λ

marsh void
#
(string: str, x: int) -> {
    // return string copied <x> times
    return string * x;
}``` how about just this
proper vault
#

ye, that works too

#

C++/java like

marsh void
#

λ

#

what I am creating is pretty much python + rust but works like python haha

#

@rugged sparrow actually, I’ll probably just construct FunctionType(...) during compilation lol

rugged sparrow
#

makes sense lol

cursive plover
#

hey there, I'm doin this just for fun..
Would there be a way to condense it into even lesser number of lines? It's 5 lines atm

medals = input().split()[:-1][::-1]
num = list(map(int,input().split()))
for i in range(0, len(medals), num[0]):
    num.extend(medals[i:i+num[0]][::-1])
print(*num[1:])
#
where my input is like so:
10 20 30 40 50 60 -1
3

And my output after some processing is:
40 50 60 10 20 30
#

and the processing that happens btw is that,
So my 1st line of input is the well, list. (And the -1 at the end is just useless so that has to be popped)
The second line is say some number x.

So like I have to start from the end of my input list, print the last x numbers, then move behind further, on and on

proper vault
#

why is the num read as a list?

cursive plover
#

cuz at the end I'm doing *num[1:]

#

Like, I read it as int before but my program was

#

more than 5 lines with that

proper vault
#

oh

edgy kelp
#

can do [medal for i in range(0, len(medals), num[0]) for medal in medals[i:i+num[0]][::-1]] for the loop as the simplest thing

proper vault
#

is the length of medals guaranteed to be a multiple of num

cursive plover
#

yes, it's guaranteed

#

@edgy kelp so this

medals = input().split()[:-1][::-1]
num = list(map(int,input().split()))
print(*[medal for i in range(0, len(medals), num[0]) for medal in medals[i:i+num[0]][::-1]])
#

that's 3 lines

#

great

#

is this the best we can go? There's no way btw where input and printing can take place all in the same line yeah?

proper vault
#
print(*(elem for chunk in zip([[*map(int, input().split())][:1][::-1]]*int(input())) for elem in chunk))
cursive plover
#

I'm thinking the 2 lines of input could somehow be reduced to 1

proper vault
#

this seems to work

cursive plover
#

wait,

proper vault
#

it is quite hacky, but it does indeed work

cursive plover
#

@proper vault but it doesn't provide the right output 😦

proper vault
#

it worked when I tested it

cursive plover
#

Erm

#

Why would it not work for me?

proper vault
#

what output did you get?

cursive plover
edgy kelp
#

getting the same as thejester

proper vault
#

ah, found the error

#
print(*(elem for chunk in zip(*[[map(int, input().split())][:1][::-1]]*int(input())) for elem in chunk))
``` forgot to save
edgy kelp
#

isn't that pycharm?

proper vault
#

it is

cursive plover
#

I still get

#

uhm

#

this

#
<map object at 0x7f8acae2c7f0> <map object at 0x7f8acae2c7f0> <map object at 0x7f8acae2c7f0>
#

as output

edgy kelp
#

where are you saving or runing the old thing then (or wrong run config set? )

cursive plover
#

uhm

#

I'm doing it here

proper vault
#

oh, nvm, I had the wrong file running

edgy kelp
#

lak, not you. Just curious about the saving because pycharm autosaves

proper vault
#

ye, I did not forget to save, I just ran a wrong scratch file

cursive plover
#

so

#

I can't run it on an online compiler then?

proper vault
#

no, my code does not work

#
print(*(elem for chunk in [*zip(*[iter([*map(int, input().split())][:-1])]*int(input()))][::-1] for elem in chunk))
``` this seems to finally work
cursive plover
#

ah yes

#

could you also explain how that works 😅 so I could write some magic like that myself in the future

proper vault
#

it uses the zip(*[iter(var)]*n) trick, which lets you do this

#

!e

var = range(12)
n = 4
print(*zip(*[iter(var)]*n))
night quarryBOT
#

@proper vault :white_check_mark: Your eval job has completed with return code 0.

(0, 1, 2, 3) (4, 5, 6, 7) (8, 9, 10, 11)
proper vault
#

and then prints those out in reverse order, flattened

cursive plover
#

well

#

how did you compress the two lines of input into 1,

#

er wait I get that actually

proper vault
#

you just call input() in 2 different places. In most cases, the left side of a binary operator is evaluated first, so e.g.

#

!e

(print("Hi"),1)[1] * (print("Bye"),1)[1]
night quarryBOT
#

@proper vault :white_check_mark: Your eval job has completed with return code 0.

001 | Hi
002 | Bye
proper vault
#

will always print those in that order

#

(at least I think so, someone correct me if I am wrong)

#

which is why it should never happen that input() happen in the wrong order

#

if you do need them in some less convenient order

#

you can do

#
(lambda n,l: rest_of_code)(input(), map(int, input().split()))
``` which is guaranteed to evaluate from left to right
cursive plover
#

(print("Hi"),1)[1]
what's the [1] for? and why do you have the 1 in the tuple too?

proper vault
#

so that the * would not error

cursive plover
#

oh right

proper vault
#

I just make a tuple of print("Hi"), 1, select the 1 and multiply it with another one from another tuple

#

another way to do it is using or

#

!e

(print(1)or 1) * (print(2)or 2)
night quarryBOT
#

@proper vault :white_check_mark: Your eval job has completed with return code 0.

001 | 1
002 | 2
cursive plover
#

(print(1) or 1)? lol what that mean

proper vault
#

!e

print(1 or 2, 0 or 1, None or 1, type or False, False or 88)
night quarryBOT
#

@proper vault :white_check_mark: Your eval job has completed with return code 0.

1 1 1 <class 'type'> 88
cursive plover
#

wow it could compare type with False

proper vault
#

!e

import time
print(20 or this_variable_is_not_defined, 20 or quit(), 20 or time.sleep(10))
print('no sleep')
night quarryBOT
#

@proper vault :white_check_mark: Your eval job has completed with return code 0.

001 | 20 20 20
002 | no sleep
proper vault
#

or in python checks if the first operand is truthy, and if it is, it results in it, completely ignoring the other one. If it is falsey, it just returns the other one without checking it

cursive plover
#

I see, I wonder
!e

print(class or type)
proper vault
#

class is a keyword, not a value

cursive plover
#

well, is type a value too?

#

cuz earlier we did False or type

proper vault
#

yep, type is value

cursive plover
#

!e
print(type)

night quarryBOT
#

@cursive plover :white_check_mark: Your eval job has completed with return code 0.

<class 'type'>
cursive plover
#

uhm

#

so the value of type is what again?

#

!e
print(type(type))

night quarryBOT
#

@cursive plover :white_check_mark: Your eval job has completed with return code 0.

<class 'type'>
proper vault
#

type is an instance of type

#

metaclasses in python are a thing

#

which lets you do

#

!e

print(type("", (), {"__str__": lambda *_: "totally a real class promise"})())
night quarryBOT
#

@proper vault :white_check_mark: Your eval job has completed with return code 0.

totally a real class promise
cursive plover
#

oh wow, I've never heard about metaclasses before so I'll be sure to read up on that, and look at that code again

#

about the original code, it was this
print(*(elem for chunk in [*zip(*[iter([*map(int, input().split())][:-1])]*int(input()))][::-1] for elem in chunk))

So

#
[*zip(*[iter([*map(int, input().split())][:-1])]*int(input()))][::-1]

gave us the

#

uhm, [ [40,50,60], [10,20,30] ]

proper vault
#

yep

cursive plover
#

now you did elem for chunk in [ [40,50,60], [10,20,30] ] for elem in chunk

proper vault
#

except the inner ones are tuples, but that is not relevant

#

yep, you can nest list comprehension

cursive plover
#

oh right, you take each element, and form a new list of all such individual elements

#

and then you have a print(*(new list formed))

proper vault
#

yep

cursive plover
#

right, this zip(iter()) thing is something I've never seen before, thank you

#

is there a place where you can hone your golfing skills or something? I don't think I can just think of such magic thingies by myself

proper vault
#

here tbh

cursive plover
#

like, how did you, where did you begin, when you began

#

oh

proper vault
#

just like, hang around and you find some truly cursed things

cursive plover
#

yeah, that's true too

proper vault
#

also, clash of code has shortest mode

cursive plover
#

so there's no like, place or book or smth that actually talks about this in detail right?

#

sec lemme look up what's clash of code

proper vault
#

note that codegolf is not put things in one line

#

it is as few chars as possible

cursive plover
proper vault
cursive plover
#

ah, okay, fewer chars

#

is there something for trying to put code into baar?

#

like, I've been trying to do one-liners for problems in the recent past, guess golfing isn't really the right word for that like you pointed out

#

also, that website doesn't open for me, is it just me or is the link broken?

#

Mm, also thank you once again. I learnt quite a lot !

proper vault
#
In [83]: type(Ellipsis)
Out[83]: ellipsis
``` interesting
marsh void
#

!e
e = ...
print(e, type(e), type(e)())

night quarryBOT
#

@marsh void :white_check_mark: Your eval job has completed with return code 0.

Ellipsis <class 'ellipsis'> Ellipsis
marsh void
#

@proper vault soo? ¯_(ツ)_/¯

rugged sparrow
#

@marsh void I think Ellipsis is a Singleton too

thin trout
#

Yeah it is

marsh void
#

It is

#

Modules are technically also singletons

thin trout
#

I'm pretty sure you can find a way to import the same module twice and make two different objects

vestal quail
#

The import machinery lets you just... create modules. Sure, regular imports are cached, but modules are by no means singletons

marsh void
#

I said technically

#

I know how creating modules work, haha

sick hound
#

hmhmhm. has this channel produced ever anything tangibly useful? lemon_thinking

#

this stuff makes me feel warm and fuzzy inside

sick hound
#

hmm is there some nifty way to implement in basic python the prod function just like sum?

proper vault
#
from math import prod
sick hound
#

in python 3.8 I guess?

proper vault
#

ye

vestal quail
#

there's always reduce and operator.mul

proper vault
#

ye, that is a nice one

sick hound
#

I hacked it together with those but I was wondering to get it to work on lists somehow nicely

proper vault
#
from functools import reduce
from operator import mul
reduce(mul, [1,2,3,4])
sick hound
#

that's as close as I got too

proper vault
#

what is this thing lacking?

sick hound
#

this is very good

#

but this is no sum 🙂

proper vault
#

it pretty much is. You can also give it an initial value arg, except even better, because it does not assume 0 by default

sick hound
#

okay hmm

#
    prod = lambda xs: xs[0] if len(xs) == 1 else xs[0]*prod(xs[1:])
    prods.append(prod(chunk))```
#

it's not pretty but

#

now it works like the sum

#

no need for any imports

proper vault
#
def prod(xs):
  it = iter(xs)
  val = next(it)
  for n in it:
    val *= n
  return val
sick hound
#

that's hurting my brain. what is val pointing to?

#

it's not changing when it changes I suppose

#

but it gets reassigned when it gets multiplied everytime by n?

#

ok yeah the return makes more sense

proper vault
#

val is the first element of the iterable

#

so that it works for multiplying things that do not have 1 as an interoperable element

sick hound
#

i was thinking you're accumulating the answer into the xs or something

#

like it was a cumulative product of some kind

#

where the values of the array get reassigned by the product so far

marsh void
#
def prod(iterable):
    value = 1
    for n in iterable:
        value *= n
    return value```
#

sorry, I just un-esoteric-ed it

proper vault
#

that assumes 1 * x == x, which is not guaranteed

zealous widget
#
def prod(iterable, start=None):
    if start is None:
        start, *iterable = iterable
    for n in iterable:
        start *= n
    return start
proper vault
#

to be pedantic, memory inefficient if you pass a generator and no start

zealous widget
#

that's true, you can just next it

vestal quail
#

*= is technically also different from *

proper vault
#

yep, in this case you do want *= though

sick hound
#

that assumes 1 * x == x, which is not guaranteed
@proper vault as an algebra fanboy, highly agreed

vestal quail
#

You do? You'd want your prod function to mutate your start object?

zealous widget
#
def prod(iterable, start=None):
    iterable = iter(iterable)
    if start is None:
        start = next(iterable)
    for n in iterable:
        start *= n
    return start
proper vault
#

oh, ye, in salts case no, in the one I had, ye

#

but honestly, even then it would be fine

#

you generally pass a literal for start

zealous widget
#

i've passed mutables for start

#

Counter()

proper vault
#

literal was a bad term, I meant more inline object

#

essentially sth you do not have a named reference to

grizzled cloak
#

@proper vault when would 1 * x != x?

proper vault
#

when you use an object with custom __mul__

grizzled cloak
#

ah

marsh void
#

ah, lmao

#

yes

#

Sorry, we don't have python objects in algebra

lost dawn
#

if x was a deck of cards and if you ever multiply a deck of cards it shuffles it or something

#

:D?

#

Very dank

proper vault
#

tbh, I can think of no case where x * 1 != x would make sense

zealous widget
#

mostly in cases where it isn't defined

zealous widget
#
In [30]: class permutation: 
    ...:     def __init__(self, *seq): 
    ...:         if not all(i in seq for i in range(len(seq))): 
    ...:             raise ValueError("Not a proper permutation.") 
    ...:         self.seq = seq 
    ...:      
    ...:     def __mul__(self, other): 
    ...:         if not isinstance(other, permutation): 
    ...:             raise TypeError("Not a permutation.") 
    ...:         if not len(other) == len(self): 
    ...:             raise ValueError("Length mismatch.") 
    ...:         return permutation(*(self.seq[i] for i in other.seq)) 
    ...:      
    ...:     def __len__(self): 
    ...:         return len(self.seq) 
    ...:      
    ...:     def __repr__(self): 
    ...:         return f"permutation({', '.join(str(i) for i in self.seq)})" 
    ...:              
    ...:                                                                                                                                                            

In [31]: a = permutation(0, 4, 2, 1, 3)                                                                                                                             

In [32]: b = permutation(3, 1, 4, 2, 0)                                                                                                                             

In [33]: a * b                                                                                                                                                      
Out[33]: permutation(1, 4, 3, 2, 0)

I don't think it would make sense here, for instance.

scarlet scroll
#

Anyone know how I would make this code make as least a sense as possible so people wouldn't know to remove it. Trying to add a secret message into my program as people have been selling it.

#
import codecs
import base64
import sys

fortnite_ios_token = "R3V2ZiBvYmcgdmYgc2Vyci4gdnMgbGJoIGNudnEgc2JlIHZnLCBsYmgganJlciBmcG56enJxLg=="
sys.stdout.write(codecs.decode(base64.b64decode(fortnite_ios_token).decode(), 'rot_13') + '\n')
edgy kelp
#

do those people have knowledge in python?

#

or programming

scarlet scroll
#

Probably not.

edgy kelp
#

Made this thing a bit ago that encodes text to a string of zero width spaces https://paste.fuelrats.com/iqunayowem.py, if they don't know python it should be less obvious than a bunch of lambdas or something

#

the first bunch of functions are faster but result in a lot longer strings

sick hound
#

i would recommend obfuscating that in with the rest of the program too and making sure the boundary is unclear

#

however much you obfuscate that bit of code, if someone can just see the obfuscated bit and get rid of it you've failed

mystic owl
#

@scarlet scroll What is the token for?

edgy kelp
#

there will still be a clear difference between that code and normal code, so unless you plan on obfuscating it all or making the source unavailable t'll still probably be fairly easy even with trial and error

sick hound
#

This bot is free. if you paid for it, you were scammed.

#

if you decode the base64 you get Guvf obg vf serr. vs lbh cnvq sbe vg, lbh jrer fpnzzrq., and then you un-rot13 that and you get that

pure dew
#

i was gonna write the crazy thing for compiling a python codebase to bytecode and writing a codec register to execute it on load, but python already does that

#

so i guess all i'm writing is a nifty in-place bytecode compiler

cursive plover
#

when you use an object with custom __mul__
@proper vault
erm, could you also give an example?

marsh void
#
class Lol:
    def __rmul__(self, other):
        exit()
1 * Lol()``` @cursive plover
cursive plover
#

oh so that does 1 * exit() and thus exits, ah

lament ibex
#
>>> class Safe:
...     def __init__(self):
...             if __import__('random').randint(0, 1):
...                     __import__('ctypes').string_at(0)
... 
>>> Safe()
<__main__.Safe object at 0x7f0db2ab1e90>
>>> Safe()
Segmentation fault (core dumped)

segfault roulette. I have no idea why I thought of this or wrote it.

marsh void
#

haha

#
import ctypes
import random


class MaybeSafe:
    def __init__(self) -> None:
        if random.randint(0, 1):
            ctypes.string_at(0)

``` ![OKFlex](https://cdn.discordapp.com/emojis/614087661782564894.webp?size=128 "OKFlex") pep8
pure dew
#

pep8 bad

marsh void
#

pep8 nice

sudden osprey
#

What is that cool trick where you can split a string into several parts of size n, for example 'abcdefghi' with part size of 3 would return ['abc', 'def', 'ghi']

vestal solstice
#

zip(*[iter(string)]*size)

#

technically not what you asked because it doesn't work on strings

#

without join

sudden osprey
#

Ahh, that's what I was thinking of. Thank you.

snow beacon
#

I think it's called chunking.

edgy kelp
#
print(*__import__("itertools").zip_longest(*[iter("ABCDEFGH")]*3, fillvalue=None))
neat otter
#

hey, do you guys have some weird way to delete all files in a windows pc ?

#

trying to show some friend why he shouldn't be copypasting code without knowing how it works

vestal solstice
#

you can just turn it off

neat otter
#

(didn't intent to run it tho), kind of curious about how you can camouflage code

vestal quail
#

a puzzle for y'all:

$ python3 -ic 'url = "http://httpbin.org/status/402"'
>>> del __builtins__.__import__
>>> # your code here
...
>>> requests.get(url).text
'F**k you, pay me!'

Borrowed from https://sopython.com/wiki/Riddles#1-3

sick hound
#

is this cheating? ```py

del builtins.import
class Lol:
... def getattr(self, attr):
... return self
... def call(self, *args):
... return self
... def repr(self):
... return "'Fk you, pay me!'"
...
requests = Lol()
requests.get(url).text
'F
k you, pay me!'```

vestal quail
#

yeah, sorry. You're supposed to actually import requests

whole kiln
#
spec = __loader__.find_spec("builtins")
m = __loader__.create_module(spec)
requests = m.__import__("requests")
proper vault
#

Create module is the piece I was missing

vestal quail
#

@whole kiln Nice!

#

fair warning: I spent like 4 hours on that one

sick hound
#

come on, that's easy

proper vault
#

seems like you get left with an unremovable __builtins__ dict

sick hound
#
>>> del __builtins__.__import__, __builtins__
>>> sys = ().__class__.__base__.__subclasses__()[64].acquire.__globals__['sys']
>>> __builtins__ = sys.modules['builtins']
>>> spec = __loader__.find_spec('builtins')
>>> m = __loader__.create_module(spec)
>>> requests = m.__import__('requests')```
#

on different versions of python that 64 might change to something like 80

#

but same idea

#

@vestal quail that wasn't very hard :P

vestal quail
#

huh. Not bad, not bad at all

sick hound
#

this should also work if you clear globals

#

so, onto problem 6

#

hmm

vestal quail
#

glad you're enjoying the puzzles (:

edgy kelp
#

you can do pretty much anything after getting to object which is always accessible from constants

sick hound
#

well if it can be any error other than a SyntaxError, (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( would do the trick since it stack overflows the parser and raises a MemoryError

edgy kelp
#

6 seems like a good case for the compiler recursion errors 😄

whole kiln
#

@vestal quail Well it only took me 30 seconds to realise builtins is available in locals()

#

And then it's basically the same solution as before

edgy kelp
#

... or just use a tab to have it more convenient in the console and get a TabError

vestal quail
#

Wait, you can access locals() after running globals().clear()?

whole kiln
#

Yes

vestal quail
#

that throws a NameError on my machine

whole kiln
#

Worked for me

vestal quail
#
>>> globals().clear()
>>> locals()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'locals' is not defined
sick hound
#

number 10 is easy, ||object.__new__(Bomb)||

proper vault
#
>>> globals().clear()
>>> globals().keys()
dict_keys(['__builtins__'])
``` I have this neat thing
whole kiln
vestal quail
#

not using CPython I guess?

whole kiln
#

I am

#

3.8.1

sick hound
#

for 11, is ||__import__('__main__').__dict__.__delitem__('x')|| considered cheating?

vestal quail
#

Interesting. Haven't tried that in 3.8 yet

#

@sick hound yes

sick hound
#

aww :(

vestal quail
#

@proper vault Are you also using 3.8?

proper vault
#

ye

vestal quail
#

that explains why locals is still accessible, then

sick hound
#

also i have a self-containing tuple ```py

t
((...),)
t[0] is t
True```

vestal quail
#

dude, how

sick hound
#
>>> import ctypes
>>> t = 0,
>>> ctypes.c_longlong.from_address(id(t)+24).value = id(t)
>>> t
((...),)```
marsh void
#

smart

vestal quail
#

Thanks, I'm gonna post that solution if you don't mind

#

You guys are on a roll, so maybe someone wants to help us figure out #22

sick hound
#

actually i do mind, a proper solution would fix the reference counts

#

since otherwise if you removed the reference to that tuple, it would probably end up with a reference count of -1 which is not good

#

and you might also break 0's reference count, not that it would particularly matter

vestal quail
#

lots of these puzzles have side effects that are not good hahaha

sick hound
#

well yeah but ```py

import ctypes
x = id((1, 2, 3))
x = ctypes.cast(x, ctypes.py_object).value
x
(((((((((((((((((((((((((((((<NULL>, (<class '_ctypes.Structure'>,), {(<class 'ctypes.c_long'>, (), 1): <class 'ctypes.CFUNCTYPE.<locals>.CFunctionType'>}), 'BigEndianStructure', <class '_ctypes.Structure'>), None, None), (<class '_ctypes.PyCFuncPtr'>,), {((((((((<NULL>, <class 'ctypes._endian.BigEndianStructure'>), <class 'ctypes.CFUNCTYPE.<locals>.CFunctionType'>), 1), None), 'ctypes'), 'cast'), 'x'), None): 0}), 'CFunctionType', <class '_ctypes.PyCFuncPtr'>), (), 1), 'This class represents a dll exporting functions using the\n Windows stdcall calling convention, and returning HRESULT.\n HRESULT error values are automatically raised as OSError\n exceptions.\n ', None), 'l', None), 'This class represents a dll exporting functions using the\n Windows stdcall calling convention.\n ', None), 'This class represents the Python library itself. It allows\n accessing Python API functions. The GIL is not released, and\n Python exceptions are handled correctly.\n ', None), 'u', None), 'pointer', '_pointer_type_cache'), '?', None), 'P', None), 'c', None), 'b', None), 'B', None), 'Q', None), 'q', None), 'g', None), 'd', None), 'f', None), 'I', None), 'i', None), 'L', None), 'l', None), None, None), None, None), 2571192850400, <class 'ctypes.py_object'>)```

vestal quail
#

0 is interned anyway, so shouldn't be a problem

sick hound
#
>>> import ctypes
>>> x = id((1, 2, 3, 4, 5))
>>> x = ctypes.cast(x, ctypes.py_object).value
>>> x
('ctypes', 'cast', 'x', 'py_object', 'value')``` how did *that* happen??
vestal quail
#

shrug

sick hound
#

if you mess up your reference counting, this kind of stuff happens ```py

import ctypes
x = id((1, 2, 3, 4, 5, 6))
x = ctypes.cast(x, ctypes.py_object).value
x
(((((<NULL>, 'module', 'qualname', 'doc', 'slots', 'swappedbytes'), 'module', 'qualname', 'doc', 'slots', 'swappedbytes'), 'module', 'qualname', 'type', '_check_HRESULT', 'check_retval'), 'module', 'qualname', 'doc', '_FUNCFLAG_STDCALL', 'func_flags'), 2, 3, 4, 5, 6)```

#

oh hey look this tuple contains itself ```py

x
((((((...), 'module', 'qualname', 'doc', 'slots', 'swappedbytes'), 'module', 'qualname', 'doc', 'slots', 'swappedbytes'), 'module', 'qualname', 'type', '_check_HRESULT', 'check_retval'), 'module', 'qualname', 'doc', '_FUNCFLAG_STDCALL', 'func_flags'), 2, 3, 4, 5, 6)```

#

what ```py

x
(((...), 'module', 'qualname', 'doc', ''\'\\\'\\\\, 'func_flags'), 2, 3, 4, 5, 6)```

#
>>> x
(((...), '__module__', '__qualname__', '__doc__', "((...), \\\\\\\\\\\\'\\\\\\", '_func_flags_'), 2, 3, 4, 5, 6)```
#

ok it seems like it's staying at that

vestal quail
#

mind if I post it as a "partial solution"?

#

still better than nothing

sick hound
#

you can post it as a partial solution if you want to, just keep in mind that you might get some nonsense tuple out if you mess around with the resulting self-containing tuple enough

sick hound
sick hound
#

Challenge: segfault in 1 line

#

And less than 40 characters

proper vault
#

!e

 __import__('ctypes').string_at(0)
night quarryBOT
#

@proper vault :warning: Your eval job has completed with return code 139 (SIGSEGV).

[No output]
proper vault
#

33

edgy kelp
#

third of the things here are segfaults 😄

sick hound
#

well

#

Try doing it without using .string_at

proper vault
#

!e

 __import__('ctypes').wstring_at(0)
night quarryBOT
#

@proper vault :warning: Your eval job has completed with return code 139 (SIGSEGV).

[No output]
proper vault
#

34

#

😛

night quarryBOT
#

@sick hound :x: Your eval job has completed with return code 139 (SIGSEGV).

001 | Fatal Python error: Cannot recover from stack overflow.
002 | Python runtime state: initialized
003 | 
004 | Current thread 0x00007f6d2563a740 (most recent call first):
005 |   File "<string>", line 2 in f
006 |   File "<string>", line 2 in f
007 |   File "<string>", line 2 in f
008 |   File "<string>", line 2 in f
009 |   File "<string>", line 2 in f
010 |   File "<string>", line 2 in f
011 |   File "<string>", line 2 in f
... (truncated - too many lines)

Full output: too long to upload

sick hound
#

this is also 33 characters:

#

!e from ctypes import*;memset(0,0,1)

night quarryBOT
#

@sick hound :warning: Your eval job has completed with return code 139 (SIGSEGV).

[No output]
proper vault
#

ye, pretty much any ctypes pointer set at 0 will segfault

sick hound
#

challenge: segfault python in less than 33 characters

#

Sigh

edgy kelp
#

looks like the above doesn't work on win

sick hound
#

challange: segfault python without any imports / external modules. Only with the builtin object and syntaxes (importing any extension module is forbidden)

proper vault
#

from ctypes import*;string_at(0) is 32

sick hound
#

if you find such a case, you can report it to the upstream btw

edgy kelp
#

just refuses the access with OSError

sick hound
#

Try doing it with something that doesn't include string in the function name

#

@sick hound py def f(): try:f() except:f() f() i don't know if this is exactly a segfault but...

#

this is not a segfault

#

@sick hound

#

if you're wondering what on earth i did, it jumps forward 2,164,260,863 opcodes, which (as you might expect) breaks something

#

i didn't import anything or use any external modules, just some internal cpython madness

#

that is cool

#

not worth to report though

#

btw in 3.8 you can use .replace method of codetype

gilded orchid
#
import inspect
f=lambda:eval(inspect.getsource(f)[2:])()

terrible way of hitting the recursion limit

marsh void
#

ah lmao

#

that is smart

gilded orchid
#
a,b=[input()],-1
while a[b]!=a[b][::b]:a+=[str(int(a[b])+int(a[b][::b]))]
print(*a)

some terrible code I just made

#

I feel like it belongs here

thin trout
#

!e

a,b=[input()],-1
while a[b]!=a[b][::b]:a+=[str(int(a[b])+int(a[b][::b]))]
print(*a)```
night quarryBOT
#

@thin trout :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | EOFError: EOF when reading a line
thin trout
#

Yeah, it is in fact horrible haha

gilded orchid
#

it's a lot more readable if you substitute all of the b's for -1, but it's 2 bytes shorter so yeah

earnest wing
#
>>> class Int:
...   def __init__(self, value):
...     self.value = value
...     self.pos = False
...     self.neg = False
...   def __pos__(self):
...     if self.pos: self.value += 1
...     self.pos = not self.pos
...     return self
...   def __neg__(self):
...     if self.neg: self.value -= 1
...     self.neg = not self.neg
...     return self
...   def __repr__(self):
...     return repr(self.value)
...
>>> i = Int(0)
>>> ++i
1
>>> --i
0
>>> --i
-1
>>> i
-1
#

Not usable, but fun :^)

fallen heath
#

Somebody wanted to know if you could do

max = MO[0]
for i in range(15):
    if max < MO[i]:
       max = MO[i]```
shorter. I am not proud of this.
#

!e

vals = [3, 4, 2, 7, 8, 9, 2, 1]
m = vals[0]
[m := vals[i] for i in range(len(vals)) if vals[i] > m]
print(m)```
night quarryBOT
#

@fallen heath :white_check_mark: Your eval job has completed with return code 0.

9
vestal quail
#

Isn't that just max(MO)?

fallen heath
#

Yes, he didn't want to use max though

zealous widget
#

anyone need nice performant multiset with choice?

edgy kelp
#

only the map at the end reminds me of here

zealous widget
#

where, i figured the need for a multisetch was pretty esoteric

#

not the code itself

#

how about this max:

In [95]: vals = np.random.randint(0, 20, size=20).tolist()

In [96]: [m for m in [-float('inf')] for i in vals for m in [m if m > i else i]][-1]
Out[96]: 19

In [97]: max(vals)
Out[97]: 19
#

it's not really shorter, but it is a one-liner

green nymph
#
In [1]:  vals = [3, 4, 2, 7, 8, 9, 2, 1]                                                                                                                                                            

In [2]: m = vals[0]                                                                                                                                                                                 

In [3]: [m := (m,x)[m<x] for x in vals]                                                                                                                                                             
Out[3]: [3, 4, 4, 7, 8, 9, 9, 9]

In [4]: m                                                                                                                                                                                           
Out[4]: 9```
cursive plover
#
students = int(input())
cards = int(input())
l1 = [num for i in range(1, cards, 2*students) for num in range(i,i+students) ]
for i in range(1, students + 1):
    if cards in l1:
        if cards - i % students == 0:
            break
    else:
        if (cards + i) % students == 0:
            break
print("S%d" %i)

Now I know I can reduce the two lines of input to a baar, any way you'd reduce the whole for loop thing into lesser baar?

vestal quail
#

I have no idea what this code is doing

cursive plover
#

I can explain that

#

so consider this

#

Card Number ↓     1    2   3   4   5
                  9    8   7   6   10
                  11   12  13  14  15
                  19   18  17  16  20
                  21   22  23  24  25
#

I have 5 students, and say 25 cards, which are distributed in the manner as shown

#

now given a card, I'm to say which student it belongs to, which my code does

#

what I did there is that I noticed, the rows where the numbers are increasing, like 1 2 3 4 5, or 11 12 13 14 15, you can get the student id X like so:

vestal quail
#

I think you misplaced the 10 there?

cursive plover
#

no, it's right. That's how it's supposed to be

#

it's like circular

#

so it goes s1 -> s2 -> s3 -> s4 -> s5 -> s4 -> s3 -> s2 -> s1 -> s5 -> s1 -> ...

#

anyway that's besides the point

#

what I did is, if you see the rows where the cards are in an increasing order, you can notice a pattern

#

the student id X is such that it satisfies Card - X % Total number of cards == 0

#

and for non increasing rows, Card + X % Total number of cards == 0

#

That's what my code does

#

the list l1 basically contains the elements which are in increasing order in a row in that table I made above

#

does that make sense?

vestal quail
#

I'm still trying to process it

cursive plover
#

would you like me to clarify some part in specific @vestal quail ?

vestal quail
#

I think I'm confused because your code doesn't match your explanation

#

at least I think it doesn't

cursive plover
#

hm, wait lemme edit that

#

I think I'm writing it badly with the 'Element of the row' thing

rugged sparrow
#

!e py vals = [1,19,2,3,24,5,15,6,7,8,8] print(sorted(vals)[-1])

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

24
vestal quail
#

I also don't see how your code takes a card as input. As far as I can tell it only asks for the number of students and the number of cards, but never asks for a specific card

cursive plover
#

@vestal quail ah, yes the number of cards, is well also the card that is supposed to be the specific card

#

so is number of cards is 36, the specific card is also 36

vestal quail
#

Oh. Then I'm pretty sure there's an easier way to find the result

cursive plover
#

oh right

#

what would that be

vestal quail
#

still thinking about it, but I'm pretty sure it exists

#

do you happen to have some test cases?

cursive plover
#
Input
5
16
Expected output
S4
-------------------
Input
7
14
Expected output
S7
-------------
Input
7
36
Expected output
S6
vestal quail
#

this seems to do it:

def find_student(students, card):
    if ((card-1) // students) % 2:
        # decreasing row
        return students - card % students
    else:
        # increasing row
        return (card - 1) % students
#

the increasing rows always start with a multiple of students + 1, so in those you basically just need a modulo operation

#

the decreasing rows are similar, except you subtract the result from students because the ordering goes backwards

cursive plover
#

yeah, you have a cards - 1 in the else but no so in the if, why is that?

#
students = int(input())
cards = int(input())
if ((card-1) // students) % 2:
  print("S%d" %(students - card % students))
else:
  print("S%d"%(card - 1) % students)
``` and the new shortened code would look like this
#

I think I can shorten that further

#

so something like this

#
students, card = [int(input()) for i in range(2)]
print("S%d" %(students - card % students) if ((card-1) // students) % 2 else "S%d"%(card - 1) % students)
#

wonder if I could combine the above 2 lines into 1

vestal quail
#

In the decreasing rows you don't need a -1 because they're shifted - the largest number is on the right

cursive plover
#

ah, yes

vestal quail
#

Don't, you're making it incomprehensible again

#

shorter != better

cursive plover
#

@vestal quail nah I'm looking to write a one-liner for fun

#

lakmatiol!

proper vault
#
(lambda students, card: print("S%d" %(students - card % students) if ((card-1) // students) % 2 else "S%d"%(card - 1) % students))(int(input()), int(input()))
#

I have no clue what is going on, but I do know how to inline variables

cursive plover
#

inline variables?

proper vault
#

take a

var = stuff
code
``` and make it a single line
cursive plover
#

so is the basic structure like
(lambda variable, variable, more variables : print() and other functions here THEN the conditions THEN the input)
?

#

can I use that in all cases?

proper vault
#
(lambda var, var1, var2: code with vars)(get_var(), get_var1(), get_var2())
``` the trick is you call the lambda
cursive plover
#

I call the lambda? but where?

sudden osprey
#

Its useful if for example you need to use the input more than once

cursive plover
#

the () which enclose the wholecode?

sudden osprey
#

Something like (lambda a: (a+1)*(a-1))(int(input()). You call it directly

cursive plover
#

uhm

#

also, why is the whole lambda thing inside a pair of brackets()
like

#

why is it (lambda a: (a+1)*(a-1))(int(input()) and not lambda a: (a+1)*(a-1))(int(input() ?

#

Is it the brackets that are helping us call the lambda function?

proper vault
#

(lambda a: thing)(5) calls the lambda with 5 as the argument

sudden osprey
#

Because of order of operations. Also, note where the first parenthesis closes, it is not at the end

cursive plover
#

Oh ya, missed the closing position

proper vault
#

whereas lambda a: thing(5) would call thing with 5 and give us a lambda

cursive plover
#

give us a lambda? like lambda object or smth?

sudden osprey
#

The whole thing would return a lambda (if it didn't error)

cursive plover
#

uhm, sorry but what is 'a lambda'?

proper vault
#

lambdas do not error as long as there is not a syntax error in them

cursive plover
#

I thought lambdas were just like unnamed functions

proper vault
#

they are

sudden osprey
#

Oh yeah, good point

cursive plover
#

so lambda(x) returns to me an unnamed function? whereas (lambda)(x) calls the function?

proper vault
#

you can do

def u(): pass
a = u
``` and you can do
```py
a = lambda: None
#

in both cases, you get a function instance

cursive plover
#

oh wow, I didn't know you can do that

sick hound
#

something like lambda: None gives you a function

proper vault
#

in the first case, its name is u, in the other it is either None or <lambda>, I am not too sure

sick hound
#

(the name would be <lambda> iirc)

#

if you have a function in something like a, you can call it with a()

proper vault
#

!e print((lambda:0).__name__)

night quarryBOT
#

@proper vault :white_check_mark: Your eval job has completed with return code 0.

<lambda>
proper vault
#

ye

sick hound
#

if your function is lambda: None, you can't do lambda: None() since that would be a lambda that calls None, so you add brackets

#

(lambda: None)() calls the lambda

#

not particularly helpful in this case since you could just write None but still

proper vault
#

functions are objects in python, meaning you can do the same things with it as you can with any other variable

#

and also you can do this

sick hound
#

almost everything in python is an object

proper vault
#

!e

a = lambda:0
a.i = 5
print(a.i)
night quarryBOT
#

@proper vault :white_check_mark: Your eval job has completed with return code 0.

5
sick hound
#

yep, that works

#

classes are also objects

cursive plover
#

classes are objects? what wow

proper vault
#

everything except keywords are objects in fact

sick hound
#
>>> class Example:
...     pass
...
>>> print(Example)
<class '__main__.Example'>
>>> x = Example
>>> x
<class '__main__.Example'>```
vestal quail
#

keywords are syntax thingies, objects are runtime thingies. Kinda pointless to compare them

sick hound
#

you can also use functions as arguments to functions ```py

(lambda f:f())(lambda:4)
4```

cursive plover
#

Thank you people for the help, learnt so much. I'm gonna head off now but will come back and read the convo that goes on

hot crypt
#

is it possible to set function code by string assignment?

def dummy():
    pass

# magic? somehow?
dummy.code = "print('Hello World')\nprint('kthxbye')"

dummy()

> Hello World
> kthxbye```
#

not overriding the function, just changing its code

edgy kelp
#
>>> def func(): pass
...
>>> func.__code__ = compile("print('hey')", "<string>", "eval")
>>> func()
hey
hot crypt
#

that was fast

proper vault
#

is it possible for

variable
``` to execute arbitrary code.
brisk zenith
#

possibly.

#

if you override dict.__getitem__ somehow, or replace the dictionary given by globals() with a custom subclass which implements its own __getitem__

sick hound
#
>>> class EditedGlobals(dict):
...     def __getitem__(self, x):
...             if x.startswith('exec_'):
...                     self.__class__.__base__.__getitem__(self, '__builtins__').exec(self.__class__.__base__.__getitem__(self, '__builtins__').__import__('binascii').unhexlify(x[5:]))
...             else:
...                     return self.__class__.__base__.__getitem__(self, x)
...
>>> __import__('ctypes').c_longlong.from_address(id(globals())+8).value=id(EditedGlobals)
>>> __import__
<built-in function __import__>
>>> exec_7072696e74282768656c6c6f20776f726c642729
hello world```
#

@proper vault

proper vault
#

neat, I though that ctypes may be the way, but I do not know enough about ctypes

sick hound
#
>>> exec_0a78203d206c6973742872616e676528322c203130303029290a69203d20320a7768696c65206920696e20783a0a20202020666f72206a20696e20783a0a20202020202020206966206a203e3d20693a0a202020202020202020202020627265616b0a2020202020202020696620692025206a203d3d20303a0a202020202020202020202020782e72656d6f76652869290a202020202020202020202020627265616b0a2020202069202b3d20310a7072696e742878290a
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]```
#

if you're wondering what all of the self.__class__.__base__.__getitem__(self, '__builtins__') is about, it's because if you try to access globals the function will recurse infinitely

#

but self and x aren't globals so those are fine

grizzled cloak
#

btw for earlier:

import forbiddenfruit as fb

def dummy(): pass

fb.curse(type(dummy), 'code', property(lambda s: None))

def _set_code(f, c):
    f.__code__ = compile(c, "<string>", "eval")

fb.curse(type(dummy), 'code', type(dummy).code.setter(lambda s, c: _set_code(s, c)))

dummy.code = "print('test')"
dummy()```
gilded orchid
#
i=int(input())
a=i-2
print(*['#'*i,*['#'+' '*a+'#']*a,'#'*i*(i>1)],sep='\n',end='')

more terrible code I wrote

#

it basically outputs a square, so with an input of 3 it gives

###
# #
###
brisk zenith
#

!eval ```py
i=int("20")
a=i-2
print(*['#'i,['#'+' '*a+'#']*a,'#'i(i>1)],sep='\n',end='')

night quarryBOT
#

@brisk zenith :white_check_mark: Your eval job has completed with return code 0.

001 | ####################
002 | #                  #
003 | #                  #
004 | #                  #
005 | #                  #
006 | #                  #
007 | #                  #
008 | #                  #
009 | #                  #
010 | #                  #
011 | #                  #
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/vazixayagu

brisk zenith
#

so it does

proper vault
#

that is shockingly terrible

gilded orchid
#

yeah I agree

#

any ideas to golf that?

edgy kelp
#

golfing would only make it more readable

marsh void
#

haha

proper vault
#
i=int("20")
a=i-2
print('#'*i,*['#'+' '*a+'#']*a,'#'*i*(i>1),sep='\n',end='')
``` is I feel a pretty good start
gilded orchid
#

oh yeah good point

#

any ideas on how to get rid of the *(i>1)? (made so it works when input is 1)

gilded orchid
#
class a:
 def __invert__(_):
  return ~_
_=a()
print(~_)

another way of hitting the recursion limit

gilded orchid
#

how can I overwrite builtin's dunders?

sick hound
#

the module builtins or just generally built-in things?

gilded orchid
#

just generally built-in things

sick hound
#

depends on which dunder it is

gilded orchid
#

I wanted to overwrite things like int.__add__

sick hound
marsh void
#
~type('',(),{'__invert__':lambda _:~_})()``` @gilded orchid hey what was that clean code to cause recursion errors, here's better one
proper vault
#

you can use forbiddenfruit

#

!e

from forbiddenfruit import curse
curse(int, '__add__', lambda *_: 5)
print(1 + 6)
night quarryBOT
#

@proper vault :white_check_mark: Your eval job has completed with return code 0.

7
proper vault
#

oh, right, snekbox is not always accurate with those

#
In [3]: from forbiddenfruit import curse
   ...: curse(int, '__add__', lambda *_: 5)
   ...: print(1 + 6)
5
marsh void
#

snekbox da power

#

!e
import ctypes
ctypes.memmove(id(4), id(5), 28)
print(4, 5, 4 == 5, 4 is 5)

night quarryBOT
#

@marsh void :x: Your eval job has completed with return code 139 (SIGSEGV).

001 | <string>:3: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | 5 5 True False
003 | munmap_chunk(): invalid pointer
marsh void
#

owo

#

@proper vault this is interesting

proper vault
#

my repl just gives up

#

putting it into a scratch file does give the same output as snek

marsh void
#

oki

#

fun

#

repl be like

#

holy f*ck what'cha doing man

#

stop it

proper vault
#

ipython just completely gives up

marsh void
#

haha

proper vault
#

as it does more math to figure out how it should look, and pretty much any ctypes fuckup will collapse it

#

such as replacing any integer sum with 5, or replacing 4 with 5

#

how about replacing all cached integers with 5

marsh void
#

ipython died

sick hound
#

@marsh void i hope you're writing

marsh void
#

Nah

#

Because if I do it it gets looong

proper vault
#

what are we doing again?

sick hound
#

It is getting long for me already

#

Making this as verbose and long as possible

marsh void
#
from typing import Union
def sign(n: Union[float, int]) -> int:
    return (-1 if n < 0 else (1 if n > 0 else 0))```
#

simple one

#

just as an example of what I do on average with it

sick hound
#

I shouldn't have used mypy for this

#

*flake8

marsh void
#

on what haha

sick hound
#

on making that verbose

#

@marsh void this was a mistake

proper vault
sick hound
#

Mine is longer

#

@proper vault

#

i think

proper vault
#

I will make it even longer, forgot a docstring

sick hound
#

Fuck you

#

You didn't even write that yourself

#

You probably made it using a tool

#

Mine is handmade quality

proper vault
#

I did write the tool myself

sick hound
#

yes but still

proper vault
#

buuut, I do concede it is kinda cheating

vestal quail
#

two guys arguing over whose is longer 🤔

proper vault
#

😳

#

5262characters of utter irrelevance

sick hound
#

that link tho

#

i fix a jikey

proper vault
#

neat

sick hound
#

hackerman

sick hound
#

ok it's not that bad but i got bored

#

your move, @marsh void

proper vault
#

oops, forgot to import itertools as it

#

other than that, it does work and the parsing is actually taking time now

round geode
#

hi special channel.

proper vault
#

Hi special member

hot crypt
#

!e

class Str(str):
    def __mul__(self, other):
        if type(other) in [float, int]:
            absval = abs(other)
            s = super().__mul__(int(absval))
            cf = len(self) * (absval - int(absval))
            s += self[:int(cf)]
            return Str(s) if other >= 0 else Str(s[::-1])
        else:
            return Str(super().__mul__(other))
better_string = Str("Hello World!")
print(better_string * 2)
print(better_string * 2.5)
print(better_string * -0.3)
print(better_string * 5 * 0.1)
night quarryBOT
#

@hot crypt :white_check_mark: Your eval job has completed with return code 0.

001 | Hello World!Hello World!
002 | Hello World!Hello World!Hello 
003 | leH
004 | Hello 
hot crypt
#

I am happy now

sick hound
#

@hot crypt Geniuos

sick hound
#

@hot crypt Geniuos

sick hound
#

mhmhm

#

you could generalize that

#

it warms my heart

#

🔥 ❤️

#

string + string is easy to define. that's just concatenation

#

string times string would be an inner product. that's the only way it makes sense. so it would probably be the difference in length or something

#

string - string hmm

#

what is that

vestal solstice
#

string - string just deletes the length

sick hound
#

but what about "kappa" - "ligma"

vestal solstice
#

'Hello' - 'Dude' = 'H'

sick hound
#

how does that make sense

proper vault
#

that would be "Hello" - 4 imho

vestal solstice
#

string times string is join

#

WHellooHellorHellolHellod

proper vault
#

' ' * "ABCDE" == "A B C D E"

sick hound
#

"Kappa" * "Ligma" = "LigmaKLigmaALigmaPLigmaPLigmaA"

#

or wrong way around

#

I don't think we can get the algebra working 😓

zealous widget
#

you can overload __mul__ for different types

hot crypt
#

how about string - string deletes all characters from string2 in string1

#

so "Hello" - "eo" == "Hll"

vestal solstice
#

that seems reasonable

#

"lello" - "l" = "eo" ?

hot crypt
#

kinda like set substraction, but order is preserved

#

or maybe string2 is removed from string1 if present...
"Hello this is text" - "this is " == "Hello text"
nvm theres already str.replace("text", "") for that

proper vault
#

ye, a - b as a.replace(b, '') sounds good

hot crypt
#

could even be extended to str - list(str)

sick hound
#

!eval
print("test")

night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

test
sick hound
#

!eval print test

#

!eval
while True:

#

!eval
while True:

#

!eval
foo = 0
while True:
print("This is line " + str(foo) + " of the test.")
foo += 1

night quarryBOT
#

@sick hound :x: Your eval job timed out or ran out of memory.

001 | This is line 0 of the test.
002 | This is line 1 of the test.
003 | This is line 2 of the test.
004 | This is line 3 of the test.
005 | This is line 4 of the test.
006 | This is line 5 of the test.
007 | This is line 6 of the test.
008 | This is line 7 of the test.
009 | This is line 8 of the test.
010 | This is line 9 of the test.
011 | This is line 10 of the test.
... (truncated - too many lines)

Full output: too long to upload

sick hound
#

gotcha

marsh void
#

why

#

this is neither esoteric nor in right channel; #bot-commands is for normal tests

marsh void
#

!eval
import ctypes
t = 0,
ctypes.c_longlong.from_address(id(t) + 24).value = id(t)
while t:
t = t[0]

night quarryBOT
#

@marsh void :warning: Your eval job timed out or ran out of memory.

[No output]
marsh void
#

hehe

woven cipher
#

someone on repl.it turned python into a bunch of lambdas

#

it took something like 540 bytes just to output "Hello!"

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

that's 1916 bytes

brazen geyser
#

nice

dusky python
#

BRUH! I don't understand nothing in this code

snow beacon
#

I believe it creates some numbers using some bitshifts and by reading the number of parameters to a function mapped to 8 functions, then I think it finds sys.stdout.write or something by constructing the attribute names out of the documentation and names of various objects. It passes the numbers to whatever output function it's using, and the numbers represent the Unicode for Hello world!

dusky python
#

This is code with best readability lol

sick hound
#

actually it gets os.write, not sys.stdout.write

marsh void
#

!pep 614

night quarryBOT
#
**PEP 614 - Relaxing Grammar Restrictions On Decorators**
Status

Accepted

Python-Version

3.9

Created

10-Feb-2020

Type

Standards Track

marsh void
#

Behold, everyone!

rugged sparrow
#

Hell yes

marsh void
#

lambdas as decorators without magic!

#
def d_(x):
    # identity
    return x

@print
@d_(lambda f: f.__name__)
def lemon() -> None: ...``` though we should be able to do this now
snow beacon
#
_=lambda x:x
@_(lambda:0)
def zero():5
robust palm
#

first time posting some snippet in #esoteric-python ```py
from random import choice
while True:
(lambda player_move=input('rock paper scissors\n'),computer_move=choice(['rock','paper','scissors']):
print('Draw') if computer_move==player_move else print ('You win.') if {'paper':'scissors','scissors':'rock','rock':'paper'}[computer_move]==player_move else print ('You lose.') if player_move in ('rock','paper','scissors') else print('Invalid Input'))()

snow beacon
#

This is cool. Stand by for me making it even more weird.

thin trout
#

PEP614, oh hell yeah!

snow beacon
#

By the way @robust palm in your dictionary, 'scissor' is missing an s.

#
*iter(lambda options={'paper':'scissor','scissors':'rock','rock':'paper'}:(user_move:=input("rock paper scissors\n"))and (computer_move:=__import__("random").choice([*options]))and print(computer_move,[["You lose!","You win!"][options[computer_move]==user_move],"Draw!"][computer_move==user_move]),...),
#

PEP 614 was accepted‽ I agree with the 'hell yeah!'

#

I expect the code above can be golfed a lot by combining the strings and only checking the first letter for the dict.

marsh void
#

@snow beacon yeah, it was; GvR was basically the sponsor of it so it makes sense haha

robust palm
#

Nice @snow beacon Can you tell me how this works without if statement [["You lose!","You win!"][options[computer_move]==user_move],"Draw!"][computer_move==user_move]),...),?

snow beacon
#

Working back from the end:

#

The comma is part of *blah, which converts to a list.

#

The , ...) is the second argument of iter.

#

In this case, it makes a while loop that executes the function until it returns Ellipsis, which is basically a while loop.

#

Then there's the subscript [computer_move==user_move] which is either True or False, which are used as integers in this case. False is 0, True is 1.

#

It indexes in the list [options[computer_move]==user_move],"Draw!"].

#

Wait, no.

#

The list is [["You lose!","You win!"][options[computer_move]==user_move], "Draw!"]

#

So it either picks "Draw!" or the other option based on the boolean.

robust palm
#

Thanks, now I understand it.

#

The list part is cool.

snow beacon
#

Thanks.

#

There's another way to make it which is extremely hard to read.

#

I'll make a demo.

#
"YYoouu  lwoisne!!"[options[computer_move]==user_move::2]
#

Replacing ["You lose!","You win!"][options[computer_move]==user_move].

#

I'll let you figure out how it works because I've got to go.

robust palm
#

I figured it out [options[computer_move]==user_move will return either true 1or false 0 and then print the string skipping a character each time

proper vault
#

salt-die made this really cool RPS

from random import randint

user = "rsp".find(input("Choose rock[r], paper[p], or scissors[s]: "))
computer = randint(0, 2)
print(f"The computer chose {('rock', 'scissors', 'paper')[computer]}.")
print(("It's a draw!", "You lose!", "You win!")[user - computer])
gilded orchid
#
>>> ord('r')%5%3
1
>>> ord('p')%5%3
2
>>> ord('s')%5%3
0

this might be useful

vocal pawn
#

@gilded orchid That raises an error

#

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

#

for me, anyway.

#
Traceback (most recent call last):
  File "C:\Users\User\python\myProgram.py", line 1, in <module>
    (lambda _, __, ___, ____, _____, ______, _______, ________:
  File "C:\Users\User\python\myProgram.py", line 2, in <lambda>
    getattr(
OSError: [Errno 9] Bad file descriptor```
marsh void
#

well

#

ouch

#
lambda cls: next(obj for obj in __import__('gc').get_objects() if type(obj) is dict and obj == dict(cls.__dict__))``` this seems more friendly
#

And I made this one, hehe

bitter iris
#

@marsh void does it same with gc.get_referents(cls.__dict__)

marsh void
#

Wait is this real

#

Holy crap this is sick

bitter iris
#

yea, most of time I use it

#
>>> gc.get_referents(object.__dict__)[0]["__init_subclass__"] = classmethod(lambda cls: print("I am the owner of this interpreter"))
>>> class X:
...     pass
... 
I am the owner of this interpreter
#

This would be a good challange for this channel to create a class that is not inheriting from object in python 3

marsh void
#

how

#

lmao

#

Okay that would be hecking fun

#
get_dict = lambda cls: __import__('gc').get_referents(cls.__dict__)[0]``` okay this one is better for modifying stuff then
#

TIL such an epic thing exists

thin trout
#

I'm pretty sure that they are sending this challenge completely aware that it is impossible haha

marsh void
#

Yeah it feels like so

potent comet
#

It's not, you could do it by using ctypes or the like to create a class inheriting from itself.

marsh void
#

even though everything in python inherits from object

thin trout
#

I'm pretty sure the interpreter will reject it

#

It doesn't implement the basis of what a python object needs to communicate with the interpreter

#

Or.. You could redefine everything yourself

marsh void
#

Lol

sick hound
#

i'm getting somewhere ```py

from ctypes import *
x=c_char_p(b'test')
y=c_char_p(b'something')
typ=cast(ARRAY(c_longlong,44)(10, id(type), 0, c_void_p.from_buffer(x).value, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, c_void_p.from_buffer(y).value, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),py_object).value
typ
<class 'test'>```

#

@bitter iris ```py

from ctypes import *
x=c_char_p(b'test')
y=c_char_p(b'something')
arr=ARRAY(c_longlong,44)(10, id(type), 0, c_void_p.from_buffer(x).value, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, c_void_p.from_buffer(y).value, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
arr[33]=addressof(arr)
typ=cast(arr,py_object).value
z=()
arr[42]=id(z)
typ
<class 'test'>
typ.bases
()```

#

@marsh void @thin trout it's not impossible

marsh void
#

yooo

sick hound
#

admittedly it's not a particularly useful class ```py

typ()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot create 'test' instances```

#

but it is not a subclass of object ```py

issubclass(typ, object)
False```

marsh void
#

isinstance(typ, object) tho?

#

neat

#

all these zeros for methods like tp_iter and stuff in C code?

sick hound
#

yes

marsh void
#

okay gotcha

#

Neat I guess

sick hound
#
>>> obj=cast(ARRAY(c_longlong,2)(10,id(typ)),py_object).value
>>> obj
<test object at 0x000001BFE5613E10>
>>> type(obj)
<class 'test'>
>>> isinstance(obj,object)
False```
hot crypt
#

i love how no matter what is thrown at this channel, in a matter of hours someone has it coded

snow beacon
#

That's Python for you.

bitter iris
#

noice @sick hound

sick hound
#

that reminds me i need to update my nickname

#

anyway yeah, i basically just looked up the struct and wrote the memory manually

bitter iris
#

I lost my discord account because of discord kicked me out of session while switching my 2FA app :///

#

@sick hound yea, there is a part which checks a special condition and if the condition couldnt find it sets object as a base

indigo sand
#

Here's a one line rock-paper-scissors using the tricks from above:

print((lambda a,b:'The computer played '+['scissors','rock','paper'][b]+'.\n'+'DYYrooauuw   WL io ns !e  !'[(a-b)%3::3])(ord(input()[0])%5%3,__import__('random').randint(0,2)))

If you don't care what the computer played:

print('DYYrooauuw   WL io ns !e  !'[(__import__('random').randint(0,2)-ord(input()[0])%5%3)%3::3])

Someone who knows more about python than I do could probably get it shorter, but I'd say it's decent.

zealous widget
#
from random import randint

user = "rsp".find(input("Choose rock[r], paper[p], or scissors[s]: "))
computer = randint(0, 2)
print(f"The computer chose {('rock', 'scissors', 'paper')[computer]}.")
print(("It's a draw!", "You lose!", "You win!")[user - computer])

-->

print("=LW"["rsp".find(input("r,p,s: "))-randint(0,2)])
snow beacon
#

(Importing random still.)

indigo sand
#

I feel like it would be difficult to get it shorter than

print('=LW'[ord(input())%-4+__import__('random').randint(0,2)])
zealous widget
#

well you could ignore the input and just return a random LW=

#

i mean, that's really the gist of it anyway

#
input();print(choice('=LW'))
snow beacon
#

On cpython you can get random-ish numbers with id.

brazen geyser
#

__import__('os').urandom(1)[0]%3 one char shorter :p

snow beacon
#

Can that return 2?

#

Oh, right, it's a bytes object.

edgy kelp
#

I stand by my threaded random generator

#

maybe could make it a bit faster by changing the switch interval

marsh void
#

sleep(0) is somewhat a random generator lol

neat otter
#

!e

(lambda cls: __import__('gc').get_referents(cls.__dict__).pop(0))(int).update(square=lambda self: self * self); print(13.square())
night quarryBOT
#

@neat otter :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     (lambda cls: __import__('gc').get_referents(cls.__dict__).pop(0))(int).update(square=lambda self: self * self); print(13.square())
003 |                                                                                                                              ^
004 | SyntaxError: invalid syntax
neat otter
marsh void
#

oops

#

!e (lambda cls: import('gc').get_referents(cls.dict).pop(0))(int).update(square=lambda n: n**2)

night quarryBOT
#

@marsh void :warning: Your eval job has completed with return code 0.

[No output]
marsh void
#

!e (lambda cls: import('gc').get_referents(cls.dict).pop(0))(int).update(square=lambda n: n**2); print((13).square())

night quarryBOT
#

@marsh void :white_check_mark: Your eval job has completed with return code 0.

169
marsh void
#

@neat otter

neat otter
#

excuse me what

marsh void
#

yep

neat otter
#

no idea about how it works but it looks super cool

marsh void
#

defining new method

#

for a builtin type

neat otter
#

can I define variables inside 1 line ? SenkoThink

edgy kelp
#

a=val

neat otter
#
f"{' , '.join([' '.join([clef + ':', kwargs[clef] , '(' + type(kwargs[clef]).__name__ + ')']) for clef in kwargs])}
``` Wonder how I could get the len of that thing in the middle lol
#

O wait, i'm just stupid

#

(supposed to present the code to ppl in my class, trying to make one line overly stupid and complicated just to mess up with them

thin trout
#

I did the same to my math teacher, it was fun haha

#

It was a little for loop to calculate sequences, I turned it into a one-liner with some itertools in the middle

gilded orchid
#

shortest way to get the product of a list of numbers?

#

actually nvm

#

are there any ways I can golf this code?

a=1
for x in input().split():a*=sum(map(int,x))
print(a)
proper vault
#

!e

import math
print(math.prod(range(1,12)))
night quarryBOT
#

@proper vault :white_check_mark: Your eval job has completed with return code 0.

39916800
stone bane
#

Also I don't get why you're mapping int on x and summing

#

So "12" is supposed to become 3?

#

Cause otherwise that's a logical error

vestal solstice
#

print(eval(input().replace(' ','*')))

vestal quail
#

It's not, it's splitting the input on whitespace before iterating

stone bane
#

"12 24" x becomes "12" in first iteration and so on, right?

vestal quail
#

oh yeah, you're right after all

vestal solstice
#

input() is one line

#

the map is a mistake

#

wait I'm confused

stone bane
#

To simplify, basically If you're splitting, then all you need is int(x).

#

Summing on a Mapping takes the string one digit at a time. That will give you bad results

vestal solstice
#

it's reasonable that they want that, they never said otherwise

stone bane
#

Aye, I've posed it as a question

vestal solstice
#

eval('print(('+input().replace('','+').replace('+ ',')*(')+'0))')

gilded orchid
#

an input would be like

3
12 53 16

the first line is the number of numbers, and the second line was the space seperated numbers

#

the goal was to output the product of the sums of each number's digits (eg: (1+2)*(5+3)*(1+6) which is 158 in that case)

marsh void
#

AttributeError: attribute 'f_locals' of 'frame' objects is not writable

#

Any way to mess with it?

#

I need to replace function's globals

brazen geyser
#

you can call update/clear/pop or delete/insert individual keys

#

to f_locals

marsh void
#

ah, I meant f_globals

#

I tried to make it like that so it will not affect current globals but ehh

#
a = 13
f = lambda: var(b=a**13), result(b)``` basically I am trying to get this to work
#

var modifies f_locals, but b is already LOAD_GLOBAL in the code

#

that's what I am trying to figure out

marsh void
#

@brazen geyser

brazen geyser
#

you can modify f_globals the same way as f_locals

#

and aside from that you'd have to patch the bytecode to change any instructions to use locals rather than globals

#

if i understand what youre trying to do correctly

proper vault
#

how about putting things into globals and then restoring the state of globals, using sth like a context manager. Not sure how much more viable it is that that though

marsh void
#

Yeah it seems like a way to go

#

But smart bytecode patch sounds more neat

bitter iris
#

if you have access to the actual source symbol table might help you to infer the context of variables unless you dont know

marsh void
#

I mean ehh

#

So my idea now is to find the access to variables that are in call var(a=1) (updates locals()['a'] = 1 basically)

#

For now I am looking for LOAD_GLOBAL which refer to a name defined as kwarg for that var function

#

Then I replace it with LOAD_FAST pointing to the index of a new appended name in co_varnames

#

But it doesn't seem to work quite well haha

marsh void
#

hm, I just thought, how about

#
def f():
    var(a=<expr>, b=<expr>)
    print(a, b)``` convert the bytecode of this function to that:
```py
def f():
    a = <expr>
    b = <expr>
    print(a, b)```
thin trout
#

_May I ask what is var() ? It doesn't seems like a built in, doesn't it? _

proper vault
#

it is the thing he is making

#

it should let you do

lambda u: (var(a=u+3),print(a))
thin trout
#

Whaaattt

#

It basically creates a new variable?

rugged sparrow
#
f= lambda u:((a:=u+3), print(a)) ```
marsh void
#

Well that works but not <3.8

#

hm, is augmented assignment an additional opcode though

#

!e
import dis; dis.dis('(a := 1)')

night quarryBOT
#

@marsh void :white_check_mark: Your eval job has completed with return code 0.

001 |   1           0 LOAD_CONST               0 (1)
002 |               2 DUP_TOP
003 |               4 STORE_NAME               0 (a)
004 |               6 RETURN_VALUE
marsh void
#

yikes

#

!e
import dis
def f():
(a := 1); print(a)
dis.dis(f)

night quarryBOT
#

@marsh void :white_check_mark: Your eval job has completed with return code 0.

001 |   3           0 LOAD_CONST               1 (1)
002 |               2 DUP_TOP
003 |               4 STORE_FAST               0 (a)
004 |               6 POP_TOP
005 |               8 LOAD_GLOBAL              0 (print)
006 |              10 LOAD_FAST                0 (a)
007 |              12 CALL_FUNCTION            1
008 |              14 POP_TOP
009 |              16 LOAD_CONST               0 (None)
010 |              18 RETURN_VALUE
marsh void
#
def f():
    var(a=<expr>, b=<expr>)
    print(a, b)``` convert the bytecode of this function to that:
```py
def f():
    a = <expr>
    b = <expr>
    print(a, b)```

So, any ideas regarding this? I tried but it turns pretty meh since I am pretty newbie to bytecode

#

!e
import dis
def f(): var(a=1, b=str()); print(a, b)
def g(): a = 1; b = str(); print(a, b)
dis.dis(f), dis.dis(g)

night quarryBOT
#

@marsh void :white_check_mark: Your eval job has completed with return code 0.

001 |   2           0 LOAD_GLOBAL              0 (var)
002 |               2 LOAD_CONST               1 (1)
003 |               4 LOAD_GLOBAL              1 (str)
004 |               6 CALL_FUNCTION            0
005 |               8 LOAD_CONST               2 (('a', 'b'))
006 |              10 CALL_FUNCTION_KW         2
007 |              12 POP_TOP
008 |              14 LOAD_GLOBAL              2 (print)
009 |              16 LOAD_GLOBAL              3 (a)
010 |              18 LOAD_GLOBAL              4 (b)
011 |              20 CALL_FUNCTION            2
... (truncated - too many lines)

Full output: too long to upload

marsh void
#

So yeah that's what I have

bitter iris
#

I really like working with dis.Bytecode objects. They are immutable but the Instruction format makes everything a bit more easy. You can create a Bytecode object, go over the instructions and check if the opcode is LOAD_GLOBAL and the value of the oparg is one of your kwargs (var (**kwargs)) and if it is true append this bytecodes offset to a list. And then go over that list of offsets and alter the only opcode that is presented on that offset, argument can be same and then recreate a Code object with replace

earnest wing
#

Can I subclass bool by means of ctypes?

#

Oh, it turns out my use case simply needed to do some reference trickery in __bool__().

thin trout
#

Hey everyone, I'm gathering some ideas to maybe bring esoteric challenges back to life as a user event, if you have any interesting challenge ideas, feel free to DM me lemon_pleased

#

My brain is just melting right now

zealous widget
#

i feel like i deleted my fork a day or two ago

thin trout
#

Hey, you have a repo bin

zealous widget
#

is that true

#

how about a non-intersecting circles challenge

thin trout
#

Yes in your settings I thing

#

I mean.. I didn't even understood what was your circles about haha

zealous widget
#

it's the different ways to draw non-intersecting circles

#

where () represents a circle

#

(())() is one circle inside another circle next to a circle

#

((())) circle inside a circle inside a circle

thin trout
#

But what do you consider as intersecting?

zealous widget
#

the circles don't intersect

thin trout
zealous widget
#

they are either next to each other or inside one another, but no intersecting boundaries

thin trout
#

(()) but this can be considered as intersecting and non-intersecting, right?

zealous widget
#

it could if we didn't specify non-intersecting circles apriori

crystal mica
#

Intersecting is like (()()) right?

zealous widget
#

no thats two circles next to each other inside a big circle

crystal mica
#

Hmm

#

)()( this? lol

zealous widget
#

that would be a forbidden config

crystal mica
#

This sounds like one of the thing I did, forgot what it is, but needs to count open / close brackets

zealous widget
#

sorry about the bad gimp drawing

#

but maybe that makes it clearer

#

how many topologically distinct sets of n non-intersecting circles?

#

i find it interesting that you can represent them with parenthesis mostly

thin trout
zealous widget
#

second picture the circles overlap

#

which isn't allowed

#

non-intersecting

#

means the circles can't intersect

proper vault
#

so the goal is to draw the circles?

thin trout
#

Right, that’s why they have the little ❌

#

It is salt’s goal

zealous widget
#

intersecting circles shown above can be done with different brackets:
( { ) }

#

but not all distinct sets of intersecting circles can be represented 1-dimensionally

#

since the intersections can get pretty subtle with a lot of circles

thin trout
#

(May I also ask what this can be used for?)

zealous widget
#

but none of that matters for non-intersecting circles, they're perfectly representable

#

i dunno what it can be used for

#

it's a fun problem, it can be used to take up some of your time

thin trout
#

It sounds a bit like an advent of code challenge

zealous widget
#

it could be probably

thin trout
#

Well, if you have any other challenge idea pithink lemon_pleased

radiant bear
#

the intersecting circles is codewars i think

zealous widget
#

that's much different than the combinatorial problem

crystal mica
#

Okay, I see, so different circles has different brackets to denote

#

()[]{} and ({})[] are good

#

({)}[] is not

#

Yep, this sounds a lot like what I use for parsing wikimedia or w/e it is

#

I made my own parser to parse into trees, basically have a stacks of opens and ends

#

Whenever I see an end symbol, I pop the last open symbol and pair them together -> never overlap

#

so ({)}[] turned into ({})[]

#

Can be tweaked to check I guess

zealous widget
#

you don't really need different brackets for non-intersecting circles though, it's unambiguous

#

it might make it more readable though

#

i have a function that gives this:

In [154]: set(all_words_length(4))
Out[154]: 
{(((()))),
 ((()())),
 ((())()),
 ((()))(),
 (()(())),
 (()()()),
 (()())(),
 (())(()),
 (())()(),
 ()((())),
 ()(()()),
 ()(())(),
 ()()(()),
 ()()()()}

but there are some redundant sets in there

#

like this ((())()) is really the same as this (()(())) topologically

#

i was going to work more on it eventually

cursive plover
#

I was able to use laktiamol's teachings today, and rewrite

total, rows = int(input()), int(input())
l = [i**3 for i in range(1, total + 1)]
print(rows**3, sum(l), sep = "\n")

into baar

(lambda total, rows: print(rows**3, sum([i**3 for i in range(1, total + 1)]), sep = "\n"))(int(input()), int(input()))```
🙂 so I'm glad I've made some progress, thank you @proper vault !
#

Oh there's 2 other kind of things I wanna learn to write in a baar
Ek is this:

l1 = []
indices = []
while a != 0:
    l1.append(a)
    if a%2 == 0:
        indices.append(index)
    a = a//2
    index += 1

essentially a while loop with conditions in it and appending to two lists in the same loop

The 2nd is this:

l2 = []
for j in range(len(l1)):
    l2.append(b)
    b = b*2

where I'm changing something inside the for loop, but like
so I could do l2 = [b**2 for j in range(len(l1))] but that will miss out the first b that was appended in the original for loop.

So how do I write the above two things in like baar xd

crystal mica
#

The 2nd one looks likepy l2 = [b * pow(2, i) for i in range(len(l1))]

#

It's simply math, where you loop from 0 to len(l1) but not doing anything with it, and each time increase b by 2

zealous widget
#

that first looks like the recipe to fast exponentiation

crystal mica
#

It does

zealous widget
#

which you can shrink by wrapping it in a function and letting it call itself, i guess

cursive plover
#

The 2nd one looks likepy l2 = [b * pow(2, i) for i in range(len(l1))]
thanks, damn I didn't think of that

crystal mica
#

The first can be like this, i still think it can be much better

#
prev = a * 2
l1 = [(prev := prev // 2) for _ in range(len(bin(a)[2:]))]
indices = [i for i, s in enumerate(bin(a)[2:]) if s == '1']
print(l1, indices)```
#

basically making use of bin(a)

zealous widget
#

you could use log base 2 i think

cursive plover
#

sorry salt, I don't follow

The first snippet is well yeah, appending to a list a number, and the quotient when divided by 2, till the number becomes 1 and storing indices where the quotient was even

crystal mica
#

yep, im dumb

#
l1 = [a // pow(2, i) for i in range(len(bin(a)[2:]))]
indices = [i for i, n in enumerate(l1) if not n % 2]
print(l1, indices)```
#
[10, 5, 2, 1] [0, 2]```
zealous widget
#

i don't think i have a simple fast exponentiation snippet, just a matrix mul one

#

but when you are doing fast exponentiation: you use squares

#
def exp_squaring(u, n):
    if n == 0:
        return [[1, 0], [0, 1]]
    if n == 1:
        return u
    if n & 1:
        return matrix_mul(u, exp_squaring(u, n - 1))
    return exp_squaring(matrix_mul(u, u), n >> 1)
crystal mica
#

that's overkill lol

cursive plover
#

@crystal mica right, the log2 thing and checking for places with 1, yeah that makes sense

crystal mica
#

but ye that'll work

#

well you are basically reversing a binary

zealous widget
#

but you can bit shift

#

instead of divide by 2

crystal mica
#

the length of l1 is the length of bin(a)[2:]

#

oh shit

#

im dumb again gdi

#
prev = a << 1
l1 = [(prev := prev >> 1) for i in range(len(bin(a)[2:]))]
indices = [i for i, n in enumerate(l1) if not n % 2]
print(l1, indices)```
zealous widget
#
In [170]: 11//2
Out[170]: 5

In [171]: 11 >> 1
Out[171]: 5
crystal mica
#

yeah I just realized

zealous widget
#

yep, bit shifting is fast

crystal mica
#

it is extremely fast

cursive plover
#

no way by the way to have both indices and l1 being assigned things in like a baar, yeah?

crystal mica
#

why not

cursive plover
#

uhm, how ?

crystal mica
#
prev = a << 1
l1, indices = [(prev := prev >> 1) for i in range(len(bin(a)[2:]))], [i for i, s in enumerate(bin(a)[2:]) if s == '1']```
#

hmm, 2 lines

cursive plover
#

also why did you use := there

crystal mica
#

well if you go with the // then you wont need it

#

hmm

#

good question

#
l1, indices = [a >> i for i in range(len(bin(a)) - 2)], [i for i, s in enumerate(bin(a)[2:]) if s == '1']```
#

There you go

#

I need sleep

zealous widget
#

len(bin(a)) - 2

#

int(log(a, 2))

cursive plover
#

oh yeah

#

int(log(a, 2))
where does that come?

zealous widget
#

that's the length of a binary number .... well you need to take the ceiling

cursive plover
#

so you mean do a for i in range(ceil(int(log(a,2)))) in Shirayuki's code?

zealous widget
#
In [181]: a = 312109841204
     ...: len(bin(a)) - 2
Out[181]: 39

In [182]: ceil(log(a, 2))
Out[182]: 39
crystal mica
#

something like that, yes

cursive plover
#

ah, nice

#

baar

#

thank you!

crystal mica
#

Sometimes it's about thinking outside the box

cursive plover
#

hm, yeah I'm dumb xd