#esoteric-python

1 messages · Page 81 of 1

snow beacon
#

Or at least is simpler.

marsh void
#

ofc it is

#

just not as beautiful, hehe

snow beacon
#

The sacrifices one must make for concision.

brazen geyser
#

@marsh void it's looks like it's kind of like forbiddenfruit

marsh void
#

oh ok

brazen geyser
#

readme says its specifically for making 2+2=5 lol

thin trout
#

Talking about forbiddenfruit, have you tried to evaluate a snippet with it?

proper vault
#

I did and it worked oddly

thin trout
#

And have you tried like numpy, or scipy, or networkx?

grave rover
#

||** **||

#

apparently this is a thing now

#

or well

#

again

#

sending markup without content :^)

pure dew
#

|| ||

#

nice

rugged sparrow
#
chilaxan@Macbook-Air[~/Desktop/python]: python3 -i struct_testing.py
>>> x = {'a': 100}
>>> x.a
100
>>> ```
#

i did a thing

pure dew
#

that looks too much like js

proper vault
#

and lua

#

and elm

rugged sparrow
#

¯_(ツ)_/¯

proper vault
#

it is cool though, no doubt about that

rugged sparrow
#
dict_struct = PyTypeObject.from_address(id(dict))
def dict_getattr(self, key):
    try:
        return type(self).__getattribute__(self, key)
    except AttributeError as attr_err:
        try:
            return type(self).__getitem__(self, key)
        except:pass
        traceback.print_exception(type(attr_err), attr_err, attr_err.__traceback__)
        return None

dict_getattr_p = get_cfunc(dict_struct.tp_getattro)(dict_getattr)
dict_struct.tp_getattro = dict_getattr_p
``` uses the struct code from doublescript
#

imma make setattr work next

#

it does break dir

#
>>> x = {'a':1}
>>> del x.a
ValueError: PyObject is NULL
>>>  ``` i got setattr to work
#

but thats a bit weird

pure dew
#

yikes C errors

rugged sparrow
#

yea...

brazen geyser
#

take key as a void pointer

#

check for null

#

if not null cast to py object

#

might work?

grave rover
#

to work on a serious project or my code injection, hmm...

rugged sparrow
#

@brazen geyser i only get that error with del

#

i dont think its toooo important to fix

brazen geyser
#

yes, because del passes NULL as attr into tp_setattro

rugged sparrow
#

ohhh it does

brazen geyser
#

and then ctypes tries to work with this as a py_object

#

which for some reason can't take NULL i guess

#

idk

rugged sparrow
#
def dict_setattr(self, key, val):
    if callable(val):
        val = type(type('',(),{'a':lambda s:0})().a)(val, self)
    type(self).__setitem__(self, key, val)
    return 0``` this is my setattr
brazen geyser
#

it's gotta be done at the function pointer level

#

rather than using a py_object for value argument youd use a c_void_p

#

i wonder how safe this is with regards to ref counting though

#

iirc py_object automatically inc/dec refs as needed

rugged sparrow
#

rn i clone my cfunc args from the orig func

brazen geyser
#

noticed that

#

might steal :P

rugged sparrow
#

lel

#

go for it

#

you still have to have a ref to the orig func to do it so it still needs a bunch of boilerplate

brazen geyser
#

hmm

#

actually

#

i think this will require changing the struct altogether

rugged sparrow
#
def get_cfunc(cfunc):
    return CFUNCTYPE(cfunc._restype_, *cfunc._argtypes_)```
brazen geyser
#

the void_p seems to get cat back to py_object automatically

#

due to the definition in _fields_

rugged sparrow
#

yea that error is raised before ctypes's hook

glacial rampart
#
🐍 x = [[1]]
🐍 y = [[[1]]]
🐍 x in y
True
🐍 import sys
🐍 for _ in range(sys.getrecursionlimit()):
••      x = [x]
••
🐍 for _ in range(sys.getrecursionlimit()):
••      y = [y]
••
🐍 x in y
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RecursionError: maximum recursion depth exceeded in comparison

ehehehe that was fun

#

you know something good is about to happen when you see for _ in range(sys.getrecursionlimit()) 🍿

zealous otter
#
def f():
    f()
f()```
#

Alright that's fun but a little bit easy. My goal is to get a RecursionError in one line of code.

I thought I could use an immediately invoked function like (lambda: 42)() but recursion makes it hard.

(f=lambda:f())() throws a SyntaxError which is weird because I thought the assignment operator returned a value (otherwise a = b = 42 wouldn't work) but apparently I'm missing something.

So now I'm trying something like (lambda:getcurrentfunction)() but I don't know where to find such a function.

#

The SyntaxError was caused by the parentheses before the assignment.
(lambda: 42)() works
(a=42) doesn't

#

Hmmm,
def ff(): return sys._getframe(0).f_code.co_name -> ff
ff = lambda: sys._getframe(0).f_code.co_name -> <lambda>
That's a bummer.

#

To be clear, f=lambda:f();f() is cheating.

red timber
#
(f:= lambda: f())()```
#

I know it's also possible to declare a lambda with lambdas, and make a recursive call from the inner ones

#

which is more of a mess

#

I want to call @crystal mica to the stand because I was never able to follow his walrusless recursive lambda abomination for AoC

snow beacon
#
(lambda x: x(x))(lambda x: x(x))
red timber
#

@snow beacon could you explain what's going there? I don't even know the order I should read it

snow beacon
#

I read it from the right.

#

The (lambda x: x(x)) is a function that takes a function and calls it on itself.

#

In order to make it recurse infinitely, we just need to call it on itself.

#

Fortunately, we've already figured out what function calls its argument on its argument.

#

It's the same function.

#

That's why it repeats.

red timber
#

I see

#

things become less obivous for me as you add more and more things to it

snow beacon
#

More explanations, or more lambdas?

red timber
#

more operations in the lambda

#

such as having a working, and actually useful lambda like that

snow beacon
#

(lambda x: x(x))(print) prints "<builtin print function>" or something similar to the console. (lambda x: x(x))(str) returns "<builtin class str>" or whatever it is. (lambda x:x())( lambda x: x() ) calls itself on itself on itself on itself on itself...

#

I like to look at it in terms of beta-reduction.

red timber
#

I mean just recursive lambdas

snow beacon
#

lambdas can be pretty messy, I don't blame you.

red timber
#

like taking the last one and doing fibonacci recursion

#

(lambda x: x(x))(print) this isn't hard to read, it's the lambda definition being evaluated first, then we pass print so we print(print)

#

recursive lambdas mess are my issue lol

#

not that it matters since they're merely done for esoteric enjoyment but still

pure dew
#

it basically is beta-reduction

zealous widget
#

combinators are fun:

In [44]: Y = lambda f:(lambda x: f(lambda z:x(x)(z)))(lambda x:f(lambda z:x(x)(z)))
    ...: R = lambda f: lambda n: 1 if n <= 2 else f(n-1) + f(n-2)
    ...: print(*(Y(R)(i) for i in range(1, 10)))
1 1 2 3 5 8 13 21 34
pure dew
#

oh yes

#

i did that in coconut a while back

#

was slow as hell, but it looked awesome

#

im liking the look of Hy tho

rugged sparrow
#
>>> utils.edit(list, 'sq_length')(lambda *s:print(s))
<CFunctionType object at 0x1028f2640>
>>> len([1,3])
Python(97991,0x10515adc0) malloc: *** error for object 0x102a3efc0: pointer being freed was not allocated
Python(97991,0x10515adc0) malloc: *** set a breakpoint in malloc_error_break to debug
[1]    97991 abort      python3``` this is fun
pure dew
#

what

zealous otter
#

@red timber @snow beacon Two beautiful solutions, thanks

gilded orchid
#

What's the shortest way to get the number of arguments a function takes?

zealous widget
#

.__code__.co_varnames length of that?

#

or inspect module

#

.__code__.co_argcount even better

brazen geyser
#

what should this method return in the case of variadic arguments?

zealous widget
#

i'm not sure, lemme find out

brazen geyser
#

i meant in terms of spec

gilded orchid
#

I don't think I'm dealing with variadic functions, so it doesn't really matter what it does

brazen geyser
#

co_argcount wont take *args, **kwargs into account i dont think

zealous widget
#

In [9]: a = lambda *args:None

In [10]: a.__code__.co_argcount
Out[10]: 0
#

which is probably the best way to handle it

brazen geyser
#

idk, that's rather ambiguous

zealous widget
#

*args is pretty ambiguous

brazen geyser
#

how will you differentiate between a function that actually doesnt take any arguments?

#

though

#

I don't think I'm dealing with variadic functions, so it doesn't really matter what it does

#

so it doesn't really matter for the problem at hand

zealous widget
#

i think there is a solution though, but i've long forgetten it

#

uhhh, i used __code__ in my intcode computer for AoC, and i remember there being some wrinkle for *args, **kwargs

#

__code__.co_varnames[:f_code.co_argcount + f_code.co_kwonlyargcount]

#

lemme try that

#
In [11]: a = lambda a, b, *args, c, **kwargs:None

In [12]: code = a.__code__

In [13]: code.co_varnames[:code.co_argcount + code.co_kwonlyargcount]
Out[13]: ('a', 'b', 'c')
grave rover
#

@zealous widget dont forget posonlyargcount (3.8+)

zealous widget
#

oh nice

potent comet
#

@gilded orchid The best way to get an argument count would be to use inspect.signature() on the function - that returns an object you can inspect, and uses a protocol allowing it to produce the right result for builtin functions (which don't have __code__) as well as stuff like functools.partial that have dynamic argument requirements.

rugged sparrow
#

@pure dew you were wondering about this the other day

#

@brazen geyser you also might like to take a look ^

marsh void
#

@rugged sparrow I'd rather make iter(123) result in 1, 2, 3 generator

rugged sparrow
#

I like it doing range cause it makes for loops cleaner

#
for i in 10:
     print(i)```
marsh void
#
>>> class Int(int):
...     def __iter__(self):
...         yield from map(int, str(self))
... 
>>> list(Int(123))
[1, 2, 3]``` idk
rugged sparrow
#

I mean, you can always import _utils and make the wrapper for your code lol

#

The stuff in there is mainly examples

marsh void
#

haha

#

but it's CPython only

#

I wonder if we're the only ones who are doing this roothink

rugged sparrow
#

Honestly I doubt it

crystal mica
#

Take it to the next level, so Int(10111213) will return 10, 11, 12, 13 lol

#

Coz Int(10-13) is for casual

rugged sparrow
#

Ooo

#

Time to mod int subtract to make ranges

#

Lmao

#
>>> @utils.edit(int, 'nb_subtract')
... @utils.nullwrap
... def int_sub(self, other):
...     return range(self, other)
... 
>>> 1-2
Traceback (most recent call last):
  File "_ctypes/callbacks.c", line 237, in 'calling callback function'
  File "/Users/chilaxan/Desktop/python/future/_utils.py", line 16, in wrapper
    return func(*map(lambda arg:ctypes.cast(arg, ctypes.py_object).value if arg else Null, args))
  File "<stdin>", line 4, in int_sub
TypeError: 'range' object cannot be interpreted as an integer
Traceback (most recent call last):
  File "_ctypes/callbacks.c", line 237, in 'calling callback function'
  File "/Users/chilaxan/Desktop/python/future/_utils.py", line 16, in wrapper
[1]    2075 segmentation fault  python3``` 🤔
#

i guess subtraction has to return an int

#
>>> @utils.edit(list, 'nb_subtract')
... @utils.nullwrap
... def list_sub(self, other):
...     for item in other:
...             try:self.remove(item)
...             except:pass
...     return self``` ah well i can still do this
#
>>> x = [1,2,3]
>>> x - [1,2]
[3]```
#

tbh that should prob use .copy

pure dew
#

bruh tf

#

is that the shit you showed me other day with random C errors but it still ran?

rugged sparrow
#

yea

pure dew
#

oh boy

#

as soon as i get settled in after the move i'll check it oud

rugged sparrow
#

it will basically be a more precise forbiddenfruit module

marsh void
#

@dense spire I strongly request to rename this channel to esoteric-cpython, haha

dense spire
#

.. why?

#

that would be inaccurate

pure dew
#

hardly

nocturne saddle
#

No, it would be. Sure, a lot of the tweaks and hacks are cpython specific, but not all patterns used here are cpython-specific; most lambda-golfs are perfectly fine according to the language specs and not necessarily cpython-specific.

pure dew
#

We have a lot of ctypes

#

but I was more joking than anything

sick hound
#

@rugged sparrow

#

!pep 276

night quarryBOT
#
**PEP 276 - Simple Iterator for ints**
Status

Rejected

Python-Version

2.3

Created

12-Nov-2001

Type

Standards Track

thin trout
#

Hmm

#

Could be interesting

sick hound
thin trout
#

Oh wait, you actually implement dead PEPs?

sick hound
#

yup

#

I kind a stopped because I dont have enough time but it still works on 6-7 peps

thin trout
#

Haha that's great!

sick hound
#

thanks

rugged sparrow
#

anyone here know why raising an exception in a CFuncType python function causes a segfault?

#

( only when its called from c)

marsh void
#

raising like raise?

#

PyErr_SetString or something was used for that if I didn’t forget it

rugged sparrow
#

PyErr_SetString doesnt work

#

i think this might actually be a bug with ctypes 👀

#

or acc prob something wrong with how my code works

#

either way, if an exception is raised, a garbage value is being returned that any operations on fail (except id)

marsh void
#
PyObject* raise() {
    PyErr_SetString(PyExc_RuntimeError, "test except");
    return NULL;
}``` doesn’t this kinda thing work? or are you doing ctypes all the way
rugged sparrow
#

Ctypes all the way

#

Also its probably my code

#

Cause Im manually initializing the structure within python if the type doesnt have it

rugged sparrow
#

@brisk zenith i remember you do a lot of ctypes stuff, do you know how i can properly add a new methods struct to a class? like tp_as_number on a list. I got it to work unsafely (it segfaults on exit, any exception in any of those methods causes it to return a garbage value that) but would prefer it work properly

manic kayak
#

question about recursion:

say you call getFactorial(3)
1 it adds getFactorial(3) to the stack
2 it adds getFactorial(2) to the stack
3 it adds getFactorial(1) to the stack, which returns 1
4 then it returns 2* getFactorial(1) == 2
5 then it returns 3* getFactorial(2) == 6

my question is can you stop the execution after step 3, such that it doesn't clear the steps 4, 5 from the stack?

brisk zenith
#

@rugged sparrow i'm not sure what you mean. could i see an example? :D

rugged sparrow
#

Also I think I fixed adding the struct

#

I just need to push newest

#

The issue I'm having now is with exceptions raised inside the CFunctions

#

nope it still segfaults on exit

#
>>> from py_future import _utils as utils
>>> @utils.edit(list, 'nb_subtract', safe=False)
... @utils.nullwrap
... def list_sub(self, other):
...     return self, other
... 
>>> [] - []
([], [])
>>> exit()
[1]    4211 segmentation fault  python3
``` @brisk zenith
#
>>> from py_future import _utils as utils
>>> @utils.edit(list, 'nb_subtract', safe=False)
... @utils.nullwrap
... def list_sub(self, other):
...     [*other]
... 
>>> x = [] - 1
Traceback (most recent call last):
  File "_ctypes/callbacks.c", line 237, in 'calling callback function'
  File "/Users/chilaxan/Desktop/python/py_future/_utils.py", line 18, in wrapper
    return func(*map(lambda arg:ctypes.cast(arg, ctypes.py_object).value if arg else Null, args)) #TODO solve exceptions issue
  File "<stdin>", line 4, in list_sub
TypeError: 'int' object is not iterable
>>> id(x)
140732819296720
>>> # x is now some sort of garbage value somehow
... 
>>> print(x)
[1]    4528 segmentation fault  python3```
#

@brisk zenith this is another weird issue with exceptions ^

sick hound
#

@rugged sparrow are you doing the references properly?

#

if the function is something in a type struct then that's a reference to it, so you need to incref it

#

the error thing is really weird though

rugged sparrow
#

I am increasing it's reference count

#

I should probably make a atexit function to decref it tho

rugged sparrow
#
morse=lambda s:''.join((lambda c,i=lambda c,s=0,t=None:int(str(ord(c))[s:t]):{''.join('.-'[int(l)]for(l)in bin(i(a,s=2))[3:]):chr(i(a,t=2))for(a)in'ʏ᧠ᩆ᪜ʴ᭪ᯊᰰ˞᳿ᵙ᷄̉̒ừὖ῁‒͆͋͛↩∇≹⋟⍄ፓᎯᐏᑱᓔᕈᖴᘜᚂዿ'}.get(c)or' ')(m)for(m)in s.split())
``` golfed morse code translator
thin trout
#

The crazy characters are just here for their chr value?

rugged sparrow
#

yea

thin trout
#

Haha, that’s great!

rugged sparrow
#

that string contains all the data needed for a morse code map of letter/number to val

zealous widget
#

for(a) same bytes as for a

rugged sparrow
#

Yeah

#

@zealous widget if you want to shorten it more be my guest I want to see how short it can get

proper vault
#

you can replace s=2 with just 2 I think

rugged sparrow
#

You're right

proper vault
#

.get(c)or' ' maybe can be
.get(c,' ') (this one I am not sure, you may be using falsey values along with the None

rugged sparrow
#

Nah that should work too

#

Damn I didn't see either of those lol

proper vault
#

you can replace the outermost comprehension (the one in ''.join) with a map

rugged sparrow
#

that works too nice

#
morse=lambda s:''.join(map(lambda c,i=lambda c,s,t:int(str(ord(c))[s:t]):{''.join('.-'[int(l)]for(l)in bin(i(a,2,9))[3:]):chr(i(a,0,2))for(a)in'ʏ᧠ᩆ᪜ʴ᭪ᯊᰰ˞᳿ᵙ᷄̉̒ừὖ῁‒͆͋͛↩∇≹⋟⍄ፓᎯᐏᑱᓔᕈᖴᘜᚂዿ'}.get(c,' '),s.split()))
``` @proper vault got it a bit shorter by making `i` not take any kwargs
proper vault
#

nice

rugged sparrow
#

5 more chars off to get it to 200

proper vault
#

you can save 2 chars by adding ,o=''.join to the args of the main lambda and replacing the two calls

rugged sparrow
#

true

#
morse=lambda s,o=''.join:o(map(lambda c,i=lambda c,s,t:int(str(ord(c))[s:t]):{o('.-'[int(l)]for(l)in bin(i(a,2,9))[3:]):chr(i(a,0,2))for(a)in'ʏ᧠ᩆ᪜ʴ᭪ᯊᰰ˞᳿ᵙ᷄̉̒ừὖ῁‒͆͋͛↩∇≹⋟⍄ፓᎯᐏᑱᓔᕈᖴᘜᚂዿ'}.get(c,' '),s.split()))
``` current version
marsh void
#

does it decode or encode?

last locust
#

Decode @marsh void

#
>>> morse("- . ... -")
'TEST'```
glad cedar
#

hi

marsh void
#
>>> morse('... --- ...')```
#

hehe

last locust
#

😄

glad cedar
#

I'm new to python so yeah. Hi guys.

marsh void
#

Hey; this channel isn't intended for some beginner stuff, though; more like abusing C, python's parser and writing one-liners/golfing things.

glad cedar
#

oh

proper vault
#
-~a == a + 1
~-a == a - 1

kinda neat

marsh void
#

mhm

glad cedar
#

I'm not a fully begginer but I don't know what you class a begginer but I can do some random number maths quizzes

marsh void
#

!e
from dis import dis
dis('-~1'), 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 (2)
002 |               2 RETURN_VALUE
003 |   1           0 LOAD_NAME                0 (a)
004 |               2 LOAD_CONST               0 (1)
005 |               4 BINARY_ADD
006 |               6 RETURN_VALUE
marsh void
#

wait what

#

is that some magic

proper vault
#
  1           0 LOAD_NAME                0 (a)
              2 UNARY_INVERT
              4 UNARY_NEGATIVE
              6 RETURN_VALUE
  1           0 LOAD_NAME                0 (a)
              2 LOAD_CONST               0 (1)
              4 BINARY_ADD
              6 RETURN_VALUE
marsh void
#

oops

#

ah, yep

proper vault
#

the binary operation is faster

marsh void
#

yep

#

!e from timeit import timeit; t = lambda s: timeit(s, setup='a = 13'); print(t('a = -~a')); print(t('a += 1'))

night quarryBOT
#

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

001 | 0.08198634907603264
002 | 0.06853515096008778
sick hound
#

I have a little challenge for all of you guys

#
fizz = 0

while True:
    fizz += 1
    if fizz%3 == 0 and fizz%5 == 0:
        print("FizzBuzz")
    elif fizz%5 == 0:
        print("Buzz")
    elif fizz%3 == 0:
        print("Fizz")
    else:
        print(fizz)
    if fizz == 20:
        break

Make this a one liner

pure dew
#

simple ternary expression

print("\n".join(not x%5 and not x%3 and 'FizzBuzz' or not x%5 and 'Buzz' or not x%3 and 'Fizz' or str(x) for x in range(1, 21)))
``` edit: that actually looks a bit nicer and still works
vestal solstice
#
print('1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n11\nFizz\n13\n14\nFizzBuzz\n16\n17\nFizz\n19\nBuzz')
brazen geyser
#

~~```py
any(map(lambda i:print((('FizzBuzz','Fizz'),('Buzz',i))[i%3>0][i%5>0]),range(1,21)))

~~```py
any(print((('FizzBuzz','Fizz'),('Buzz',i))[i%3>0][i%5>0])for i in range(1,21))
```~~
```py
[print((('FizzBuzz','Fizz'),('Buzz',i))[i%3>0][i%5>0])for i in range(1,21)]
pure dew
#

oh nice

vestal solstice
#

why any and not []

brazen geyser
#

oo good call

#

what else

#

theres probably a way to flatten the tuple and index it once

#

just gotta figure out the logic

gilded orchid
#
[print((i%3<1)*'Fizz'+(i%5<1)*'Buzz'or i)for i in range(1,21)]
#

there's probably a way to use less brackets in this

marsh void
#

what’s that fizzbuzz thing

snow beacon
#
for i in range(1,21):print((i%3<1)*'Fizz'+(i%5<1)*'Buzz'or i)
marsh void
#

if divisible by 3, print Fizz, if divisible by 5, print Buzz, else print a number

#

yep?

snow beacon
#

It prints FizzBuzz if divisible by 15.

marsh void
#

I didn’t say elif there! haha

snow beacon
#

But you didn't put an else clause on the first if.

proper vault
#

for i in range(20):print(i%3//2*'Fizz'+i%5//4*'Buzz'or-~i)

#

It is not the shortest possible, but it is the shortest I know of

snow beacon
#

That looks pretty short.

gilded orchid
#

that integer division is smart, I spent ages looking for bitwise operators that could do it but didn't find anything

vestal solstice
#

what's the evidence that it's not the shortest @proper vault

proper vault
#

there is some website with these where someone got it down to 54 (when going up to 100)

vestal solstice
#

7 people with sub-57 solution

#

this one?

#

it counts multibyte characters as 1

#

this one doesn't have sub 58 solutions

#

the top 2 are likely cheating

vestal solstice
#
exec('潦⁲⁩湩爠湡敧ㄨ〰㨩牰湩⡴╩⼳㈯✪楆空⬧╩⼵㐯✪畂空漧⁲⭩⤱'.encode('u16')[2:])
```this is 56, exec doesn't even need a string wow
#

maybe they used 3 or 4-byte characters somehow

snow beacon
#

What do you mean?

vestal solstice
#

I'm saying lakmatiol solution is likely to be the shortest

#

the 54 byte solution, upgraded to 53 is from a site that counts several bytes as one, as long as it's one character

snow beacon
#

Ah, right.

vestal solstice
#

utf has 2,3 and 4 byte characters, 2 byte turns out to be simple

#

I don't know how to use the larger ones

vestal solstice
#

Oh wait, they have 58 with range 100, how could I miss that

gilded orchid
#

I have a feeling there could be some crazy way to do something like 'FizzBuzz'[something:]or i
where something somehow gets the right string

#

actually wait you would need something on the other side as well

sick hound
#

'FizzBuzz'[4*(i%3>0):4*(i%5==0)+4]or i seems to work

gilded orchid
#

Oh wow

sick hound
#
(i%3<1)*'Fizz'+(i%5<1)*'Buzz'or i
'FizzBuzz'[4*(i%3>0):4*(i%5<1)+4]or i```
#

ok it's actually longer than if you do it the other way

gilded orchid
#

I have a feeling there is a way to shorten both parts of the slicing

#

the right part can be ~-i%3//2*4 I'm pretty sure

sick hound
#
>>> ['FizzBuzz'[~-i%3//2*4:4*(i%5<1)+4]or i for i in range(20)]
['Buzz', 'Fizz', 'Fizz', 3, 'Fizz', 'FizzBuzz', 6, 'Fizz', 'Fizz', 9, 'FizzBuzz', 'Fizz', 12, 'Fizz', 'Fizz', 'Buzz', 'Fizz', 'Fizz', 18, 'Fizz']```
#

nope

gilded orchid
#

Right part of the slice, not left

sick hound
#

oh

gilded orchid
#

wait oops no that's wrong I think

sick hound
#
>>> ['FizzBuzz'[4*(i%3>0):~-i%3//2*4]or i for i in range(20)]
['Fizz', 1, 2, 'Fizz', 4, 5, 'Fizz', 7, 8, 'Fizz', 10, 11, 'Fizz', 13, 14, 'Fizz', 16, 17, 'Fizz', 19]```
#

for reference here's the correct answer ```py

['FizzBuzz'[4*(i%3>0):4*(i%5==0)+4]or i for i in range(20)]
['FizzBuzz', 1, 2, 'Fizz', 4, 'Buzz', 'Fizz', 7, 8, 'Fizz', 'Buzz', 11, 'Fizz', 13, 14, 'FizzBuzz', 16, 17, 'Fizz', 19]```

gilded orchid
#

oh ok

#

I'll work on this later to see if I can make it actually work

vestal solstice
#

You need to start with i=1 for these

#

'FizzBuzz'[i%-3&4:12&8-i%5]

#

Stolen

proper vault
#

That one is actually one char shorter than the multiplication, but you need to start from 1, which adds 2 characters

vestal solstice
#

But saves 1 on incrementing

proper vault
#

Oh, I miscounted, it is equally long

vestal solstice
#

Or not, I don't know what we're comparing

proper vault
#

But it ends up 1 char longer, unless it is acceptable to start from 0

vestal solstice
#

Maybe start with 2 and decrement

gilded orchid
#

I might make a bruteforcer to see if [i%-3&4:12&8-i%5] can be any shorter

#

although it does look pretty optimal

#

where did you steal find that from? @vestal solstice

red timber
#

Don’t try this at home, kids!

rugged sparrow
#

anyone want to help me implement this py d = {'a': 100, 'b':200} a, b, c = d #a = 100, b = 200, c = None

brazen geyser
#
def dict_iter(self):
  iterator = iter(self.values())
  while True:
    yield next(iterator, None)
#

replace tp_iter with that

grizzled cloak
#
d = {'a': 100, 'b':200}
b, a, c = d #b = 100, a = 200, c = None```
#

or

d = {'a': 100, 'b':200}
b, a, c = d #a = 100, b = 200, c = None```
rugged sparrow
#

@grizzled cloak @brazen geyser the goal is to make it set vars with the same name as a key to the corresponding value

vestal solstice
#

Oh snap

brazen geyser
#

get the line of code using inspect and linecache

#

then regex the names out

rugged sparrow
#

yea thats what i was about to try tbh

brazen geyser
#

how to handle a,b,c=d;e,f,g=d

#

?

#

then you gotta look into the bytecode

rugged sparrow
#

hmm true

#

honestly looking at the bytecode will prob be best in the long run

proper vault
#

imo, a nicer way would be {'a': foo, 'b': bar} = {'a': 10, 'b': 20}; foo,bar==(10,20)

rugged sparrow
#

or py foo:'a', bar:'b' = {...}

proper vault
#

ye, that would work too

#

though I would reverse the order

rugged sparrow
#

eh first imma try to get the var names

proper vault
#

also, couldnt you do sth like locals().update({varname: targetdict.get(varname) for varname in the_variables_assigned_t}) (probably not locals(), but you get the idea

rugged sparrow
#

yea

#

but if i can get the variables assigned to i can just build and return a list iterator that has all the vals in the right order

#
from . import _utils as utils
import inspect
import dis

@utils.edit(dict, 'tp_iter')
@utils.nullwrap
def dict_iter(self):
    last_frame = inspect.currentframe().f_back
    for instruction in dis.Bytecode(last_frame.f_code):
        if instruction.opname in ['STORE_FAST', 'STORE_GLOBAL', 'STORE_NAME', 'STORE_DEREF']:
            yield self.get(instruction.argval)
``` this mostly works
#
from py_future import expdict
>>> def func(**kwargs):
...     opt1, opt2 = kwargs
...     return opt1, opt2
... 
>>> func(opt1=10, opt2=20, opt3=30)
(10, 20)
>>> ```
brazen geyser
#

@rugged sparrow dont foget about f_lasti to get index of last instruction

#

for disambiguation purposes

rugged sparrow
#

Ah yeah you're right

lament ibex
snow beacon
#

I like. It also links to an HTML variant that inspired it.

gilded orchid
#

Is it possible to exec a string as code in f-strings?

distant wave
#

!e ```py
a = 'print(1),"2"'
print(f"{exec(a)}")

night quarryBOT
#

@distant wave :white_check_mark: Your eval job has completed with return code 0.

001 | 1
002 | None
distant wave
#

?

gilded orchid
#

I meant without using exec or eval

#

actually nvm

#

what builtins/dunders (if any) can be made using the characters lfisp_?

thin trout
#

You can use the same character many times?

high garnet
#

no builtins, apparently

#
>>> [name for name in dir(builtins) if all(char in set('lfisp_') for char in name)]
['_']
chrome moth
#
def PYTHON(PYTHON):
    def PYTHON(*PYTHON):
        return ''.join(*PYTHON)

    return PYTHON


class PYTHON:

    def __new__(PYTHON):
        return PYTHON.PYTHON('PYTHON')

    @PYTHON
    def PYTHON(PYTHON):
        return PYTHON


print(PYTHON())
pure dew
#

the fuck

chrome moth
#

PYTHON!

pure dew
#

this isnt a shitposting channel @chrome moth

chrome moth
#

No shit

pure dew
#

wasnt sure you realized that

chrome moth
#

?

#

How is what I posted a shitpost

tropic night
#

whats going on here?

chrome moth
#

I'm not sure I just posted some "General Pyhon weirdness" and got called a shit poster rofl, please correct me if this isn't the place to post such snippets.

glacial rampart
#

half the stuff i've seen here could be construed as a shitpost

tropic night
#

I was more thinking about why you would comment like that @pure dew. like, I do not see how useful your post is @chrome moth but i would not call it out

glacial rampart
#

it's just dumb obfuscated code that serves no practical value but is fun to think about and read

#

like a lot of the on-topic content here

pure dew
#

It's not functional at all

glacial rampart
#

it prints "PYTHON"

pure dew
#

@chrome moth yo I'm sorry

#

I misread the code

tropic night
#

cool.. 😄

#

ill get out of here before i see something that makes my head explode 😄

pure dew
#

it's late ya'llq imma go to bed so i wont be a grumpy bear

chrome moth
#

all good

marsh void
#

@chrome moth that's why I avoid same variable names haha

glacial rampart
#

dapper misreading the code is just more proof it belongs in this channel 😏

sick hound
#

@glacial rampart i hope you realise that obfuscation and code gore are listed in the channel topic as well

#

:)

glacial rampart
#

that's what i mean @sick hound

#

:)

sick hound
#

sorry, I meant to ping @pure dew

#

my bad

next mist
#

im so glad i switched to notepad as my editor, its clean white and black makes it so easy to see everything without all the colors confusing my eyes

pure dew
#

@sick hound Yea that was my bad all around

distant kite
#

What the actual f██k

next mist
#

yeah what the fack

#

@distant kite how dare anonymous make that mistake

distant kite
#
from mrmister import code

code.is_confusing = True
next mist
#

no no, i think youre just tired or something, its pretty straight foward

#

it takes your name and makes you a new nickname

distant kite
#

Oh, shut up. That thing is unreadable

next mist
#

othan than cases i think its pretty pythonic

distant kite
#

Pythonic or not, its unreadable

next mist
#

i think thats a little harsh, as you can see by its file name, its perfect_code

distant kite
#

I didn't even notice that

#

There is one thing worse than the code though: NOTEPAD

next mist
#

no, objectively wrong, its the best way to write code, no confusing colors or indent lines

odd blade
#

notepad is cool

next mist
#

and the perfect code is so simple, you give it your name and it give you the better name

BabBoop>>>MrMister
your name is MMurgle```
distant kite
#

Notepad++ is good.
VSCode is better.
Notepad can burn in hell for programming

distant kite
#

Like this?

next mist
#

yes exactly, im glad youve embraced the perfect code

distant kite
#

Notepad can still burn

next mist
#

pft notepad > sublime > VSCode > Notepad++

distant kite
#

Where notepad is worst and notepad ++ is best

next mist
#
not_correct = "pft notepad > sublime > VSCode > Notepad++"
correct = not_correct.replace(">", "is better than")
print (correct)
#

pft notepad is better than sublime is better than VSCode is better than Notepad++

distant kite
#

.replace("VSCode", "VSCode is best")

rugged sparrow
#

@distant kite you think that is bad?

#

you should scroll up this channel a bit

next mist
#

you better be posting code soup

rugged sparrow
#
morse=lambda s,o=''.join:o(map(lambda c,i=lambda c,s,t:int(str(ord(c))[s:t]):{o('.-'[int(l)]for(l)in bin(i(a,2,9))[3:]):chr(i(a,0,2))for(a)in'ʏ᧠ᩆ᪜ʴ᭪ᯊᰰ˞᳿ᵙ᷄̉̒ừὖ῁‒͆͋͛↩∇≹⋟⍄ፓᎯᐏᑱᓔᕈᖴᘜᚂዿ'}.get(c,' '),s.split()))
``` @distant kite @next mist  morse code decoder
next mist
#

yeah thats the one

rugged sparrow
#

i can find minesweeper one sec

#
[[[[[t.update(n=t['n']+b[i+x][j+y]['d'])for y in[-1,0,1]for x in[-1,0,1]if all(map(lambda v:v>=0and v<len(r),[i+x,j+y]))]for j,t in e(r)]for i,r in e(b)],f(b,0,0,8),[*iter(lambda h='\x1b[':all(all((t['d']&1and t['d']&2)or t['d']&4for t in r)for r in b)or[p(h+'2J'),[p('',*[h+f'{7if t["d"]&8else 0}m{t["n"]if t["d"]&4else"F"if t["d"]&2else"#"}{h}0m'for t in r])for r in b],p(f'\n{h}7mMove (wasd), Flag (f) or Clear (c):{h}0m '),[*[(lambda t,c,n:lambda:[f(b,*c,8),f(b,c[0]+n[0],c[1]+n[1],8)]if c[0]+n[0]>=0and c[0]+n[0]<len(b[0])and c[1]+n[1]>=0and c[1]+n[1]<len(b[0])else 0)(*g(b,e),n)for n in zip([-1,0,1,0],[0,-1,0,1])],lambda:f(b,*g(b,e)[1],2),lambda:exit('You Lose')if g(b,e)[0]['d']&1else f(b,*g(b,e)[1],4)if g(b,e)[0]['n']else r(b,f,r,*g(b,e)[1],[]),p]['wasdfc'.find(__import__('sys').stdin.read(1))]()][0],1)],exit('You win')]for e,p,b,f,g,r in[(enumerate,print,(lambda s:[[dict(d=__import__('random').choice([0]*s+[1]*(s//3)),n=0)for()in[()]*s]for()in[()]*s])((lambda i:int(i)if i.isnumeric()and int(i)>2else(exit('Invalid Size')))(input('Board Size (Min 3): '))),lambda b,x,y,v:b[x][y].update(d=b[x][y]['d']^v),lambda b,e:sorted([[(t,(i,j))for j,t in e(r)if t['d']&8]for i,r in e(b)])[-1][0],lambda b,f,r,i,j,l:[[[f(b,i+x,j+y,4),r(b,f,r,i+x,j+y,l+[(i+x,j+y)])if b[i+x][j+y]['n']==0and(i+x,j+y)not in l else 0]if not b[i+x][j+y]['d']&4and not b[i+x][j+y]['d']&1else 0]for y in[0,1,-1]for x in[0,1,-1]if all(map(lambda v:v>=0and v<len(b[0]),(i+x,j+y)))])]]``` @distant kite take a look
distant kite
#

HOW IS THAT MINESWEEPER?!?!

rugged sparrow
#

spooky magic

#

run it in a repl

distant kite
#

No

#

Its gonna lit something on fire

next mist
#

worked for me haha

#

thats stupid

#

its ugly, but it works

rugged sparrow
#

its beautiful

next mist
#

nah its so hard to actually tell whats going on

#

i expected something pretty like a numpy array looking thing

#

not that...thing

rugged sparrow
#

oooohh

#

youre on windows

next mist
#

i mean arnt most people

rugged sparrow
#

i mean it works in WSL

pure dew
#

works on linux

next mist
pure dew
#

windows console is yikes

rugged sparrow
#

put __import__('colorama').init() at the top of the file

#

@next mist ^

#

should make it work

next mist
#

okay thats way better looking

#

even without the world surf league

distant kite
#

Screenshot?

next mist
#

other than no color so i cant see what block is highlighted

rugged sparrow
#

fml

#

i hate windows console

distant kite
#

Try cmd

rugged sparrow
#

^

next mist
#

nope

#

same thing

pure dew
#

dont think cmd supports ansi either

#

try cmder

#

or conemu

rugged sparrow
#

colorama should have fixed ittttt

next mist
#

eww, downloading stuff? thats work

pure dew
#

suit yourself

next mist
#

i understand what its supposed to be haha

pure dew
#

cmder is a much better console than cmd/pshell for all purposes

rugged sparrow
#

problem is windows removed some of the apis that colorama used in the newest couple updates

pure dew
#

did they really?

#

lmao

#

this is why ansi sequences reign supreme

distant kite
#

Then it's time to fire up a VM I guess

pure dew
#

what

#

if you have a relatively new build of windows 10, you can enable the windows subsystem for linux (WSL) and download ubuntu directly in windows

distant kite
#

Or just do that

pure dew
#

you run it like you would powershell

rugged sparrow
#

yea wsl supports ansi

pure dew
#

does it support in the default conhost tho?

#

i use alacritty so idk

distant kite
#

Quick question, could anyone look at my post in #303934982764625920? It's not really esoteric, but it's my first public project

rugged sparrow
#

Wsl has a seperate shell program

pure dew
#

oh ah

rugged sparrow
#

@distant kite sure

distant kite
#

thanks :)

thin trout
#

It isn't a separate shell

#

It just launch conhost with WSL

rugged sparrow
#

Oh really? Honestly hadn’t looked much into it

pure dew
#

windows console api is wack, who knows

thin trout
#

Yeah, same as for openssh and things like that

pure dew
#

i'll stick with stdout/stdin and good old \x1b[34m

thin trout
#

It is the formatting character type of thing, isn't it?

rugged sparrow
#

ANSI escape sequences yea

thin trout
#

Yeah, I tried that, it is kinda hard to deal with

#

And does it work on windows though?

rugged sparrow
#

nope

#

cause windows likes to be special

thin trout
#

Haha, it is special indeed

distant kite
#

Time to fire up a VM now then?

rugged sparrow
#

if you want man

rugged sparrow
#
if not x == x:
  print(1)
``` add code above this that creates the variable `x` so that this snippet runs. (no defining classes/no `type`)
edgy kelp
#

good old banana

rugged sparrow
#

bingo

vestal solstice
#

what

#

ah

snow beacon
#

x = float('nan')

#

Stand by for a method without explicitly calling float

#

x = 1e309 - 1e309

#

(Might depend on your implementation. If it doesn't work add some zeroes)

distant wave
#

!e ```py
a = [1, 2, 3, 4, 5, 6]

a.extend(a)
print(a)
def extend(dest, src):
for i in src:
dest.append(i)
#extend(a, a)

night quarryBOT
#

@distant wave :white_check_mark: Your eval job has completed with return code 0.

[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]
sick hound
#

!e

en = lambda x:list(enumerate(enumerate(enumerate(x))))
x = range(10)
print(en(en(en(en(en(en(en(x))))))))
night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 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, (1, (1, (1, (1, (1, (1, (1, (1, (1, (1, (1, (1, (1, (1, (1, (1, (1, 1))))))))))))))))))))), (2, (2, (2, (2, (2, (2, (2, (2, (2, (2, (2, (2, (2, (2, (2, (2, (2, (2, (2, (2, (2, 2))))))))))))))))))))), (3, (3, (3, (3, (3, (3, (3, (3, (3, (3, (3, (3, (3, (3, (3, (3, (3, (3, (3, (3, (3, 3))))))))))))))))))))), (4, (4, (4, (4, (4, (4, (4, (4, (4, (4, (4, (4, (4, (4, (4, (4, (4, (4, (4, (4, (4, 4))))))))))))))))))))), (5, (5, (5, (5, (5, (5, (5, (5, (5, (5, (5, (5, (5, (5, (5, (5, (5, (5, (5, (5, (5, 5))))))))))))))))))))), (6, (6, (6, (6, (6, (6, (6, (6, (6, (6, (6, (6, (6, (6, (6, (6, (6, (6, (6, (6, (6, 6))))))))))))))))))))), (7, (7, (7, (7, (7, (7, (7, (7, (7, (7, (7, (7, (7, (7, (7, (7, (7, (7, (7, (7, (7, 7))))))))))))))))))))), (8, (8, (8, (8, (8, (8, (8, (8, (8, (8, (8, (8, (8, (8, (8, (8, (8, (8, (8, (8, (8, 8))))))))))))))))))))), (9, (9, (9, (9, (9, (9, (9,
... (truncated - too long)

Full output: too long to upload

pure dew
#

that looks awesome on mobile

grizzled cloak
#

Hahah I though you were setting "en" to lambda and typehinting x as a list of enum hahah

#

Mobile formating suucks

sick hound
#

yeah

#

I just used en so I didn't have to type enumerate 80k times

thin trout
#

@edgy kelp banana? roothink

snow beacon
#

Probably ba NaN a

thin trout
#

Ahh haha

pure dew
thin trout
#

What is all that white?

pure dew
#

white theme >.>

thin trout
#

Why do you have to do that to yourself?

pure dew
#

because i like it

rugged sparrow
#
morse=lambda s:"".join(map(lambda c,i=lambda c,s,t:int(str(ord(c))[s:t]):{bin(i(a,2,9))[3:].translate(48*a+'.-'):chr(i(a,0,2))for(a)in'ʏ᧠ᩆ᪜ʴ᭪ᯊᰰ˞᳿ᵙ᷄̉̒ừὖ῁‒͆͋͛↩∇≹⋟⍄ፓᎯᐏᑱᓔᕈᖴᘜᚂዿ'}.get(c,' '),s.split()))
``` @proper vault got morse code translator shorter with `str.translate`
proper vault
#

nice

rugged sparrow
#

the 48*a is padding for the translate table

brazen geyser
#

wow lol

rugged sparrow
#

@brazen geyser any suggestions on golfing it even further?

brazen geyser
#

will let you know if i do. my brain is fried atm

rugged sparrow
#

aight

sick hound
#

I mean you could make morse m but u don't think that's what you were asking

rugged sparrow
#

yea

#
morse=lambda s:"".join(map(lambda c,i=lambda c,s,t:int(f'{ord(c)}'[s:t]):{bin(i(a,2,9))[3:].translate('.-'*25):chr(i(a,0,2))for(a)in'ʏ᧠ᩆ᪜ʴ᭪ᯊᰰ˞᳿ᵙ᷄̉̒ừὖ῁‒͆͋͛↩∇≹⋟⍄ፓᎯᐏᑱᓔᕈᖴᘜᚂዿ'}.get(c,' '),s.split()))
``` cut it down to 195
rugged sparrow
#
morse=lambda s:"".join(map(lambda c:{bin(int(str(ord(a))[:-2]))[3:].translate('.-'*25):chr(ord(a)%100)for(a)in'ڈǙॆ՟ࠜ̉ʦثࣨ஥кͳƀϙۺңਜ૥୊ኍ཮ෟഘವዶᘗឨᡱᣌȵঢ੫Ӵčݎֿ'}.get(c,' '),s.split()))
``` new encoding method, got rid of `i` lambda
static gale
#

lambda, lambdas everywhere

#

man it's so fun

rugged sparrow
#
morse=lambda s:"".join({bin(a//100)[3:].translate('.-'*25):chr(a%100)for(a)in map(ord,'ڈǙॆ՟ࠜ̉ʦثࣨ஥кͳƀϙۺңਜ૥୊ኍ཮ෟഘವዶᘗឨᡱᣌȵঢ੫Ӵčݎֿ')}.get(c,' ')for(c)in s.split())
``` even shorter (157) @proper vault
pure dew
#

any ya'll seen CodeKlavier

#

it's not esoteric code per-se, but the goal is use a midi keyboard as a computer interface

rugged sparrow
#

what?

pure dew
#

Right now it's like a midi player that you control with code using the midi player itself instead of a keyboard https://youtu.be/6QEhnffDlk8

The CodeKlavier is a system which enables a pianist to code through playing the piano as a performative experience. The CodeKlavier repurposes the traditional piano to serve as both a live coding interface and as a musical instrument. This is a performance of our "Hybrid"

T...

▶ Play video
rugged sparrow
#

huh. neat

marsh void
#
(lambda gd: print(gd.api.Editor().add_objects(*(gd.api.Object(target_group_id=n, x=30, y=n*30, duration=1).set_id('trigger:move').set_easing('easing:ease_in_out') for n in range(1, 101))).dump()))(__import__('gd'))``` I have added builder style for my library and did this for no reason
static gale
#

er_svar_riktig = lambda self, svar: svar == str(self.riktig_svar)
Inside of a class. TA is going to freak out but that's okay

#
__str__ = lambda self: f"\nSpørsmål:\n\n{self.sporsmaal}" + \
                       "".join(map(lambda t: f'\n\n{t[0]}:\t{t[1]}', enumerate(self.svaralt)))```
snow beacon
#

That thing is in production code?

marsh void
#

I hope not lol

sick hound
#
def pic_th():
    global screenheight, screenwidth, res, drawfile
    window = pyglet.window.Window(screenwidth, screenheight)

    def init():
        drawgif('sans.gif')

    def drawimg(selected):
        pyglet.resource.path = [res]
        pyglet.resource.reindex()
        bg = pyglet.resource.image('greenscreen.png')
        bg.width, bg.height = screenwidth, screenheight
        image = pyglet.resource.image(selected)
        move = window.width - image.width
        @window.event
        def on_draw():
            window.clear()
            pyglet.gl.glEnable(pyglet.gl.GL_BLEND)
            bg.blit(0, 0)
            pyglet.gl.glBlendFunc(pyglet.gl.GL_SRC_ALPHA, pyglet.gl.GL_ONE_MINUS_SRC_ALPHA)
            image.blit(0 + move, 0)
            pyglet.app.exit()

    def drawgif(selected):
        pyglet.resource.path = [res]
        pyglet.resource.reindex()
        animation = pyglet.resource.animation(selected)
        bg = pyglet.resource.image('greenscreen.png')
        bg.width, bg.height = screenwidth, screenheight
        sprite = pyglet.sprite.Sprite(img=animation)
        move = window.width - sprite.width
        sprite.x += move
        @window.event
        def on_draw():
            window.clear()
            pyglet.gl.glEnable(pyglet.gl.GL_BLEND)
            bg.blit(0, 0)
            pyglet.gl.glBlendFunc(pyglet.gl.GL_SRC_ALPHA, pyglet.gl.GL_ONE_MINUS_SRC_ALPHA)
            sprite.draw()
            pyglet.app.exit()
    init()
    while True:
        time.sleep(1 / 600)
        if drawfile:
            if drawfile.endswith('.gif'):
                drawgif(drawfile)
                drawfile = ''
            elif drawfile.endswith('.png'):
                    drawimg(drawfile)
                    drawfile = ''
        pyglet.app.run()```
grizzled cloak
#

whats a short way to generate the string '0123' for f(4)?

#

something better than
''.join(map(str, range(n)))

#

because thats just asking to be shortened

#

ok i guess i should post the entire challenge,
a function that takes a string and a number and then replaces the first n letters of that string with 0-n

#
>>> f("Hello World", 4)
'0123o World'```
#

this is my shortest so far:
f=lambda s,n:''.join(map(str,range(n)))+s[n:]

sick hound
#

what happens if you get numbers higher than 9?

rugged sparrow
#

@grizzled cloak if the function wont get numbers higher than nine, then this works py f=lambda s,n:'0123456789'[:n]+s[n:]

zealous widget
#
f=lambda s,n:('0123456789'*(n//10+1))[:n]+s[n:]

if you want the string to repeat for higher n?

grizzled cloak
#

tbh i have no idea haha it was someones question

crystal mica
#

hmm

#
f=lambda s,n:''.join(map(str,range(n)))+s[n:]```
#

Shorter by a tiny bit?

#

wait that's literally what leterax has lol

grizzled cloak
#

hehe

edgy kelp
#

made a random generator...

import threading
import time

THREAD_AMOUNT = 2000
loaded = False
def b():
    while not loaded: time.sleep(0.3)
    print("1", end="0")

for thread in [threading.Thread(target=b) for _ in range(THREAD_AMOUNT)]:
    thread.start()
loaded = True
grizzled cloak
#

@proper vault added a spacing arg to your shortened version of mine:

h = lambda n,s:{print((('*'+s*' ')*-~i).center(n*(s+1),' '))for i in range(n)}```
proper vault
#

I had to, sorry

h = lambda n,s:{print((('*'+s*' ')*-~i).center(n*-~s,' '))for i in range(n)}
grizzled cloak
#

haha fair enough

#

but isnt it the exact same len? haha

#

-1!!!

proper vault
#

Saves 2, I loose () and replace +1

marsh void
#

@edgy kelp ouch.

winter trail
#

does anyone know a python bot scirpt that dms everyone in a server

snow beacon
#

This isn't the channel for that.

hollow patrol
#
(lambda f: f(f))(lambda x: print(5 * 4), x)
``` Does this work?
#

That's my attempt at a Y combinator.

rugged sparrow
#

no that doesnt work

marsh void
#

@hollow patrol you mean that?

>>> (lambda f: f(f))(lambda x: (print(5 * 4), x))
20
(None, <function <lambda> at 0x10eac7268>)```
hollow patrol
#

@marsh void Right, yeah that doesn't work

#
(lambda f: f(f))(lambda x: print(5 * 4), x())
#

That?

marsh void
#

that is well

#

recursive?

#

what is Y combinator?

#

@hollow patrol

proper vault
vestal solstice
#

Y combinator is how you make recursion

#

even if the language forbids it or something

proper vault
#

it is a specific way to create recursive functions, there are other ways

marsh void
#

second should work imo

#

when you call x after

proper vault
#

essentially, Y(f) beta reduces to f(Y(f)),

marsh void
#
(lambda f: f(f))(lambda f: (input('test '), f(f))[0])``` that's inf recursion right
#

and what are we trying to achieve

proper vault
#

in python, you really do not need a Y combinator

hollow patrol
#

I'm just trying to achieve using an esoteric way for recursion

#

We do things that you don't need in Python

marsh void
#

(lambda f: f(f))(lambda f: (print('test'), f(f)))

hollow patrol
#

Yep

#
(lambda f: f(f))(lambda x: print(5 * 4), x(f))
#

I actually do have a use for lambdas

#

Not the single-expression ones, but more complex ones

marsh void
#

this one doesn’t work

#

wrap in ()

hollow patrol
#
(lambda f: f(f))((lambda x: print(5 * 4)), x(f))
#
lt.function(lambda v: print(5 * 4), v.__ref__())
marsh void
#

is that lambdatools haha

#

λ

hollow patrol
#

yes

#

I actually use it a fair amount when I need complex logic in lambdas and a decorator won't work

proper vault
#

What are you using lambdas for?

marsh void
#

for everything

#

he's making lambdas like actual functions I'd say

#

so you can have loops etc

proper vault
#

I see

lament ibex
#

what's lambdatools? can't find anything relevant on google

hollow patrol
#

It's a small project I'm working on @lament ibex

#

It gives lambdas some abilities like async lambdas,recursion, conditionals, loops

#

Of course, most/all of these things can be done with extreme python hacks, but I find mine more readable

#

It's on my github

lament ibex
#

Sounds cool, might have a look

#

Do you have a link?

hollow patrol
#

Sure

#
    myfunction = function(lambda v: ( #define function as ANONYMOUS function set to variable myfunction
        setattr(v, x = 0), #set x to 0
        (yield from during(lambda v: v.x < 6, lambda v: ( #loop while x < 6 with a yield inside the loop
            setattr(v, x = v.x + 1), #increment x by 1
            (yield v.x) #yield x
        )))
    ))
``` It makes lambdas less esoteric
thin trout
#

When is the PyPi release?

#

:D

tribal moon
#
(lambda x: x(int(__import__('sys').stdin.readline()).__rmul__(int(__import__('sys').stdin.readline()))))(lambda y: __import__('sys').stdout.write(y.__str__()).__str__()[:-1])

multiplies 2 numbers without using print nor input in 1 line

#

or *

#

just garbage

snow beacon
#

Someone made a program to multiply numbers using string manipulation.

marsh void
#

^

snow beacon
grave rover
#

@tribal moon shorter: py (lambda r,w:w(int(r()).__rmul__(int(r()))))(*(lambda s:s.stdin.readline,s.stdout.write)(__import__("sys"))

tribal moon
#

Haha

proper vault
#
radix_sort = lambda nums,base:(lambda n:(lambda f,*a:f(f,*a))(lambda f,nums,idx:f(f,sum([[num for num in nums if get_digit(num,idx,base)==digit]for digit in range(base)],[]),idx+1) if idx<n else nums,nums,0))(ceil(log(max(nums),base)))
marsh void
#

oml

#

you haven't reduced some spaces tho

gilded orchid
#

what's the shortest way to get rid of the first occurunce of a specific number in a list?

sick hound
#

remove?

#
>>> x = [1, 2, 3, 1, 2, 3, 3, 2, 1, 3, 2, 4, 1]
>>> x
[1, 2, 3, 1, 2, 3, 3, 2, 1, 3, 2, 4, 1]
>>> x.remove(2)
>>> x
[1, 3, 1, 2, 3, 3, 2, 1, 3, 2, 4, 1]```
gilded orchid
#

will that work in recursive lambdas?

#

(eg: f=lambda x:f(x.remove(2)))

proper vault
#

no, it returns None

gilded orchid
#

oh

proper vault
#

you can do x.remove(a)or x

#

which will return x with the remove applied to it

#

but you need a named reference to the list

gilded orchid
#

oh ok that will work, thanks 🙂

#

also I made this terrible thing to sort a list of unique numbers

f=lambda a,b=[]:(f({*a}-{min(a)},b+[min(a)])if len(a)else b)
sick hound
#

what about sorted

#
f=sorted```
young wyvern
#

hi

#

i want help with Microsft azure search

#

image and wb

#

I am clueless

#

If you know of guides/experience do let me know

rugged sparrow
#

@young wyvern not the right channel for that

sick hound
#

this channel is for help with things like making 2 + 2 equal 5

#
>>> from ctypes import *
>>> cast(id(4), POINTER(c_int))[6] = 5
>>> 2 + 2
5```
thin trout
#

Meh

#

What if I do 3 + 1 now? 😄

vague gust
#

5

proper vault
#

and guess what 3 + 1 - 1 will be

thin trout
#

It was rethorical joe :D

#

4?

proper vault
#
>>> 3 + 1- 1
5
#

no, 5 still

#

4 - 1 is also 5

#

4 + 1 is 6

#

doing ~4 does weird things

thin trout
#

Oh yeah, 5, it is just too late to do maths now 😄

proper vault
#

overall, this seems to break ~ entirely

thin trout
#

What is even ~? Is it some kind of binary inverter type of thing?

proper vault
#

binary complement, essentially invert all bits

#

in python it ends up -(i+1) == ~i

sick hound
#
>>> ~4
-6
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: raw write() returned invalid length 5 (should have been between 0 and 4)
-6```
muted locust
#

@proper vault is that overloaded when using with pandas? I just know that ~ negates a series of true/false

proper vault
#

yep, you can overload it with __invert__

muted locust
#

so the operator used in pandas has been overloaded - here i mean - it's acting in a way one might not expect given the outline of it in this thread

gilded orchid
#

shortest way to flip a string of binary digits? (eg: "1000" -> "0111")

thin trout
#

~str(int(s))

proper vault
#
''.join('10'[int(e)] for e in s)
``` not sure how to use `~` here, as bin on negative numbers does not do 2s complement
gilded orchid
#

I'm trying to make the shortest lambda to increment a binary string, without using bin, if anyone has any ideas

gilded orchid
#
f=lambda x:(x[:x.rfind("0")]+"1")[::-1].zfill(len(x))[::-1]

I made this horrible thing but it doesn't work if the input is all 1's

#

(also .rpartition("0") might be useful but I can't work out how to use it

vestal solstice
#

@gilded orchid you can subtract ord from 97

#

Not sure if it's short

#

Like it looks fine, just add 0 to x before doing rfind

gilded orchid
#
>>> f=lambda x:(x[:("0"+x).rfind("0")]+"1")[::-1].zfill(len(x))[::-1]
>>> f("111")
'100'
vestal solstice
#

Yeah :/

proper vault
#

you could do sth like this

f=lambda x:(lambda a,b,c:a+'1'+'0'*len(c))(*x.rpartition('0'))
#

but that is quite long

gilded orchid
#
f=lambda x:(a:=x.rpartition("0"))[0]+"1"+"0"*len(a[2])
proper vault
#

ah, forgot about walrus

gilded orchid
#

I wonder if there's a way to do it without walrus (somehow getting the number of 1's at the end of the string in a short way)

#
f=lambda x:x.rpartition("0")[0]+"1"+"0"*len(x.split("0")[-1])

I did it without walrus but it's longer

vestal solstice
#

Rsplit?

gilded orchid
#

wdym?

vestal solstice
#

Rsplit with 1 is like rpartition

#

I don't know

proper vault
#

it would save a few in the lambda solution

gilded orchid
#

i'm confused, how?

proper vault
#

you could skip the b parameter, as rsplit('0',1) would only return 2 things

gilded orchid
#

oh right

#

wait i'm still confused

vestal solstice
#

It means you need "0"+ again

#

I'm being stupid because flu

gentle pagoda
#

is there a way of overloading operators on functions?

wispy horizon
#

You can create a function object that has its own operators

#

I think it's possible

#

Then call the object like a function

gentle pagoda
#

how would that work?

#

i only want it on specific functions btw

proper vault
#
def function_with_overloaded_operators(fun: Callable, operations: Dict[str, Callable]):
  return type('', (), {'__call__': lambda self, *a:fun(*a), **operations})()
``` sth like this perhaps
#
In [11]: super_print = function_with_overloaded_operators(print, {"__add__": lambda s,o: s(o)})

In [12]: super_print + "Hello World!"
Hello World!
rugged sparrow
#

ooooo

#

i like that

proper vault
#

could make it a decorator like so

def with_operators(**operations: Dict[str, Callable]):
  def decorator(fun: Callable):  
    return type('', (), {'__call__': lambda self,*a: fun(*a), **operations})()
  return decorator
#

ah, minor error I just noticed

#
In [11]: @with_operators(__add__=lambda s,o:s(o))
    ...: def a(o):
    ...:     print(o)
    ...:

In [12]: a + 4
4

In [13]: a(4)
4
snow beacon
#

What's the shortest Hello World that doesn't use any ( or )?

proper vault
#

import __hello__ maybe

snow beacon
#

That's a good one. There I was puzzling the best way to call functions.

snow beacon
#

!e python f=lambda _:"Hello world" @print @f class t:pass

night quarryBOT
#

@snow beacon :white_check_mark: Your eval job has completed with return code 0.

Hello world
snow beacon
#

No brackets.

rugged sparrow
#

clever

#

@(lambda f:...) doesnt work sadly

marsh void
#

wait what

#

!e
@print
def f(): return 13

night quarryBOT
#

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

<function f at 0x7f752375f1f0>
marsh void
#

ah, makes sense

brazen geyser
#

!pep 614

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

Draft

Python-Version

3.9

Created

10-Feb-2020

Type

Standards Track

brazen geyser
#

@rugged sparrow maybe some day

#

some day not too far away

rugged sparrow
#

one can hope

#

!e ```py
d = lambda x:x

@print
@d(lambda val:'Hello World')
class a:pass

night quarryBOT
#

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

Hello World
rugged sparrow
#

that works

snow beacon
#

I was trying to avoid brackets.

rugged sparrow
#

fair

brazen geyser
#

my hope is if that pep is implemented youd be able to just do @lambda: blahblah outright

rugged sparrow
#

same

snow beacon
#

A slightly golfed version of the unbracketed one:

f=lambda _:"Hello world"
@print
@f
class _:0```
sick hound
#

wait python has lambda

#

oh shit thats neat

#

!e
print ("Hello world ")

night quarryBOT
#

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

Hello world
sick hound
#

wow

#

@snow beacon how do you get your text like that

snow beacon
#

I use ```python
Lines of code go here

#

You can omit the python on the first line if you don't care about syntax highlighting.

fallen heath
#

!e
import hello

night quarryBOT
#

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

Hello world!
sick hound
#

!e import this

#

shoot

snow beacon
#

Do you need the codeblock?

whole kiln
#

No

rugged sparrow
#

!e import this

night quarryBOT
#

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

001 | The Zen of Python, by Tim Peters
002 | 
003 | Beautiful is better than ugly.
004 | Explicit is better than implicit.
005 | Simple is better than complex.
006 | Complex is better than complicated.
007 | Flat is better than nested.
008 | Sparse is better than dense.
009 | Readability counts.
010 | Special cases aren't special enough to break the rules.
... (truncated - too many lines)

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

thin trout
#

Who need hello world when you have python

#

!e import __hello__

night quarryBOT
#

@thin trout :white_check_mark: Your eval job has completed with return code 0.

Hello world!
snow beacon
#

Class decorators are like function decorators.

thin trout
#

They are just being called with a callback to the function or class as the first arg and assign the returned value to the global name of the function/class

#

In that case, @f makes _ equal to "Hello world" and then it is fed to print() through the @print decorator

snow beacon
#

_ ends up as None from the print.

thin trout
#

Yeah because _ is the latest returned value in the repl

snow beacon
#

The decorator still assigns to it if it isn't in the repl.

hot crypt
#

!e

a = "Hello World!"
__import__(a[:len(dir(a)[~False])].lower().join([chr(len(dir(True))+len(dir(())+~False)*-~True]*-~True))```
night quarryBOT
#

@hot crypt :x: Your eval job has completed with return code 1.

001 | File "<string>", line 2
002 | SyntaxError: closing parenthesis ']' does not match opening parenthesis '('
hot crypt
#

ah mistyped

#

!e

a = "Hello World!"
__import__(a[:len(dir(a)[~False])].lower().join([chr(len(dir(True))+len(dir(()))+~False)*-~True]*-~True))```
night quarryBOT
#

@hot crypt :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | ModuleNotFoundError: No module named 'gghellogg'
hot crypt
#

can i run !e with py2.7? 😅

thin trout
#

Nope :D

hot crypt
#

😫

#

guess dict sizes change from 2.7 to 3.x

rugged sparrow
#

@gilded orchid @thin trout the f decorator is passed the class _ into it's only argument (and that isn't used) and returns the string 'Hello World'. This string is then passed to the print function (here used as a decorator because the syntax for decorators means the the return value/input to a decorator does not need to be a function. There only has to be a function at the innermost level)

thin trout
#

Hey, I think I got it right haha

hot crypt
#

Without using numbers, is there a shorter way to obtain -1 other than ~False?

#

oh -True. welp

marsh void
#

haha

hot crypt
#

im very new to golfing x)

#

I tried to code an esoteric hello world without numbers or strings other than "Hello World!", then golfed it.
The result looks like somebody with very poor logic skills attempted a hello world

a = "Hello World!"
b=True;c=-~b;d=chr((c+b<<c+c+b)-b)*c;__import__(d+a[:c+c+b].lower()+d)```
thin trout
#

Sounds like an esoteric script haha

sick hound
#

couldn't you just print("Hello World!")

proper vault
#

__builtins__.__dict__.__getitem__.__call__('__import__').__getattribute__('__call__').__call__('__hello__')

thin trout
#

Why did I laught to this

proper vault
#

the last __call__ may be cheating

hot crypt
#

but whats the fun in that @sick hound

#

you could also change a to be "Hello <whatever>"

rugged sparrow
#

__builtins__.globals.__call__().__getitem__('__builtins__') @proper vault to stretch it a bit more

proper vault
#

but then you use not __name__ things

rugged sparrow
#

ah true

proper vault
#

__builtins__.__dict__.__getattribute__('__getitem__').__call__('__import__').__getattribute__('__call__').__call__('__hello__') is an option, but you can nest those indefinitely

rugged sparrow
#

true that

#

i wonder if you could get a recursion error by doing that

edgy kelp
#

you can get one on the parser

#

or the compiler, don't remember which one it was

hot crypt
#

make everything a string. add an exec. repeat

#

(?)

edgy kelp
#

exec("[0]"*2993) for the compiler

sick hound
#

!e ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((

night quarryBOT
#

@sick hound :x: Your eval job has completed with return code 1.

001 | s_push: parser stack overflow
002 | MemoryError
edgy kelp
#

replacing exec with eval seems to move the recursions one step back

thin trout
#
Python 3.8.1 (default, Feb 17 2020, 11:48:46) 
[GCC 9.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
s_push: parser stack overflow
MemoryError```That's so dumb haha
marsh void
#

!e exec('[0]'*2993)

night quarryBOT
#

@marsh void :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | RecursionError: maximum recursion depth exceeded during compilation
marsh void
#

hahaha

proper vault
#

interesting, ipython gives the proper error

crystal mica
#

wait wat

proper vault
#

oh, nvm, just took a larger number ```py
In [23]: exec('[0]'*29993)

RecursionError Traceback (most recent call last)
<ipython-input-23-3e019763dfac> in <module>
----> 1 exec('[0]'*29993)

RecursionError: maximum recursion depth exceeded during compilation

edgy kelp
#

mistyped and put one more number when trying to find the ipython ceiling on that and python just crashed

proper vault
#

!e exec('[0]'*299993)

night quarryBOT
#

@proper vault :warning: Your eval job timed out or ran out of memory.

[No output]
edgy kelp
#

wonder why this happens

#

!e

for i in range(2):
    for func in exec, eval:
        multiplier = 2993 + i
        try:
            func("[0]"*multiplier)
        except RecursionError:
            print(f"{func.__name__} failed with {multiplier=}")
        except TypeError: pass
    print()
night quarryBOT
#

@edgy kelp :white_check_mark: Your eval job has completed with return code 0.

001 | exec failed with multiplier=2993
002 | 
003 | exec failed with multiplier=2994
004 | eval failed with multiplier=2994
edgy kelp
#

or how rather

marsh void
#

this happens when actually parsing it I think

#

Something to do with LL(1)

sick hound
sick hound
#
import ast;ast.parse("0,"*10000000000)
``` dont try at home
proper vault
#

immediately tries at home

edgy kelp
#

might as well tuple a range

sick hound
#

@marsh void just tried with pegen, fails at the same position

for func in (extension.parse_string, compile):
    x = 2992
    try:
        while True:
            x += 1
            func("[0]"*x)
    except:
        print(f"{func.__name__} failed at {x}")
parse_string failed at 2993
compile failed at 2993
#

It doesnt fail in the parser, it fails in the symboltable

#

construction

gilded orchid
#

Is the second one faster than the first one or are these the same?

def a(x,y):
 pass

def a(x: int, y:int) -> int:
 pass
#

nvm turns out they're identical

marsh void
#

isn't the latter one a negligible bit slower? @gilded orchid

#

it evaluates type annotations, idk

gilded orchid
#

I'm pretty sure type annotations don't actually do anything

#

they are just helpful for stuff like automatic documentation

marsh void
#

well

#

in 3.8 - their evaluation is postponed

gilded orchid
#

oh ok

#

I guess it will be a tiny bit slower

brisk zenith
#

it is not slower at all

#

at least, i'm 90% sure they aren't slower.

#

i mean, unless you consider the time taken to parse the extra tokens, but that's negligible.

snow beacon
#

3.8 will have broken one of my programs, it appears.

tribal moon
#
__import__('builtins', level=0).__dict__['print']('Time is: ',__import__('datetime').__dict__['datetime'].now().strftime('%I:%M'))

tells the time

thin trout
#

Typehint are a bit slower because they are additional metadata to parse, store and load into memory, but that's almost nothing compared to the rest of the startup procedure, plus it doesn't cost anything at runtime, except for memory (iirc)

marsh void
#

^

sick hound
#
>>> import ctypes
>>> ctypes.c_longlong.from_address(id(4)+8).value=id(bool)
>>> 4
False
>>> 2 + 2
False```
#
>>> 4
False
>>> bool(4)
True```
#

what have we done

marsh void
#

hahaha

#

!e
import ctypes
ctypes.c_longlong.from_address(id(True)+8).value = id(bool)
print(1)

night quarryBOT
#

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

1
marsh void
#

!e
import ctypes
ctypes.c_longlong.from_address(id(True)+8).value = id(bool)
print(True)

night quarryBOT
#

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

True
marsh void
#

okay

sick hound
#

1 and True are different

#

making True a bool doesn't change anything

marsh void
#

yeah makes sense

#

!e
import ctypes
ctypes.c_longlong.from_address(id(True)+8).value = id(int)
print(True)

night quarryBOT
#

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

1
marsh void
#

hahaha

#

got'em

#

anyway it's not gonna be True -> False this time as well

sick hound
#

alongisde token parsing, creating a temporary dictionary and mapping the arguments to annotations if you postpone the evaluation, there will be the cost of AST unparsing. Unparser itself written in C, so that won't affect much.

gilded orchid
#

out of curiousity, what doesn't error, and makes this return false?

f=lambda x:type(x)(x)==x
proper vault
#

object

#
In [100]: f=lambda x:type(x)(x)==x

In [101]: f(object)
Out[101]: False
#

and str/list/dict

#

essentially anything whose type is type

#

and type(x) != x

gilded orchid
#

is there anything that works that isn't type? (or NaN)

sick hound
#

yea, you can create a metaclass and override __call__ i guess

proper vault
#
 class A:
     def __eq__(*a): return False
     def __init__(self,*a): super().__init__()

an object defined like this, an empty numpy array (with a depracation warning, returns a falsey object)

marsh void
#

okay so

#

I have seen a speech about messing with python's import and damn it was so fun

#
some_file.json
script.py```
```py
from magic_importer import some_file
print(some_file.data)``` and this will print contents of the file
rugged sparrow
#

wait how?

sick hound
#

@rugged sparrow import hooks?

marsh void
#

yep, import hooks

#

specifically, sys.meta_path iirc

#

!eval import sys; print(sys.meta_path)

night quarryBOT
#

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

[<class '_frozen_importlib.BuiltinImporter'>, <class '_frozen_importlib.FrozenImporter'>, <class '_frozen_importlib_external.PathFinder'>]
marsh void
#

here

marsh void
#

Just add your magical PathFinder and Loader there

rugged sparrow
#

ah

#

cool

sick hound
#
>>> x = []
>>> for _ in range(10000):
...     x = [x]
...
>>> x in x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RecursionError: maximum recursion depth exceeded in comparison```
edgy kelp
#

RecursionErrors aren't pokemon

proper vault
#

are you sure?

pine wagon
#
class INF: 
    __getitem__=lambda t,k:t.__dict__[k]if k in t.__dict__ else INF()
    
print(INF()[1]["DFNDJ"][2893297493847394873]["qqq"]["dfdfd"][22][1212])
#

It is not as cool as the other ones in here, but still I thought was decent!

#

Actually, just realized that there was no point in t.__dict__ anyway, woops

snow beacon
#

Reminds me of flail.

sick hound
#

Fuck

#

I cant format it as code

#
(lambda h,t,w,o:((lambda f:(lambda x:x(x))(lambda y:f(lambda *args:y(y)(*args))))(lambda l:(lambda x:(lambda x:l(x))((lambda a,b,xpt,ypt:str(h.__getitem__(ypt).__setitem__(xpt,(((h.__getitem__(ypt).__getitem__(xpt)!="E")+1)%2)*o[t[0]%2]+(((h.__getitem__(ypt).__getitem__(xpt)!=o[(t[0]+1)%2])+1)%2)*o[(t[0]+1)%2]+(((h.__getitem__(ypt).__getitem__(xpt)!=o[(t[0])%2])+1)%2)*o[(t[0])%2]))+0*str(t.__setitem__(0,t.__getitem__(0)+1)))(print("Player "+o[t[0]%2]+" playing."),str(print("\n\t0\t1\t2\t\n\n0\t"+h[0][0]+"\t"+h[0][1]+"\t"+h[0][2]+"\t"+"\n\n1\t"+h[1][0]+"\t"+h[1][1]+"\t"+h[1][2]+"\t"+"\n\n2\t"+h[2][0]+"\t"+h[2][1]+"\t"+h[2][2]+"\t\n")),int(input("Enter the x coordinate of your selection: ")),int(input("Enter the y coordinate of your selection: ")))) if (lambda x:True)(print((o[(t[0]+1)%2]+" won!")*w(h,o[(t[0]+1)%2]))) and (lambda x:True)(print(("\n\t0\t1\t2\t\n\n0\t"+h[0][0]+"\t"+h[0][1]+"\t"+h[0][2]+"\t"+"\n\n1\t"+h[1][0]+"\t"+h[1][1]+"\t"+h[1][2]+"\t"+"\n\n2\t"+h[2][0]+"\t"+h[2][1]+"\t"+h[2][2]+"\t\n")*w(h,o[(t[0]+1)%2]))) and w(h,o[(t[0]+1)%2])==0 and t[0]<9 else None)))("c"))([["E","E","E"],["E","E","E"],["E","E","E"]],[0],(lambda b,p:(((b[0][0]==p)+(b[0][1]==p)+(b[0][2]==p))==3)+(((b[1][0]==p)+(b[1][1]==p)+(b[1][2]==p))==3)+(((b[2][0]==p)+(b[2][1]==p)+(b[2][2]==p))==3)+(((b[0][0]==p)+(b[1][0]==p)+(b[2][0]==p))==3)+(((b[0][1]==p)+(b[1][1]==p)+(b[2][1]==p))==3)+(((b[0][2]==p)+(b[1][2]==p)+(b[2][2]==p))==3)+(((b[0][0]==p)+(b[1][1]==p)+(b[2][2]==p))==3)+(((b[0][2]==p)+(b[1][1]==p)+(b[2][0]==p))==3)),["X","O"])

#

There

thin trout
#

O.o

#

Is it partially auto-generated?

zealous widget
#

yeah, by one-linerizer

thin trout
#

Aaah

hot crypt
#

is this tictactoe

proper vault
#

yes

wispy horizon
#

Oh God

gilded orchid
zealous widget
#
from itertools import*;m,p,q,r,s,l,a=dict(enumerate("276951438")),[[],[]],0,print,' │ │ ','─┼─┼─','XO';b=[*map(list,[s,l,s,l,s])];f=lambda:r('\n'.join(map(''.join,b)));f()
while m:
 i=int(input(a[q]+' move: '))-1;p[q]+=[int(m.pop(i))];b[~(i//3*2)][i%3*2]=a[q];f()
 if any(sum(d)==15for d in combinations(p[q],3)):r(a[q]+' wins');break
 q^=1
else:r('Draw')

i like this one better

sudden osprey
#

That is much nicer

zealous widget
sudden osprey
#

Haha, that's genius. I love it.

rugged sparrow
#

@zealous widget does it verify input tho?

zealous widget
#

it does not accept incorrect inputs

#

you can read the doc string

rugged sparrow
#

Oh I was looking at the embed, links in discord have always been wonky for me

brisk zenith
#

i remember when i made tictactoe in a 400MB python script.

#

the interpreter segfaulted once it reached like 50 GB of memory usage (i put a lot of swap towards it because otherwise memory errors would come first :D)

#

that was just for parsing the script

#

it never actually ran

proper vault
#

ye, the python parser sometimes breaks

#

!e ```py
exec('('*3000)

night quarryBOT
#

@proper vault :x: Your eval job has completed with return code 1.

001 | s_push: parser stack overflow
002 | Traceback (most recent call last):
003 |   File "<string>", line 1, in <module>
004 | MemoryError
brisk zenith
#

yes but that's just a memory error

#

i got a straight up segfault

#

and i couldn't upload it to github because 100MB is their file limit. so sad.

#

gitlab can do it though, i think

wind maple
#

It might have been a segfault due to you having a collections past ssize_t

brisk zenith
#

i mean, it didn't even finish parsing/compiling the code, so it's not my fault!! :D

proper vault
#

try pypy

brisk zenith
#

well i don't even have the code any more so i'm gonna recreate it

eager depot
#

!e

print("wow, working?")
night quarryBOT
#

@eager depot :white_check_mark: Your eval job has completed with return code 0.

wow, working?
eager depot
#

wow

#

:D

edgy kelp
#

there is #bot-commands for random tests

warm gate
#

haha

#

!e

code = '(lambda f: f(f))(lambda f: f(f))'
code += '()' * 3000
eval(code)```
night quarryBOT
#

@warm gate :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 | RecursionError: maximum recursion depth exceeded during compilation
warm gate
#

hehe

young mortar
#

Imagine all the people here doing something productive. That would be amazing. 😝

sick hound
#

Ok i have a challenge for all of you guys

#

Use aiohttp to get the contents of a webpage in 2 lines

#

And print it

lament ibex
#

echo "await (await __import__('aiohttp').client.ClientSession().get('http://example.org')).text()" | python3.8 -m asyncio ? Bit of a weird request

split harbor
#

!e

s="eval(s)"
eval(s)
wispy horizon
#

!e

s="eval(s)"
eval(s)

night quarryBOT
#

@wispy horizon :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 |   File "<string>", line 1, in <module>
004 |   File "<string>", line 1, in <module>
005 |   File "<string>", line 1, in <module>
006 |   [Previous line repeated 496 more times]
007 | RecursionError: maximum recursion depth exceeded during compilation
wispy horizon
pine wagon
#

lul

marsh void
#

hahaha

#

okay so I am doing this

#
# coding: not_python
def func() -> None {
    print(13);
}```
#

don't ask haha

sick hound
#

@marsh void it would be super cool to use this with from __future__ import braces

marsh void
#

Hahaha

#

hahaha

gilded orchid
#

@marsh void how does that work?

marsh void
#

# coding: something can be hooked (site module) to define new "encoding" in order to access the code before runtime

#

then I run some shitty re/parsing on the code

#

@sick hound as funny as it sounds, I am 90% sure I can do that

#

You would just have to import one small module before that

#

Oh wait, I can't do that, haha

#

Since I need to access everything before runtime

#

my dumb

sick hound
#

well actually you can

#

(just a guess) you can create a pth file to load your custom module which will just replace the decoder method of the default encoding instead of registering an encoding

#

so user doesn't need to specify # coding etc

#

while you are decoding you can just compare iterate through tokens and when you see first from token just take a peek ahead, and compare the second value is a __future__ import and then do some transformations

#

if there is not any future imports, you can just use backuped decode version of the original decoder

pure dew
#

are you doing something like inlinec?

marsh void
#

kind of

#

Though less hacky I guess

gilded orchid
#

@marsh void what in the site module do you use to hook into encodings?

marsh void
#

It’s not that

#
  • This module is automatically imported during initialization. *
#

(site)

#

And basically that fact allows you to hook encodings

#

That’s what I meant

gilded orchid
#

oh ok

marsh void
#

I am going to try and make some simple example

#

Can someone inspect if this is CPython impl detail, though?

sick hound
#

I guess it depends how you are hooking into the site?

#

AFAIK pth files are specific to CPython, and they will be removed soonish.

marsh void
#

oh no

#

this is so sad

#
# coding: pyxl
html = <html><body>Inline HTML!</body></html>
print(html)``` we can even do this now
gilded orchid
#

oh god

marsh void