#esoteric-python

1 messages · Page 84 of 1

bitter iris
#

BRM way

proper vault
#

so this would convert the float literal 12. into 12 ., to allow things like 12._add__

bitter iris
#

Yea

formal sandal
#

Then you can attach my templatechecking system and avoid manual checks with if!

def fix_number_attrgets():
  ...

ProgramWithCorrectNumberAttrgets =\
  expand(
    str,
    check_number_attrgets
  )

@overload()
def get_program(program: str):
  return fix_number_attrgets(program)

@overload(get_program)
def get_program(program: ProgramWithCorrectNumberAttrgets):
  return program
thin trout
#

@sharp canyon I did a little something to show a stupid use case for matmul, I might expand it later haha

>>> email = name@domain.com   # Note that it isn't a string, there are no quotes
>>> print(email)
name@domain.com```Full script here : https://paste.pythondiscord.com/ixusarisix.py
I'll maybe expand it to use a context manager instead of instancing objects
sharp canyon
#

Interesting

thin trout
formal sandal
#

Maybe you should also add support for -.

#

my-name@domain.com

proper vault
#

can you get the full email spec to work

formal sandal
#

Have you seen the 'official' email regexp? :)

proper vault
#

email isnt even regular, as comments can afaik be nested

thin trout
#

I'll probably expand it yeah

#

I made a little gist

cunning wasp
#

Very cool - I've never come across the @ operator before (didn't even know it was one) - what is it's purpose/use-case?

thin trout
#

It is the matrix multiplicator operator

#

It isn't used in any stdlib object, but its purpose is to multiply matrix

cunning wasp
#

Nice, never knew that before!

formal sandal
#

It looks nice between [](){}
f(hello, world)@(lorem, ipsum)

{
  "hello": "world",
  "lorem": "ipsum"
}@{
  "hello": "world",
  "lorem": "ipsum"
}@{
  "hello": "world",
  "lorem": "ipsum"
}@{
  "hello": "world",
  "lorem": "ipsum"
}
#
[](){}
```is also a valid C++ expression --- a lambda that does nothing
#

@ also allows for even more syntactically correct smileys.

___@_@L__/I
#
# This smiley is throwing a yoyo
Ж-----L@_(o_o)@_
tribal moon
#

Yes I know my code is really bad

rugged sparrow
#

@formal sandal can you turn your catcher into a lambda tho?

proper vault
#

without imports 😛

rugged sparrow
#

i can do without imports in 3.7

#

3.8 needs one import (at least with my method)

formal sandal
#

I don't think so...

#

Well...

#

I can use sys.excepthook

#

How can you do it without imports in 3.7?

thin trout
#

__import__? :P

formal sandal
#

Well, that's an import!

#

It even says so itself.

snow beacon
#

Unless sys has already been imported somewhere?

formal sandal
#

!e

print(isinstance(Warning, Exception))
print(Warning.__bases__)
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

001 | False
002 | (<class 'Exception'>,)
formal sandal
#

How so?!

#

Well, you can do something like

(exec("import sys"), <computation>)[1]

But that's still an import

#

You know what, maybe that template checking stuff isn't that bad.

#

I already wrote 270 SLOC for my little project, and I didn't use a single if statement or expression

snow beacon
#

Is sys used in site? If so, it'll be in the module list already.

edgy kelp
#

It's for injecting stuff at interpreter startup so I'd be surprised if it didn't use the module for communicating with it

rugged sparrow
#

@formal sandal you can get a ContextDecorator from object.__subclasses__() on some platforms of python3.6-3.7

rugged sparrow
#
(s:=lambda o=object:{c.__name__:[c,s(c)] for c in type.__subclasses__(o)})
#

creates a function s that produces a recursive map of every currently existing class in memory at the moment it is executed

bitter carbon
#

!e (lambda: "esoteric python")()

night quarryBOT
#

@bitter carbon :warning: Your eval job has completed with return code 0.

[No output]
bitter carbon
#

ok

#

!e print((lambda: "esoteric python")())

night quarryBOT
#

@bitter carbon :white_check_mark: Your eval job has completed with return code 0.

esoteric python
bitter carbon
#

cool

marsh void
#

!e exec('{'*3000 + '}'*3000)

night quarryBOT
#

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

square root function

#

without using square root

#

allowed to use any method

#

halley, newton, euler e.g

proper vault
#
def sqrt(n, error=0.0002):
   if n < 0: return float('NaN')
   high = n
   low = 0
   while abs(low-high) > error:
       mid = (high+low)/2
       val = mid ** 2
       if val > n: high = mid
       if val < n: low = mid
       if val == n: return mid
   return low
```one of the least painful ways
sick hound
#
a=lambda b,i=1:[i:=(i-(i*i-b)/2/i)for _ in range(100)][-1]
#

oneliner

#

gonna add error

rugged sparrow
#

sqrt = lambda i:int(i**.5) @proper vault @sick hound

sick hound
#

thats not allowed

proper vault
#

shut

sick hound
#

lol forgot to mention it

rugged sparrow
#

it doesnt use the square root

#

lmao

sick hound
#

ik lol

#

i did forgot to mention this thingie

rugged sparrow
#

yah i assumed it wouldnt count for the challenge

#

just wanted to put it out there

sick hound
#

btw nice profile pic

#

gtg bye

bitter carbon
#

!e exec(int(["20"][0])+int(["80"][0]))

night quarryBOT
#

@bitter carbon :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | TypeError: exec() arg 1 must be a string, bytes or code object
bitter carbon
#

!e int(["20"][0])+int(["80"][0])

night quarryBOT
#

@bitter carbon :warning: Your eval job has completed with return code 0.

[No output]
bitter carbon
#

!e print(int(["20"][0])+int(["80"][0]))

night quarryBOT
#

@bitter carbon :white_check_mark: Your eval job has completed with return code 0.

100
bitter carbon
#

lol

analog rock
#

anyone here good at code golf?

marsh void
#

many people are

bitter iris
#

While exploring ways to bringing braces to python with @marsh void, I just discovered we can just abuse lib2to3's parser generator for this.

from lib2to3 import pygram
from lib2to3.pgen2.driver import load_grammar

pygram.python_grammar = load_grammar("test.txt")
pygram.python_symbols = pygram.Symbols(pygram.python_grammar)

from lib2to3.pytree import Leaf
from lib2to3.pgen2 import token
from lib2to3.fixer_base import BaseFix
from lib2to3.refactor import RefactoringTool

class FuckUpPython(BaseFix):
    PATTERN = "funcdef"
    
    def transform(self, node, results):
        define, name, paramaters, fuck1, suite, fuck2 = node.children
        fuck1.replace(Leaf(token.COLON, ":"))
        fuck2.remove()
        


class RefactorTool(RefactoringTool):

    def __init__(self):
        self._fixer = FuckUpPython(None, None)
        self._fixers = [self._fixer]
        super().__init__(None, {})

    def get_fixers(self):
        return self._fixers, []
        
def fuckup(source):
    refactor_tool = RefactorTool()
    return str(refactor_tool.refactor_string(source, "fucker"))
    
print(fuckup(
"""\
def x() FUCK
    print(2+2)
FUCK
"""
))
marsh void
#

god damn it

bitter iris
#
funcdef: 'def' NAME parameters ['->' test] 'FUCK' suite 'FUCK'
``` I only changed funcdef on the original grammar and 🎉
marsh void
#

👍

formal sandal
#
def x() FUCK
  print(2+2)
KCUF
#

Like if...fi.

marsh void
#

haha

#

thanks to isidentical for teaching me some neat tokens magic

#

working on somewhat actually stable and working version of braces in python

#

what’s left to do is to catch the from __future__ import braces and actually add braces for the true epicness

formal sandal
#

!e

import sys

sys.excepthook = lambda *_: print("do bracket thingy")

from __future__ import brackets
night quarryBOT
#

@formal sandal :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 5
002 | SyntaxError: from __future__ imports must occur at the beginning of the file
formal sandal
#

ew

#

!e

import sys
from __future__ import brackets

sys.excepthook = lambda *_: print("do bracket thingy")
#

!e

from __future__ import brackets
import sys

sys.excepthook = lambda *_: print("do bracket thingy")
#

!e

from __future__ import braces
import sys

sys.excepthook = lambda *_: print("do bracket thingy")
night quarryBOT
#

@formal sandal :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 | SyntaxError: not a chance
bitter iris
#

future imports are handled at compile time rather then run time

edgy kelp
#

I mean, that works apart from it exiting with 1 anyway :D

Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import braces
do bracket thingy
bitter iris
#

well, it is one of the reasons why python is forcing you to put this future import at the top of file (but not the original reason)

edgy kelp
#

can't do much of handling and ignoring the exception itself outside of the file, at least the ones that I can think of and would be willing to do

#

the excepthook just makes it nice to look at

thin trout
#

~~!e

import dis
dis.dis('''
from future import braces
a = 1
print(a + 1)''')```~~
night quarryBOT
#

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

001 |   2           0 LOAD_CONST               0 (0)
002 |               2 LOAD_CONST               1 (('braces',))
003 |               4 IMPORT_NAME              0 (future)
004 |               6 IMPORT_FROM              1 (braces)
005 |               8 STORE_NAME               1 (braces)
006 |              10 POP_TOP
007 | 
008 |   3          12 LOAD_CONST               2 (1)
009 |              14 STORE_NAME               2 (a)
010 | 
011 |   4          16 LOAD_NAME                3 (print)
... (truncated - too many lines)

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

thin trout
#

Interesting, the rest of the code is still parsed, even if braces is imported

snow beacon
#

!e ```python
import dis
dis.dis('''
from future import braces
a = 1
print(a + 1)''')

night quarryBOT
#

@snow beacon :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/usr/local/lib/python3.8/dis.py", line 38, in _try_compile
003 |     c = compile(source, name, 'eval')
004 |   File "<dis>", line 2
005 |     from __future__ import braces
006 |     ^
007 | SyntaxError: invalid syntax
008 | 
009 | During handling of the above exception, another exception occurred:
010 | 
011 | Traceback (most recent call last):
... (truncated - too many lines)

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

thin trout
#

Nevermind, discord markdown fooled me

edgy kelp
#

You can get it to do stuff through site before the main code is parsed and compiled

formal sandal
#

!e

compare=lambda v,V,E:any(map(lambda e:(lambda t,T:print(f"test = {e}; f1 = {t}; f2 = {T}"))(*(lambda f: (v(f(e)), V(f(e))))(lambda e:(lambda t:(lambda:t.pop(0)))([len(e),*e]))),E))

def sum_recursive(s):
  if s == []: return 0
  else: return s[0] + sum_recursive(s[1:])

def f1(input):
  n = int(input())
  s = 0
  for i in range(n):
    s += int(input())
  return s

def f2(input):
  n = int(input())
  return sum_recursive([int(input()) for _ in range(n)])

compare(f1, f2, [
  [1, 2, 3],
  [],
  [-1, 0, 5],
  [100, 200, 300, 400]
])
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

001 | test = [1, 2, 3]; f1 = 6; f2 = 6
002 | test = []; f1 = 0; f2 = 0
003 | test = [-1, 0, 5]; f1 = 4; f2 = 4
004 | test = [100, 200, 300, 400]; f1 = 1000; f2 = 1000
formal sandal
#

One-liner testing framework...

#

Any thoughts on obfuscating it?

#

Oh, I know

#

I should replace compare with соmраrе

#
>>> list(map(ord,"compare"))
[99, 111, 109, 112, 97, 114, 101]
>>> list(map(ord,"соmpаrе"))
[1089, 1086, 109, 112, 1072, 114, 1077]
#
lambda _,__,___:any(map(lambda ____:(lambda _,__:print(f"test = {____}; f1 = {_}; f2 = {__}"))(*(lambda f: (_(f(____)), __(f(____))))(lambda ____:(lambda _:lambda:_.pop(0))([len(____),*____]))),___))
#
lambda _,__,___:any(map(lambda ____:(lambda _,__:print(f"test = {____}; f1 = {_}; f2 = {__}"))(*(lambda f: (_(f(____)), __(f(____))))(lambda ____:(lambda _:lambda:_.__getattribute__(dir(_)[42])(42-42))([len(____),*____]))),___))
acoustic zinc
#

what are the characters in the second one?

formal sandal
#

Cyrillic letters.

#

йцукенгшщзхъфывапролджэячсмитьбю

#

ай хев эн айдиа, мейби ви куд мейк зис ченел ивен мор изотерик иф инстед ов юзинг плейн инглиш ви юзд сырилик транскрипшен оф инглиш ин аур дискашенс.

#

ординари пипл вил онли бе эйбл ту андерстенд ус юзинг google translate.

#

текникли ит вонт вайолейт зе серверс рулз абаут онли инглиш биинг аллауд, синс ви вуд ток ин инглиш, джаст риттен ин э дифферент формат.

formal sandal
#

Пайтон экчули супортс сырилик керектерс эз вериэбл неймс. Вай вуд ит ду зет?

#

!e

вериэбл = 123
night quarryBOT
#

@formal sandal :warning: Your eval job has completed with return code 0.

[No output]
marsh void
#

@formal sandal because it is defined like that. no idea why you wrote it in russian-transcript

thin trout
#

It supports all unicode characters actually

#

!e

variabilisé = 123```
night quarryBOT
#

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

[No output]
formal sandal
#

well, all unicode letters, I guess

#

!e

if():
  𝓔 = I * R
night quarryBOT
#

@formal sandal :warning: Your eval job has completed with return code 0.

[No output]
formal sandal
#

Intersting

sick hound
#

!e print(𝓔)

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name 'E' is not defined
sick hound
#

!e py e = 4 print(𝓔)

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | NameError: name 'E' is not defined
sick hound
#

!e py E = 4 print(𝓔)

night quarryBOT
#

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

4
sick hound
#

!e py 𝓔 = 4 print(E)

night quarryBOT
#

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

4
sick hound
#

!e py print('𝓔')

night quarryBOT
#

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

𝓔
sick hound
#

!e ```py
class Test:
def getattr(self, x):
print(x)

Test().𝓔```

night quarryBOT
#

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

E
sick hound
#

huh

formal sandal
#

huh?!!

#

!e

𝓔 = 1
print(E)
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

1
nocturne saddle
#

!charinfo 𝓔

night quarryBOT
cursive plover
#

was looking to baar

a, b = input().split(), input().split()[::-1]
for c,d in zip(a,b):
    if c<=d:
        print("No")
        exit()
print("Yes")
#
(lambda a,b: [(print("No"), exit()) for c,d in zip(a,b) if c<=d else print("Yes")])(input().split(), input().split()[::-1])
#

but this gives me SyntaxError :/

#

what am I doin wrong

hot crypt
#

!e
𝓔 = 1
E=2
print(𝓔)

night quarryBOT
#

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

2
hot crypt
sick hound
#
[(print("No"), exit()) for c,d in zip(a,b) if c<=d else print("Yes")]``` @cursive plover this isn't a valid list comprehension
#
[(print("No"), exit()) if c<=d else print("Yes") for c,d in zip(a,b)]``` this is
cursive plover
#

oh yes, my bad, thank you

#

also one more thing, if I wanna use nested lambdas\

#

so say (lambda var1: (lambda var2: code)(var2) #codeHere)(var1)

#

how do I put code in the place where I wrote #codeHere

#

like say

#
(lambda a:(lambda b: print(b))(int(input())) print(b))(int(input())
#

(this was, I was trying to see if I can access b outside the inner lambda)

sick hound
#

...uhh, just don't, i guess?

#
(lambda a:(lambda b: (print(b),print(b)))(int(input())))(int(input()))```
#

or you could if you want to but you can't access b

#
(lambda a:((lambda b: print(b))(int(input())),print(b)))(int(input())) # error
(lambda a:((lambda b: print(b))(int(input())),print(a)))(int(input())) # works fine```
cursive plover
#

@sick hound your earlier solution isn't equivalent to my code :/

#

baar baar

#

ie, it has to print(yes) after exiting the loop

sick hound
#

what on earth were you using else for then

#

i assumed you were converting an if/else

#
(lambda a,b: ([(print("No"), exit()) for c,d in zip(a,b) if c<=d],print("Yes")))(input().split(), input().split()[::-1])```
cursive plover
#

oh, damn I uh had break in my for earlier, and was using else against that

#

my bad sorry

#

yeah this works

#
(lambda a:((lambda b: print(b))(int(input())),print(b)))(int(input())) # error
(lambda a:((lambda b: print(b))(int(input())),print(a)))(int(input())) # works fine```

@sick hound so hm, no way to have code like I wanted to right? Is that what we conclude

sick hound
#

if you put code outside the lambda then you can't access the arguments of the lambda

#

well you can still access the arguments but not from outside the lambda

cursive plover
#

hm, but I can't actually put code outside can I?

#

Well, the reason is

#

I had this code

#
e = int(input())
c, d = list(map(float, input().split())), list(map(float, input().split()))
a, b = int(input()) - 1, int(input()) - 1
c.pop(a),d.pop(b)

diff = [round(abs(i - j),3) for i,j in zip(c,d)]

print(c,d,sep = " \n", end = " \n")

if max(diff) == min(diff) == 0:
    print("Equal ")
elif max(diff) == min(diff):
    print("Good ")
else:
    print("Bad ")
#

which I further reduced to

#
e = int(input())
c, d = list(map(float, input().split())), list(map(float, input().split()))
a, b = int(input()) - 1, int(input()) - 1
c.pop(a),d.pop(b)
diff = [round(abs(i - j),3) for i,j in zip(c,d)]

[print(c, end = " \n"), print(d, end = " \n"), print("Equal ") if max(diff) == min(diff) == 0 else print("Good ") if max(diff) == min(diff) else print("Bad ")]
#

Now trying to that, I did

#
(lambda e,c,d,a,b:
(lambda diff: [c.pop(a),d.pop(b), [(print(*c, end = " \n"), print(*d, end = " \n")), print("Equal ") if max(diff) == min(diff) == 0 else print("Good ") if max(diff) == min(diff) else print("Bad ")]]) ([round(abs(i - j),3) for i,j in zip(c,d)]))
(int(input()), list(map(float, input().split())), list(map(float, input().split())), int(input()) - 1, int(input()) - 1)
#

and they're not equivalent, because look at the inner lambda, it's basically

(lambda diff: [c.pop(a), d.pop(b), stuff..])(declaration of diff here which is dependant on c and d)

the declaration of diff btw is ([round(abs(i - j),3) for i,j in zip(c,d)]))
But,

#

I wanna do c.pop(a), then d.pop(b), then declare diff

#

Does that make sense?

#

OH NEVERMIND, I figured it

#
(lambda e,c,d,a,b:[c.pop(a),d.pop(b), (lambda diff: [[(print(*c, end = " \n"), print(*d, end = " \n")), print("Equal ") if max(diff) == min(diff) == 0 else print("Good ") if max(diff) == min(diff) else print("Bad ")]])([round(abs(i - j),3) for i,j in zip(c,d)])])(int(input()), list(map(float, input().split())), list(map(float, input().split())), int(input()) - 1, int(input()) - 1)
#

basically, [c.pop(a),d.pop(b), (lambda diff: stuff)(declaration of diff based on updated c and d)]

#

damn hah, that makes sense

formal sandal
#

There is a nice way of replacing list.pop

#
pop = lambda x:x.__getattribute__(dir(x)[42])
#

!e

pop = lambda x:x.__getattribute__(dir(x)[42])
x = [1, 2, 3, 4]
print(pop(x)(0))
print(x)
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

001 | 1
002 | [2, 3, 4]
bitter iris
#

!e

import ast
print(ast.Module._fields)
del ast.Module._fields
print(hasattr(ast.Module, "_fields"), ast.Module._fields, "???")
del ast.Module._fields
night quarryBOT
#

@bitter iris :x: Your eval job has completed with return code 1.

001 | ('body', 'type_ignores')
002 | True () ???
003 | Traceback (most recent call last):
004 |   File "<string>", line 5, in <module>
005 | AttributeError: _fields
formal sandal
#

!e

class Step:
    def __init__(self, n):
        self.n = n

    def __lt__(self, other):
        # do some other stuff
        print(f"Step {self.n}")
        return True

process = [
    0,
    Step(1),
    Step(2),
    Step(3),
    Step(4),
    Step(5),
    Step(6),
]

min(process)
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

001 | Step 1
002 | Step 2
003 | Step 3
004 | Step 4
005 | Step 5
006 | Step 6
formal sandal
#

This is kinda like reduce...

#

You can load some initial state into Step(1) and then mutate in

bitter iris
#

this is not near even the first release but it works,

from freesyntax.factory import RuleFactory
from freesyntax.grammar import Match, Optional, Rule, Token
from freesyntax.structs import AutoLeaf

factory = RuleFactory()

@factory.funcdef(
    Match["define"],
    Token["STAR"],
    Token["NAME"],
    Token["STAR"],
    Rule["parameters"],
    Token["RARROW"],
    Rule["suite"]
)
def fixer(node):
    node.children[0].value = "def "
    node.children[1].remove()
    node.children[2].remove()
    node.children[-2].replace(AutoLeaf.COLON)

print(
    factory.transform(
        """
define *greet* (name) ->
    print(Hello, name)
"""
    )
)

a new syntax rewrite tool based on lib2to3

cursive plover
#

!e

pop = lambda x:x.__getattribute__(dir(x)[42])
x = [1, 2, 3, 4]
print(pop(x)(0))
print(x)

@formal sandal why do we have the [42] there?

snow beacon
#

To index within the directory of the list object. Presumably pop is the 43rd in alphabetical order.

cursive plover
#

where do you find that from

#

also, pop(x)(0)
pop is the whole lambda thing so
it becomes (lambda x: stuff)([1,2,3,4])
where does the 0 figure in that? I know it's for the index but erm where?

snow beacon
#

!e ```python
print(dir([1,2,3,4])[40:50])

night quarryBOT
#

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

['index', 'insert', 'pop', 'remove', 'reverse', 'sort']
snow beacon
#

pop([1,2,3,4]) returns [1,2,3,4].__getattribute__('pop')

#

The 0 is an argument to list.pop, to pop the first index of [1,2,3,4]

cursive plover
#

oh okay

#

so if that was to be

#

!e

(lambda x:x.__getattribute__(dir(x)[42])([1,2,3,4])(0)
night quarryBOT
#

@cursive plover :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     (lambda x:x.__getattribute__(dir(x)[42])([1,2,3,4])(0)
003 |                                                          ^
004 | SyntaxError: unexpected EOF while parsing
cursive plover
#

okay maybe

#

!e

(lambda x, i: x.__getattribute__(dir(x)[42](i)))([1,2,3,4],0)
night quarryBOT
#

@cursive plover :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 |   File "<string>", line 1, in <lambda>
004 | TypeError: 'str' object is not callable
cursive plover
#

hm, how?

#

Wait I think it's

#

!e

(lambda x, i: x.__getattribute__(dir(x)[42])(i))([1,2,3,4],0)
night quarryBOT
#

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

[No output]
cursive plover
#

oh, atleast it's correct now
Hm so

#

!e

(lambda x, i:[print(x, "before change"), x.__getattribute__(dir(x)[42])(i), print(x, "after change")])([1,2,3,4],0)
night quarryBOT
#

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

001 | [1, 2, 3, 4] before change
002 | [2, 3, 4] after change
cursive plover
#

NICE!

#

This was interesting, hm

#

!e

print(dir([1,2,3,4])[:])
night quarryBOT
#

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

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
cursive plover
#

oh, I see

snow beacon
#

dir already returns a list, FYI.

cursive plover
#

oh right

#

!e

print(dir([1,2,3]))
print(vars([1,2,3]))
print([1,2,3].__dict__)
night quarryBOT
#

@cursive plover :x: Your eval job has completed with return code 1.

001 | ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
002 | Traceback (most recent call last):
003 |   File "<string>", line 2, in <module>
004 | TypeError: vars() argument must have __dict__ attribute
snow beacon
#

Does it only work on classes?

cursive plover
#

I think it's because list doesn't have a __dict__ attribute?

#

and vars() is supposed to return the dict attribute if I'm reading things right, so that's why that didn't work as well I think?

#

!e

print(dir({1:'a'}))
night quarryBOT
#

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

['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
cursive plover
#

oh, dictionaries don't have a __dict__ either? :/ what does then

#

all I can find in the docs is this

snow beacon
#

Lists and dictionaries don't have writable attributes.

cursive plover
#

what do have them then?

#

oh, uh a user defined class

#

right?

#

and by writable attribute you mean like, a user defined attribute?

snow beacon
#

One that can be changed by e.g. foo.bar = "something".

#

That won't work for a list.

#

!e ```python
[].bar = "exception will be thrown"

night quarryBOT
#

@snow beacon :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | AttributeError: 'list' object has no attribute 'bar'
snow beacon
#

!e ```python
1..as_integer_ratio = (0, 0)

night quarryBOT
#

@snow beacon :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | AttributeError: 'float' object attribute 'as_integer_ratio' is read-only
cursive plover
#

ah

#

so what things have writable attributes?

snow beacon
#

User defined classes, mostly.

#

Code objects, and I believe functions also.

#

Quitters are also writable.

cursive plover
#

I didn't find much on what a quitter is on google, do you mean like sys.exit()?

snow beacon
#

No, in the repl exit and quit are quitters.

#

I think they're defined in pure python.

crystal mica
#

You can also prevent monkey patching / defining new attributes via __slots__ as well, for user defined classes

burnt pasture
#

code objects are immutable, fwiw

snow beacon
#

Oh, I must be thinking of the way you can overwrite a function's code object with a different one.

grave rover
snow beacon
#

Is this like what colorama does?

grave rover
#

colorama just allows easy use of color codes

#

What I'm trying to do is resolve all cursor movements to have the final result as a string

#

e.g. \033[5H moves the cursor up 5 lines

grave rover
#

printing to file/stdout doesn't work since those don't take VTE cursor codes into account

#

the above is a read() from terminal output (subprocess)

snow beacon
#

Is there a bash command you could incorporate using os.system()?

formal sandal
#

!e

import os
os.system("")
night quarryBOT
#

@formal sandal :warning: Your eval job has completed with return code 0.

[No output]
snow beacon
#

!e ```python
import os
os.system('echo "bash!"')

night quarryBOT
#

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

[No output]
snow beacon
#

!e ```python
import os
x = os.popen('echo "bash?"').read()
print(f"returned {x}")

night quarryBOT
#

@snow beacon :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 "/usr/local/lib/python3.8/os.py", line 981, in popen
004 |     proc = subprocess.Popen(cmd,
005 |   File "/usr/local/lib/python3.8/subprocess.py", line 854, in __init__
006 |     self._execute_child(args, executable, preexec_fn, close_fds,
007 |   File "/usr/local/lib/python3.8/subprocess.py", line 1637, in _execute_child
008 |     self.pid = _posixsubprocess.fork_exec(
009 | BlockingIOError: [Errno 11] Resource temporarily unavailable
snow beacon
#

There's a way, I expect.

formal sandal
#

tutorial included

golden ravine
#

hello

rugged sparrow
#
>>> def make_unreachable():
...     class unreachable:
...             secret = 'SECRET'
... 
>>> c('__main__.make_unreachable.<locals>.unreachable')
>>> make_unreachable()
>>> c('__main__.make_unreachable.<locals>.unreachable')
<class '__main__.make_unreachable.<locals>.unreachable'>
>>> c('__main__.make_unreachable.<locals>.unreachable').secret
'SECRET'
>>> type('a',(),{}) is c('__main__.a')
True
>>> ```
#
c=lambda n,l=lambda f,o:sum([f(f,c)for c in type.__subclasses__(o)],[o]):{f'{c}'.split("'")[1]:c for c in l(l,object)}.get(n)```
formal sandal
#

That's still reachable, though...

#

!e

import random

def guess(f, __lookup=[]):
    __lookup.append(f)
    return lambda *_,**__: random.choice(__lookup)
    
@guess
class A:
    pass

@guess
class B:
    pass

@guess
class C:
    pass

g = lambda:0
while "C" not in g.__name__:
    g = C()
print(g)
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

<class '__main__.C'>
sick hound
#

!e py import os os.exec('/bin/bash', ['bash', '-c', 'echo "bash?"'])

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | AttributeError: module 'os' has no attribute 'exec'
sick hound
#

!e py import os os.execv('/bin/bash', ['bash', '-c', 'echo "bash?"'])

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | FileNotFoundError: [Errno 2] No such file or directory
sick hound
#

huh

#

!e py import os os.listdir('/bin')

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | FileNotFoundError: [Errno 2] No such file or directory: '/bin'
sick hound
#

...

#

!e py import os os.listdir('/')

night quarryBOT
#

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

[No output]
sick hound
#

!e py import os print(os.listdir('/'))

night quarryBOT
#

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

['usr', 'snekbox', 'lib64', 'lib', 'etc']
sick hound
#

!e py import sys print(sys.executable)

night quarryBOT
#

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

/usr/local/bin/python
sick hound
#

!e py import os print(os.listdir('/usr/local/bin'))

night quarryBOT
#

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

['python3.8', 'python3', 'python']
marsh void
#

haha

thin trout
#

The PID limit is set to 1, you can't create any new process :>

#

There is no way of breaking it, apart from finding a security issue in cgroup kernel function

sick hound
#

!e

import os
print(os.system("cat /proc/sys/kernel/pid_max  "))
night quarryBOT
#

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

-1
edgy kelp
#
>>> from ctypes import c_void_p
>>> class NoMore:
...     def __str__(self):
...         return "baby don't hurt me"
...     __repr__ = __str__
...
>>> c_void_p.from_address(id(True)+8).value = id(NoMore)
>>> what = love = object()
>>> what is love
baby don't hurt me
acoustic zinc
#

that's genius

crystal mica
#

my god

#

that is genius

acoustic zinc
#

that doesn't work for me :/

edgy kelp
#

The offset is most probably version dependent

acoustic zinc
#

ah

zealous widget
#

why is there an offset at all

#

i understand nothing

brisk zenith
#

why did you use a c_longlong

#

why not use a c_void_p with the address of True?

#

that way it's architecture-agnostic

edgy kelp
#

You're asking me as if I knew that much about ctypes :P remembered that, it worked, was happy

cursive plover
#

what = love = object()
where's the object() coming from?

thin trout
#

It is Py_Object right?

proper vault
#

object here is just to get a generic object so that what is love is true

edgy kelp
#

anything could be there in place of the object()

zealous widget
#

anything mutable i think

#

or tiny immutable things

edgy kelp
#

Why tiny?

zealous widget
#

dunno, might make a new immutable thing if it isn't some stored constant, maybe not, i don't understand implementation details

edgy kelp
#

it makes the two names point to the same object don't think there's anything more going on

#
>>> a=b=int(1e300)
>>> a is b
True
zealous widget
#

i guess i assumed python would do this for immutable things:

In [67]: a = int(1e300)

In [68]: b = int(1e300)

In [69]: a is b
Out[69]: False

but doesn't seem like it

edgy kelp
#

but that's not a=b=val

proper vault
#

ye, a = b = x will always have all of them the same reference

edgy kelp
#

when used like that it creates one val and then passes it to those names

proper vault
#

(well, unless one of the assignments does more than just assign, e.g. c_longlong.value)

edgy kelp
#

well changed it to the void which I guess doesn't rely on the long implementation
Been meaning to get to know C more than just the basics which I guess would help me a bit understand what's actually going on in more detail

#

Guess there's no way to change is itself without changing whole python?

zealous widget
#

found this

#
class Direction:
    north = east = south = west = e
a = Direction()
print(a.north, a.east, a.south, a.west)
0 1 2 3
#

take that a = b = something

edgy kelp
#

is that an enum or something?

zealous widget
#

it's magic with __set_name__ only works in class definitions as far as i know

#
from itertools import count

class EnumInt:
    def __init__(self):
        self.count = count()
    def __set_name__(self, owner, name):
        setattr(owner, name, next(self.count))

e = EnumInt()
#

that's the first part

edgy kelp
#

so my initial statement is still true 😛

brazen geyser
#

descriptor fun

rugged sparrow
#

@formal sandal there you are still storing those classes in a list

#

in mine, unreachable is never stored by me, or returned

#

but because of how python stores subclasses theres still a ref to it that i can grab from a higher scope

#
>>> type('a',(),{}) is c('__main__.a')
True``` thats also why this works
cursive plover
#

@edgy kelp
What does this line do: c_void_p.from_address(id(True)+8).value = id(NoMore)
And how does love automatically become an object of class NoMore?
And when you do what is love, why isn't True printed instead of baby don't hurt me?

rugged sparrow
#

@cursive plover the c_void_p line replaces the class of True from bool to NoMore

edgy kelp
#
>>> from ctypes import c_longlong
>>> class NoMore:
...     def __str__(self):
...         return "baby don't hurt me"
...     __repr__ = __str__
...
>>> c_longlong.from_address(id(True)+8).value = id(NoMore)
>>> type(True)
<class '__main__.NoMore'>
>>> str(True)
"baby don't hurt me"
rugged sparrow
#

what and love are both the same object() instance

edgy kelp
#

what and love are just names referring to the same object so the is results in True which we have changed to return our string

cursive plover
#

Oh wait, okay so even a 1 == 1 or anything which is True would print baby ..

#

Oof, I get it now

#

also, what's the difference between c_void_p.from_address and c_longlong.from_address
and, why do you have id(True) + 8, what's the 8 in that doing?

#

and why do you have __repr__ = __str__ ?What does that help in doing? Okay that's cuz __str__ is called when print() is invoked, and __str__ is invoking __repr__

#

Hm, 8 is the offset or smth? But why 8? And why are we offsetting it

edgy kelp
#

Can't tell you why the actual reason for the offset but it doesn't work without it so that's enough for me

rugged sparrow
#

so id(True) gets the address of the beginning of the True object, +8 is the index of the True object's class

cursive plover
#

@rugged sparrow is there a way to verify that? I mean i can do id(True), which is address of True Object? how do I get address of True class

#

or rather, how did you check what's at address of True + 8th index?

rugged sparrow
#

so +8 afaik is actually specifying an offset in bytes to slot on the struct in memory

#

so the best way to find out whats at a specific offset is looking at the cpython sourcecode

cursive plover
#

ah, right

#

hm, nice

rugged sparrow
#
>>> m=lambda n:quit.__class__.__call__.__globals__['sys'].modules.get(n)
>>> m('os')
<module 'os' from '../lib/python3.8/os.py'>
>>> 
#

^get any already imported module without using import

brisk zenith
#

i think @vague gust did something like that to access os.system in the very first esoteric python challenge so that he could basically do no work in actually completing the challenge. madlad.

vague gust
#

oh yeah

brisk zenith
#

because one of the challenge restrictions was "don't use imports"

#

and so joe didn't. :D

rugged sparrow
#

clever

acoustic zinc
#

you had esoteric challenges?! that sounds neat

sick hound
#

i wish we had #define in python

acoustic zinc
#

what for?

formal sandal
#

You can implement it

#

using ast, maybe

brisk zenith
#

i encourage you to do some of them if you want, i can still accept PRs for older challenges ^~^

#

i haven't given out any new challenges in quite some time but i do plan to at some point

acoustic zinc
#

might try it at some point, sounds really cool

formal sandal
#

Any esoteric april fools ideas?

#

!e

f=lambda _:lambda p:((lambda x:x.pop( (lambda:(p,x)in(x(p,x)) )))(x[p]))
import sys
if f([[sys.path]]):
  Truе = False
print(Truе)
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

False
formal sandal
#

finally I can make this work

#

That's a technique I used here before

rugged sparrow
#
>>> sys.excepthook = lambda t,e,c:os.system(e.text[1:]) if hasattr(e,'text') and e.text[0]=='$' else sys.__excepthook__(t,e,c)
>>> $uname 
Darwin
>>> $echo 1
1
>>> ```
formal sandal
#

huh

#

Can you also add support for evaluating lambda calculus?

#

That would be convenient

rugged sparrow
#

yea as long as the first character throws an exception

formal sandal
#

Maybe : (expression)

rugged sparrow
#

!e ```py
: ()

night quarryBOT
#

@rugged sparrow :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     : ()
003 |     ^
004 | SyntaxError: invalid syntax
rugged sparrow
#

keep in mind it only works in the interpreter

#

cause it uses the except hook

formal sandal
#

True

edgy kelp
#

$?` should be good tokens

#

can be pretty much anywhere

#

and you'll get a nice syntax error

rugged sparrow
#

i need a way to continue after that line tho

formal sandal
#

Just insert a space, it will complain about indentation.

edgy kelp
#

Would need to put in your own exception handlind system that would let you continue I think

rugged sparrow
#

yea

#

maybe could use something like brm to enable it in normal scripts

edgy kelp
#

can hook into the site for the simplest thing

#

gets ran before normal code is compiled

rugged sparrow
#

with .pth?

edgy kelp
rugged sparrow
#

you can do import (module);'any onelined code'

edgy kelp
#

well still more convenient there 😄

rugged sparrow
#

true true

snow beacon
#

What if someone made a site encoding that runs a file as if in the interpreter?

rugged sparrow
#

the reason it works in the interpreter is because of how the interpreter handles exceptions differently

edgy kelp
#

and lets you define the excepthook before a syntax error is triggered during compilation

rugged sparrow
#

^ that too

snow beacon
#

An interpreter encoding would let you do things like <> not equals in a script.

rugged sparrow
#

huh i thought you could already

#

weird

snow beacon
#

No, it's interpreter only.

rugged sparrow
#

yea i just tested it

#

weird

rugged sparrow
#

@formal sandal how does that True = False work?

#

ohh

#

the e char is different

rugged sparrow
#

!e

my_import = lambda name, m=lambda n:quit.__class__.__call__.__globals__['sys'].modules.get(n):[
        setattr(m('sys'),'stdin',m('io').StringIO('q')),
        setattr(m('sys'),'stdout',m('io').StringIO()),
        help(name),
        setattr(m('sys'),'stdin',m('sys').__stdin__),
        setattr(m('sys'),'stdout',m('sys').__stdout__),
        m(name)
][-1]

print(my_import('os'))```
night quarryBOT
#

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

<module 'os' from '/usr/local/lib/python3.8/os.py'>
rugged sparrow
#

@brisk zenith does that count as not using imports?

#

actually i guess help probably uses import internally

brisk zenith
#

well, the interpreter itself uses import internally

#

so let's just get rid of that too

true nova
#

esoteric help need, just for understanding:

class DP():
    @property
    def p1(self):
        return self._p1val

    @property
    def p2(self):
        return self._p2val

    print("getters")
    print("p1: ", id(p1), repr(p1), p1.fget, p1.fset)
    print("p2: ", id(p2), repr(p2), p2.fget, p2.fset)

    def __init__(self, *args, **kwargs):
        self._p1val = "p1va"
        self._p2val = "p2va"
            
    @p1.setter
    def p1(self, val):
        self._p1val = val

    print("p1.setter")
    print("p1: ", id(p1), repr(p1), p1.fget, p1.fset)
    print("p2: ", id(p2), repr(p2), p2.fget, p2.fset)

    @p1.setter # on purpose
    def p2(self, val):
        self._p2val = val

    print("p2.setter")
    print("p1: ", id(p1), repr(p1), p1.fget, p1.fset)
    print("p2: ", id(p2), repr(p2), p2.fget, p2.fset)

guess the result

getters
p1:  4457613256 <property object at 0x109b1c7c8> <function DP.p1 at 0x109be1048> None # PyObject1
p2:  4458205416 <property object at 0x109bad0e8> <function DP.p2 at 0x109be10d0> None # PyObject2
p1.setter
p1:  4458366440 <property object at 0x109bd45e8> <function DP.p1 at 0x109be1048> <function DP.p1 at 0x109be11e0> # PyObject3 : PyObject1 was replaced
p2:  4458205416 <property object at 0x109bad0e8> <function DP.p2 at 0x109be10d0> None # PyObject2
p2.setter
p1:  4458366440 <property object at 0x109bd45e8> <function DP.p1 at 0x109be1048> <function DP.p1 at 0x109be11e0> # PyObject3 still there
p2:  4457613256 <property object at 0x109b1c7c8> <function DP.p1 at 0x109be1048> <function DP.p2 at 0x109be1268> # PyObject1 came into the game but was replaced with PyObject3

I am curious why the last thing happens. It seems to me that I could find the answer here https://github.com/python/cpython/blob/224481a8c988fca12f488544edd2f01c0af2a91d/Objects/descrobject.c#L1568
but I cannot find out what method will be called at 1582 line

#

Am I right to ask that type of questions here?

last locust
#
eucl_dist_ints = [[(pos1, pos2), sqrt( sum( [ (pos1[x]-pos2[x])**2 for x in range(3) ] ) )] for pos1,pos2 in combinations(cords,2) if int(sqrt( sum( [ (pos1[x]-pos2[x])**2 for x in range(3) ] ) )) == sqrt( sum( [ (pos1[x]-pos2[x])**2 for x in range(3) ] ) )]
```what's a much shorter (and maybe tidier?) way of doing this? I'm essentially going through pairs of 3d tuples (x,y,z cords) and storing the pairs with a euclidian distance that's an integer
#

The only improvements I can think of (exlcuding removing void spaces and renaming vars) is using walrus on the if statement and importing combinations as cpy [[(pos1, pos2), sqrt( sum( [ (pos1[x]-pos2[x])**2 for x in range(3) ] ) )] for pos1,pos2 in c(cords,2) if int((a:=sqrt( sum( [ (pos1[x]-pos2[x])**2 for x in range(3) ] ) ))) == a ]which saves about 50 chars (or if u include the edited import then 45)

formal sandal
#
sum( [ (pos1[x]-pos2[x])**2 for x in range(3) ] )
sum(  (pos1[x]-pos2[x])**2 for x in range(3)  )
sum(  (pos1[x]-pos2[x])**2 for x in (0,1,2)  )
sum((pos1[x]-pos2[x])**2for x in(0,1,2))
#

And, of course, replace variable names with single characters, remove spaces and all the other stuff.

#
sum((pos1[x]-pos2[x])**2for x in(0,1,2))
sum((a-b)**2for a,b in zip(pos1,pos2))
#

so

[[(p,P),sqrt(sum((a-b)**2for a,b in zip(*p)))]for p in c(coords,2)if int((a:=sqrt(sum((a-b)**2for a,b in zip(*p)))))==a]
#

Will this work?

[[(p,P),a:=sqrt(sum((a-b)**2for a,b in zip(*p)))]for p in c(coords,2)if int(a)==a]
last locust
#

a not defined

#

But you're using some really smart stuff I hadn't thought of lmao

#

@formal sandal

formal sandal
#

!e

print([y:=x+5 for x in range(100) if y%2 == 1])
night quarryBOT
#

@formal sandal :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 |   File "<string>", line 1, in <listcomp>
004 | NameError: name 'y' is not defined
formal sandal
#

!e

print([y for x in range(100) if (y:=(x+5))%2 == 1])
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

[5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99, 101, 103]
formal sandal
#

makes sense

#

because it evaluates the condition first, and only then the element

#

so

[[p,a]for p in c(coords,2)if int(a:=sqrt(sum((a-b)**2for a,b in zip(*p))))==a]
last locust
#

yea, that works

#

This is so much smarter lmao

#

Thanks @formal sandal ❤️

formal sandal
#

You're welcome @last locust

formal sandal
#

Yay! Now my needlessly complex typecheking library supports de Morgan's optimizations.

#
not ((not a) or (not b)) = a and b
zealous widget
#
In [79]: tt1 = TruthTable('~(~p or ~q)')

In [80]: tt2 = TruthTable('p and q')

In [81]: tt1 == tt2
Out[81]: True

In [82]: (tt1 + tt2).display()
┌───┬───┬─────────────┬─────────┐
│ p │ q │ ~(~p or ~q) │ p and q │
├───┼───┼─────────────┼─────────┤
│ F │ F │      F      │    F    │
│ F │ T │      F      │    F    │
│ T │ F │      F      │    F    │
│ T │ T │      T      │    T    │
└───┴───┴─────────────┴─────────┘
#

verified

formal sandal
zealous widget
#

no

formal sandal
#

It looks very cool

zealous widget
formal sandal
#

I am very impressed actually

zealous widget
#

but he uses more pythonic operator precedence i think

#

i just do unary, then left-to-right

#

well, parens first, obviously

#

though it's not hard to change it

formal sandal
#

Maybe it's overkill, but you could use lark-parser

zealous widget
#

what's that

#

i made my own syntax trees

#

if that's what it is

formal sandal
#

lark-parser is a parsing framework that uses EBNF notation

zealous widget
#
In [84]: (tt1 + tt2).trees
Out[84]: [~(~p or ~q), p and q]

In [85]: tt1.trees[0]
Out[85]: ~(~p or ~q)

In [86]: tt1.trees[0].expr
Out[86]: ~p or ~q

In [87]: tt1.trees[0].expr.l
Out[87]: ~p
formal sandal
#

And then you can transform any text source using a convenient transformer

zealous widget
#

i dunno what that is

formal sandal
#

Maybe I will make a lark version of the parser

#

As an example

zealous widget
#

oh, i see, i might update my own regex language and try to use it to specify boolean grammar

#

one day

formal sandal
#

Your own regex language?

zealous widget
#

yeah, it's messy, the truthtable parser is much nicer, i could copy/paste a lot of it

#

i made my own regex for the codejam qualifier though for fun

#

some of it looked like:

    MICRO = "(END or '.' (6 D as microsecond ** END))"
    EXTENDEDTIME = f"(END or 'T' 2 D as hour (END or ':' 2 D as minute (END or ':' 2 D as second {MICRO})))"
    TRUNCATEDTIME = f"(END or 'T' 2 D as hour (END or 2 D as minute (END or 2 D as second {MICRO})))"

    TZEXT = "('Z' as tzd or '-+' as tzd 2 D as tzhour (END or ':' 2 D as tzminute))"
    TZTRUN = "('Z' as tzd or '-+' as tzd 2 D as tzhour (END or 2 D as tzminute))"
#

i parse this into a networkx DAG and walk it to check for correctness of some expression

formal sandal
#

You can recursively parse a subset of XML with regexp...
https://regex101.com/r/FyrACj/1
But, unfortunately, not in python-flavoured regex.

zealous widget
#

regex is unreadable at that point

#

it's one reason i wanted to make my own, so that it's sort of readable, it does make the expressions 10-fold longer

formal sandal
#

True

zealous widget
#

i'll clean it up some day, if nothing else it's a useful tool for building networkx trees really fast

#

that's a nice module

edgy kelp
#

oh that reminded me of the regex for divisibility with 7

formal sandal
#

@zealous widget

import lark
from collections import namedtuple

grammar = """
    start: expr
    ?expr: paren_expr | or_expr | and_expr | not_expr | variable | const

    variable: /(?!(true|false)(?![a-z]))[a-z]+/

    ?paren_expr: "(" expr ")"

    or_expr.1: expr "or" expr
    and_expr.2: expr "and" expr
    not_expr: "~" expr
    
    ?const: true | false
    true: "true" | "T" | "1"
    false: "false" | "F" | "0" 

    %import common.WS
    %ignore WS
"""

parser = lark.Lark(grammar)

Or = namedtuple("Or", "left right")
And = namedtuple("And", "left right")
Not = namedtuple("Not", "expr")
Variable = namedtuple("Var", "name")

tree = parser.parse("(a or b) and b or ~T")

print(tree.pretty())

@lark.v_args(inline=True)
class LogicalTransformer(lark.Transformer):
    or_expr = lambda self, left, right: Or(left, right)
    and_expr = lambda self, left, right: And(left, right)
    not_expr = lambda self, expr: Not(expr)
    variable = lambda self, name: Variable(str(name))
    true = lambda self: True
    false = lambda self: False
    start = lambda self, expr: expr
    
print(LogicalTransformer().transform(tree))
#

Sorry for the lambda methods, I just wanted to make the code more compact.

#

The regexp in variable just makes sure that 'true' and 'false' are not variables. If you just want a single letter, you can do "a".."z", I believe

zealous widget
#

i accept any variable name currently

#

i think i like it better from scratch though

formal sandal
#

Well, your version is more beautiful.

#

lark is just cheating.

#

Maybe you could also create a logical equation solver?

#

Consider this.
Count how many distinct tuples x1, ..., x10 satisfy the relations:

(x1 and ~x2) or (~x1 and x2) or (x3 and x4) or (~x3 and ~x4) = 1
(x3 and ~x4) or (~x3 and x4) or (x5 and x6) or (~x5 and ~x6) = 1
(x5 and ~x6) or (~x5 and x6) or (x7 and x8) or (~x7 and ~x8) = 1
(x7 and ~x8) or (~x7 and x8) or (x9 and x10) or (~x9 and ~x10) = 1
#

So, on the first "step", x1 x2 can take any of the 4 values.

#

If only the first equation would be present, this would be the solution.

#

There are two ways to end up at x3x4 = 00, two ways to end up at x3x4 = 11, 4 ways to end up at x3x4 = 01 and 4 ways to end up at x3x4=10

#

So the answer for 1 equation is 2 + 4 + 4 + 2 = 12

#

In general, you can recursively solve this equation by applying this transformation

#

Maybe there is a way to deduce this transformation programmatically.

#

Tuples of x's can be of any size, it depends on the equation.

#

They can even overlap

zealous widget
#
tt.display()
┌────┬────┬────┬────┬──────────────────────────────────────────────────────────────┐
│ x1 │ x2 │ x3 │ x4 │ (x1 and ~x2) or (~x1 and x2) or (x3 and x4) or (~x3 and ~x4) │
├────┼────┼────┼────┼──────────────────────────────────────────────────────────────┤
│ F  │ F  │ F  │ F  │                              T                               │
│ F  │ F  │ F  │ T  │                              F                               │
│ F  │ F  │ T  │ F  │                              F                               │
│ F  │ F  │ T  │ T  │                              T                               │
│ F  │ T  │ F  │ F  │                              T                               │
│ F  │ T  │ F  │ T  │                              T                               │
│ F  │ T  │ T  │ F  │                              T                               │
│ F  │ T  │ T  │ T  │                              T                               │
│ T  │ F  │ F  │ F  │                              T                               │
│ T  │ F  │ F  │ T  │                              T                               │
│ T  │ F  │ T  │ F  │                              T                               │
│ T  │ F  │ T  │ T  │                              T                               │
│ T  │ T  │ F  │ F  │                              T                               │
│ T  │ T  │ F  │ T  │                              F                               │
│ T  │ T  │ T  │ F  │                              F                               │
│ T  │ T  │ T  │ T  │                              T                               │
└────┴────┴────┴────┴──────────────────────────────────────────────────────────────┘
formal sandal
#

For this specific substitution, you can get the solution to original question by multiplying the solution to this equation by 2^5 because there are 5 a's

zealous widget
#

this reminds me of the 24 solver from earlier

#

or you can use xor

#

oh we're solving this:

In [94]: tt.display()
┌────┬────┬────┬────┬────────────────────────────┐
│ x1 │ x2 │ x3 │ x4 │ (x1 xor x2) or (x3 <-> x4) │
├────┼────┼────┼────┼────────────────────────────┤
│ F  │ F  │ F  │ F  │             T              │
│ F  │ F  │ F  │ T  │             F              │
formal sandal
#

Well, yes

#

((x1 xor x2) or (x3 <-> x4)) and ((x3 xor x4) or (x5 <-> x6)) and ...

zealous widget
#

it was obfuscated

#

i thought it was xors all the way across

formal sandal
#

Maybe karma exists...

#

I got an error: ... has no attribute "curry"

#

I was very surprised. I printed out dir(can_user_view), and "curry" was there.

#

Then I printed out can_user_view.curry, and it printed it successfully.

#

The problem was that I accidentally typed a cyrillic "с" in "curry".

#

I guess I typed in "сгккн" instead of curry, then noticed that my keyboard layout was wrong, but I only erased the last 4 characters because... I guess, it looked fine

zealous widget
#
[ A     A + B]
[ B       B  ]

this is close to the fibonacci matrix

formal sandal
#

Well, it will show a fibonacci pattern.

#

Actually, most of these equations will

#

Well, not most. Many

zealous widget
#

ever done fast fibonacci with it?

#

i guess you could do the same with the above matrix:

In [99]: def npfib(n):
    ...:     return np.linalg.matrix_power(np.array([[1, 1], [1, 0]], dtype=object), n)[0, 1]
    ...: npfib(1001)
Out[99]: 70330367711422815821835254877183549770181269836358732742604905087154537118196933579742249494562611733487750449241765991088186363265450223647106012053374121273867339111198139373125598767690091902245245323403501
marsh void
#

lark is thicc

formal sandal
marsh void
#

aaa math

zealous widget
#

that's neat

#
In [101]: def almostfib(m, n):
     ...:     zero = np.zeros((m, m), dtype=object)
     ...:     zero[0] = 1
     ...:     zero[:,0] = 1
     ...:     return np.linalg.matrix_power(zero, n)[0, 1]

In [102]: almostfib(5, 3)
Out[102]: 5

In [103]: almostfib(5, 4)
Out[103]: 9

In [104]: almostfib(5, 5)
Out[104]: 29

In [105]: almostfib(5, 6)
Out[105]: 65
bitter iris
#

wow, last messages are mind blowing

formal sandal
#

You can also compute derivatives like this.

#

You compute the Taylor series and express a function as a polynomial.

#

Store that polynomial as a vector.

#

Then apply the derivative matrix, and you have a derivative of that function (approximated around some point)

#

But you'll still have to find the derivative for the Taylor series, so that's kinda very stupid.

formal sandal
#

It actually works:

[   ({'username': 'alice', 'password': '123', 'post_uid': 1},)   ]
    get_user
      => ({'username': 'alice', 'password': '123', 'post_uid': 1}, {'username': 'alice', 'password': '123', 'age': 42})
    log_in
      => ({'username': 'alice', 'password': '123', 'age': 42}, 1)
    get_post
      => ({'username': 'alice', 'password': '123', 'age': 42}, {'uid': 1, 'text': 'Lorem ipsum', 'who_can_view': ['alice', 'bob']})
    check_permission
      => {'uid': 1, 'text': 'Lorem ipsum', 'who_can_view': ['alice', 'bob']}
{'uid': 1, 'text': 'Lorem ipsum', 'who_can_view': ['alice', 'bob']}


[   ({'username': 'alice', 'password': 'wrong', 'post_uid': 1},)   ]
    get_user
      => ({'username': 'alice', 'password': 'wrong', 'post_uid': 1}, {'username': 'alice', 'password': '123', 'age': 42})
    log_in
      => {'_': 'error', 'msg': 'Incorrect password'}
{'_': 'error', 'msg': 'Incorrect password'}


[   ({'username': 'alice', 'password': '123', 'post_uid': 1000},)   ]
    get_user
      => ({'username': 'alice', 'password': '123', 'post_uid': 1000}, {'username': 'alice', 'password': '123', 'age': 42})
    log_in
      => ({'username': 'alice', 'password': '123', 'age': 42}, 1000)
    get_post
      => {'_': 'error', 'msg': 'Invalid post UID'}
{'_': 'error', 'msg': 'Invalid post UID'}
#

Basically, it's a pipe with built-in support of dependency injection:

@ask("fetch user")
def get_user(request: Request, fetch):
    return inject([
        (Error, lambda e: e),
        (Any,   lambda user: (request, user)),
    ])  ( fetch(request["username"]) )
#

@ask doesn't create a partial function, it just adds a list of names to a function.

#

So that all the functions can be defined tested like normal functions.

#

The functions are very polite as well. You don't tell the database to fetch a user. You ask the pipe executor to kindly provide you a function.

gilded orchid
#

someone here should make a coronavirus class, that requires you to washHands() every so often otherwise bad ctypes stuff starts happening

zealous widget
#
from random import random


class InfectedError(Exception):
    pass


def infect(cls):
    class Wrapper:
        def __init__(self, *args, **kwargs):
            self.wrapped = cls(*args, **kwargs)

        def __getattr__(self, name):
            if random() < .5:
                raise InfectedError
            return getattr(self.wrapped, name)
    return Wrapper


@infect
class Test:
    name = 'test'
    def show(self):
        print(self.name)
#
In [140]: a = Test()

In [141]: a.show()
test

In [142]: a.show()
Traceback (most recent call last):

  File "<ipython-input-142-97d3136b2c17>", line 1, in <module>
    a.show()

  File "/home/salt/Documents/Python/notepad.py", line 17, in __getattr__
    raise InfectedError

InfectedError
#

instead of checking random you can keep a counter, and require a washhands to reset it

#
class InfectedError(Exception):
    pass


def infect(cls):
    class Wrapper:
        def __init__(self, *args, **kwargs):
            self.count = 0
            self.wrapped = cls(*args, **kwargs)

        def __getattr__(self, name):
            if name == 'washhands':
                return self.washhands

            self.count += 1
            if self.count > 5:
                raise InfectedError
            return getattr(self.wrapped, name)

        def washhands(self):
            self.count = 0

    return Wrapper


@infect
class Test:
    name = 'test'
    def show(self):
        print(self.name)
formal sandal
#

Maybe an infected class should randomly infect other classes it interacts with.

#

I guess you could mess with stack frames.

zealous widget
#

can you just replace their __getattr__ method and give them a count attribute

#

i don't know how to tell if it's interacting with an object though

#

if it's returning an object, it could return an infected one

#

that's easy enough

zealous widget
#

it is not easy enough

formal sandal
#

very informative indeed

zealous widget
#

the best i can do is randomly infect attributes if they have a __getattr__ method

#

i'm not the best esoteric pythonista

brisk zenith
#

this reminds me of an idea that was discussed here which makes python follow the idea of constantly increasing entropy

#

so strings would slowly become randomised

#

lists would be slowly shuffled

#

etc.

marsh void
#

Okay I am working on a funny thing

#

basically takes all your code and rotates it π/2 counter-clockwise

zealous widget
#

i appreciate the radians

marsh void
#

same 💪

gilded orchid
#

radians is objectively worse than degrees

zealous widget
#

false

proper vault
#

0-1 best angle system

marsh void
#

NO

#

god no

#

radians are useful

#

degrees are for kids!

zealous widget
#

radians are by far the most intuitive

proper vault
#

0.5 - half circle
1/4 - quarter circle
3/4 - three fourths circle
1/3 - third of a circle
doesnt get more intuitive than that

zealous widget
#

false

#

if i walk so that my angle is pi/4 radians along a circle of radius 1, you know how far i've traveled?

brisk zenith
#

my argument for radians is always "yes but can you do calculus with it"

thin trout
#

Radians are only useful if you want to do some calculus, like trigonometry

proper vault
#

ye, for higher math radians all the way.

thin trout
#

If not, that's just painful

zealous widget
#

use some calculus, like trigonometry

brisk zenith
#

lmao

zealous widget
#

what

brisk zenith
#

:D

proper vault
#

if you walk 1/8 of a unit circle, you walked tau * 1/8 units of distance

hard mulch
#

i like degrees

zealous widget
#

people that like degrees were taught wrong, and i sympathize

brisk zenith
#

gradians :^)

hard mulch
#

whenever i have to respond in radians on a test (high schooler) i just do it in degrees then convert

proper vault
#

fractions of circle are also nicer for programming, because you get a rough idea of how much the angle just by printing a float, whereas with radians you have no reference unless you /pi or sth

zealous widget
#

our teacher made us memorize values for sin/cos/tan for pi/2, pi/3, pi/4, pi/6 * n

formal sandal
#

Ew...
sin'(degrees) = pi / 180 * cos(degrees)

proper vault
#

most teachers did that I would hope

hard mulch
#

eh

zealous widget
#

i literally use a pi constant

#

when programming

hard mulch
#

i don't like memorization\

zealous widget
#

so it makes no difference

brisk zenith
#

i have to memorise those values for radians and degrees

#

i mean, i don't actually memorise them because my calculator provides their exact value

#

but it's still recommended apparently

zealous widget
#

well, you only memorize for one of them

#

you can always convert to the other

formal sandal
#

sin^2(pi/4) = 1/2
sin^2(pi/6) = 1/4
That's it.

#

Then just imagine a unit circle in your head.

zealous widget
#

1/sqrt(2) i think

brisk zenith
#

they said sin²(...)

zealous widget
#

oh

#

sure nuff

#

weird

brisk zenith
#

indeedy

proper vault
#

makes it faster to get cos from it

brisk zenith
#

true enough.

zealous widget
#

well, it's the same for pi/4

proper vault
#

honestly, if I am actually doing trig, I just draw a unit circle, makes it faster for me

formal sandal
#

It can encode the same message in many different ways, but it cannot encode some messages.

#
In [9]: encrypt_message("python")
Out[9]: '[[[[[[[[[]]]]]]]]][[[[[[]]]]]][[]][[]][[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]][[[[[[]]]]]][[]][[[]]][[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]][[[]]][[]][[[[[[[]]]]]]][[[[[[[[[]]]]]]]]][[[[[[[[[[[[[[[]]]]]]]]]]]]]]][[]][[[]]][[[[[[[[[[[[]]]]]]]]]]]][[[[[[[]]]]]]][[]][[[]]][[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]][[[[[[]]]]]][[]][[[]]]'

In [10]: encrypt_message("python")
Out[10]: '[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]][[[[[[[[[]]]]]]]]][[]][[]][[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]][[[[]]]][[]][[[[[]]]]][[]][[[[[[[[[[[[[]]]]]]]]]]]]][[]][[[[[[]]]]]][[[[[[[[[]]]]]]]]][[[[[[[[[[[[[[[]]]]]]]]]]]]]]][[]][[[]]][[[[[[[[[[[]]]]]]]]]]][[[[[[[[[[[[[[[]]]]]]]]]]]]]]][[]][[[]]][[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]][[[[[[[[[[]]]]]]]]]][[]][[[]]]'

In [11]: encrypt_message("python")
Out[11]: '[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]][[[[[[[[[[[[]]]]]]]]]]]][[]][[[]]][[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]][[[[[[]]]]]][[]][[[[[]]]]][[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]][[[[]]]][[]][[[[[]]]]][[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]][[[[[[[[[[[[]]]]]]]]]]]][[]][[[]]][[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]][[[[]]]][[]][[[]]][[[[[[[[]]]]]]]][[[[[[[[[[[[[]]]]]]]]]]]]][[]][[]]'
marsh void
#

¯_(ツ)_/¯

formal sandal
#

)_/¯ツ¯\_(

zealous widget
#

my only guess is that a group of brackets is some number

#
In [393]: decode_brackets('[[[[[[[[[]]]]]]]]][[[[[[]]]]]][[]][[]][[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]][[[[[[]]]]]][[]][[[]]][[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]][[[]]][[]][[[[[[[]]]]]]][[[[[[[[[]]]]]]]]][[[[[[[[[[[[[[[]]]]]]]]]]]]]]][[]][[[]]][[[[[[[[[[[[]]]]]]]]]]]][[[[[[[]]]]]]][[]][[[]]][[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]][[[[[[]]]]]][[]][[[]]]')
Out[393]: [4, 3, 1, 1, 10, 3, 1, 1, 11, 1, 1, 3, 4, 7, 1, 1, 6, 3, 1, 1, 13, 3, 1, 1]

In [394]: decode_brackets('[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]][[[[[[[[[]]]]]]]]][[]][[]][[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]][[[[]]]][[]][[[[[]]]]][[]][[[[[[[[[[[[[]]]]]]]]]]]]][[]][[[[[[]]]]]][[[[[[[[[]]]]]]]]][[[[[[[[[[[[[[[]]]]]]]]]]]]]]][[]][[[]]][[[[[[[[[[[]]]]]]]]]]][[[[[[[[[[[[[[[]]]]]]]]]]]]]]][[]][[[]]][[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]][[[[[[[[[[]]]]]]]]]][[]][[[]]]')
Out[394]: [13, 4, 1, 1, 9, 2, 1, 2, 1, 6, 1, 3, 4, 7, 1, 1, 5, 7, 1, 1, 8, 5, 1, 1]

In [395]: decode_brackets('[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]][[[[[[[[[[[[]]]]]]]]]]]][[]][[[]]][[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]][[[[[[]]]]]][[]][[[[[]]]]][[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]][[[[]]]][[]][[[[[]]]]][[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]][[[[[[[[[[[[]]]]]]]]]]]][[]][[[]]][[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]][[[[]]]][[]][[[]]][[[[[[[[]]]]]]]][[[[[[[[[[[[[]]]]]]]]]]]]][[]][[]]')
Out[395]: [9, 6, 1, 1, 10, 3, 1, 2, 10, 2, 1, 2, 13, 6, 1, 1, 12, 2, 1, 1, 4, 6, 1, 1]
zealous widget
#

that just counts the groupings

#

looks incorrect though

#

lemme retry

thin trout
#

It seems like if the number of brackets is useful number, it has a x4 overhead

formal sandal
#

I don't know whether a human or even a computer can reverse-engineer this algorithm. I mean, if I give thousands of examples, some computer system might figure out a decryption routine, but it won't tell you much about the algorithm.

zealous widget
#

oh i divided everything by 2 for no reason

#
In [399]: decode_brackets('[[[[[[[[[]]]]]]]]][[[[[[]]]]]][[]][[]][[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]][[[[[[]]]]]][[]][[[]]][[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]][[[]]][[]][[[[[[[]]]]]]][[[[[[[[[]]]]]]]]][[[[[[[[[[[[[[[]]]]]]]]]]]]]]][[]][[[]]][[[[[[[[[[[[]]]]]]]]]]]][[[[[[[]]]]]]][[]][[[]]][[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]][[[[[[]]]]]][[]][[[]]]')
Out[399]: [9, 6, 2, 2, 21, 6, 2, 3, 23, 3, 2, 7, 9, 15, 2, 3, 12, 7, 2, 3, 26, 6, 2, 3]
#

but this isn't useful to me

formal sandal
marsh void
#

bruh

formal sandal
#

Also count the number of brackets

#

I mean, the output numbers

zealous widget
#

well, the grouping size seems to be between 1-27

formal sandal
#

I meant 'the number of output numbers'

#

I'll give you a hint that this encryption algorithm has something to do with natural language processing

zealous widget
#
In [409]: n
Out[409]: [24, 10, 2, 3, 22, 2, 2, 5, 8, 17, 2, 2, 23, 5, 2, 3, 9, 4, 2, 4, 4, 15, 2, 2, 9, 14, 2, 3, 15, 4, 2, 4, 17, 7, 2, 3, 13, 4, 2, 6, 9, 4, 2, 4, 2, 2, 2, 8, 21, 15, 2, 6, 2, 13, 2, 3, 16, 8, 2, 2, 17, 15, 2, 4, 7, 15, 2, 4, 3, 14, 2, 3, 28, 2, 2, 5, 26, 13, 2, 5, 8, 16, 2, 10, 5, 11, 2, 5, 24, 13, 2, 7, 19, 9, 2, 5, 19, 15, 2, 2, 24, 5, 2, 3, 19, 3, 2, 4]

In [410]: len(n)
Out[410]: 108
#

is that like the speak and say sequence

formal sandal
#

Don't know what that is.

zealous widget
#
1
11
21
1211
111221
312211

this sequence

formal sandal
#

Yes, I've looked it up

zealous widget
#

famous in recreational mathematics, probably because conway

formal sandal
#

You probably shouldn't waste time on this encryption... It sounded better in my head, like most of my ideas here

zealous widget
#

i do see a pattern

#

the bigger numbers seem to be pretty evenly spaced at least

formal sandal
#

true

#

Another hint: 432

zealous widget
#

are all the small numbers junk

formal sandal
#

no

#

Maybe some messages can be decoded without some of the small numbers, but I'm not sure about that

#

Yes, some messages can be decoded without some of the small numbers.

#

For instance, the sequence (2, 12, 2, 2) can be decoded without the last two numbers

#

Maybe it will be a bit easier to decode if you subtract 2 from each number.

#

Since this^ is possible, then all the numbers are 2 and greater.

#

x[] and x aren't possible

#

Have you found the connection between message length and sequence length?

zealous widget
#

i've only tried python

#

but it seems that they're in groups of 4

formal sandal
#

yep

zealous widget
#

and the start of the group is usually the biggest number

formal sandal
#

You can try and convert all the messages in a batch

zealous widget
#

or at least, the first two numbers

#

are big and the last ones are small

formal sandal
#

You know how js lets you do that:

a = 1
b = 2
x = {a, b}
// equivalent to:
x = {a: a, b: b}
#

well

#

!e

import inspect

def jsobject(*names):
    frame = inspect.currentframe().f_back
    return {key: frame.f_locals[key] for key in names}

a = 1
b = 2
c = 3

obj = jsobject("a", "b", "c")

print(obj)
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

{'a': 1, 'b': 2, 'c': 3}
glacial rampart
#

wew

#

gj

marsh void
#

heh

hushed chasm
#

!e

import sys
print(sys.version)
night quarryBOT
#

@hushed chasm :white_check_mark: Your eval job has completed with return code 0.

001 | 3.8.0 (default, Nov 23 2019, 05:49:00) 
002 | [GCC 8.3.0]
hushed chasm
#

Can someone tell me how this server executes the code?

edgy kelp
hushed chasm
#

Thanks I saw the command here so thought I’d ask in the same place, still exploring all the channels, there’s so many

edgy kelp
#

this is for golfing and other weird stuff with python

#

the command's allowed here because it's nice to show the weird stuff but generally when not relevant to here you'd run them in #bot-commands

hushed chasm
#

It’s pretty cool, on another server I’m we also allow this type of thing with a much simpler tool written in Go. But that server is for like all languages not just Python. I still appreciate this, definitely encourages people to show cool little snippets of code in action.

#

Where may I share other discord servers?

sudden osprey
#

We don't allow advertising so unless the server is whitelisted you will not be able to post the link

hushed chasm
#

Makes sense

#

Maybe you know of the community I’m talking about -> EngineerMan

#

I’m not advertising just sharing cos I got a link for this server from there.

sudden osprey
#

I can't say I've heard of it. Is it a big server?

hushed chasm
#

It’s a few thousand in size

#

Lemme check quick

#
Discord members: [7357] + 14
Newcomers:       [28] 
YouTube subs:    [305000] 
YouTube videos:  [142] 
YouTube views:   [9811000] + 27060````last run: 2090 minutes ago`
#

Anyways

#

Was just curious about the bot

#

I’ll keep looking through the rest of the channels

ivory torrent
#
print("Do you want 2 or 3 values?")
z = input()
if z == 'two':
    #code for the values
    print("Value 1:"); a = int(input())
    print("Value 2:"); b = int(input())
    print("Choose your operator (plus, minus, multiply, divide, or equals).")
    #calculation code
    op = input()
    if op == "plus":
        print(a+b)
    elif op == "minus":
        print(a-b)
    elif op == "multiply":
        print(a*b)
    elif op == "divide":
        print(a/b)
    elif op == "equals":
        if (a==b):
            print('True.')
        elif (a>b):
            print("False, a > b.")
        else:
            print('False, a < b.')
    #else code/error
    else:
        print("Sorry about that. Looks like you made a typo. Try again.")
elif z == '2':
        #code for the values
    print("Value 1:"); a = int(input())
    print("Value 2:"); b = int(input())
    print("Choose your operator (plus, minus, multiply, divide, or equals).")
    #calculation code
    op = input()
    if op == "plus":
        print(a+b+c)
    elif op == "minus":
        print(a-b-c)
    elif op == "multiply":
        print(a*b*c)
    elif op == "divide":
        print(a/b/c)
    elif op == "equals":
        if (a==b):
            print('True.')
        elif (a>b):
            print("False, a > b.")
        else:
            print('False, a < b.')
    #else code/error
    else:
        print("Sorry about that. Looks like you made a typo. Try again.")
else:
    #code for the values
    print("Value 1:"); a = int(input())
    print("Value 2:"); b = int(input())
    print("Value 3:"); c = int(input())
    print("Choose your operator (plus, minus, multiply, or divide).")
    #calculation code
    op = input()
    if op == "plus":
        print(a+b+c)
    elif op == "minus":
        print(a-b-c)
    elif op == "multiply":
        print(a*b*c)
    elif op == "divide":
        print(a/b/c)
    #else code/error
    else:
        print("Sorry about that. Looks like you made a typo. Try again.")
hushed chasm
#

I doubt that will work with input()

ivory torrent
#

it does

hushed chasm
#

The bot?

#

I’m not doubting a local instance

#

Just that the bot can’t accept input

proper vault
#

!e

import sys
from io import StringIO
newin = StringIO("Hello World\nPeter\n24\n")
sys.stdin = newin
print(f"you sent {input()}, {input()} age {input()}")
night quarryBOT
#

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

you sent Hello World, Peter age 24
hushed chasm
#

Dude! Where’s my car?! That’s amazing I did not know we could do that

#

I take it it reads by lines

proper vault
#

for stdout, you get contextlib.redirect_stdin context manager, but for stdin, you have to manually set (and reset when it comes to it)

#

input reads until newline

hushed chasm
#

I need to look into this io lib, I’ve never used it

#

Okay question for you @proper vault, since your code example is for a a specific amount of input lines, how would I wrap that in a loop to keep reading until there is nothing left to input?

#

I’m not sure if I’m phrasing correctly

proper vault
#

if you know you are getting a StringIO, you can .read(32) until it returns an empty string

#

or some other IO object

#

if you are reading from stdin, it gets a lot more complicated

hushed chasm
#

!e

import sys
from io import StringIO
newin = StringIO("Hello World\nPeter\n666\n")
sys.stdin = newin
while a:=input():
    print(f"{input()}")
night quarryBOT
#

@hushed chasm :x: Your eval job has completed with return code 1.

001 | Peter
002 | Traceback (most recent call last):
003 |   File "<string>", line 6, in <module>
004 | EOFError: EOF when reading a line
hushed chasm
#

Oops my bad

proper vault
#

ye, input() is not meant for non-stdin stuff

hushed chasm
#

!e

import sys
from io import StringIO
newin = StringIO("Hello World\nPeter\n666\n")
sys.stdin = newin
while a:=input():
    print(f"{a}")
night quarryBOT
#

@hushed chasm :x: Your eval job has completed with return code 1.

001 | Hello World
002 | Peter
003 | 666
004 | Traceback (most recent call last):
005 |   File "<string>", line 5, in <module>
006 | EOFError: EOF when reading a line
hushed chasm
#

Ah

#

Okay that kinda worked

#

So just gotta figure out how to detect EOF with code

#

This is actually awesome

#

!e

import sys
from io import StringIO
newin = StringIO("Hello World\nPyro\n666\n")
sys.stdin = newin
try:
    while a:=input():
        print(f"{a}")
except EOFError:
    print("nothing left")
night quarryBOT
#

@hushed chasm :white_check_mark: Your eval job has completed with return code 0.

001 | Hello World
002 | Pyro
003 | 666
004 | nothing left
hushed chasm
#

Booyah

formal sandal
#

@sick hound

#

!e

import inspect

class ContextCapturer:
     def __enter__(self):
         self.frame = inspect.currentframe().f_back
         self.begin_locals = list(self.frame.f_locals)
         
     def __exit__(self, *_):
         self.diff_locals = {k: self.frame.f_locals[k] for k in {*self.frame.f_locals} - {*self.begin_locals}}

class MyClass:
     capturer = ContextCapturer()
     with capturer:
         def my_func(a, b, c): pass
         hello = "world"

print(MyClass.capturer.diff_locals)
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

{'hello': 'world', 'my_func': <function MyClass.my_func at 0x7f4bfc148ca0>}
formal sandal
#

This (hacky, admittedly) way, you can register your states without creating a separate method for creating them and packing them in a dict.

night quarryBOT
#

@hushed chasm :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 39
002 |     elif 
003 |         ^
004 | SyntaxError: invalid syntax
#

@hushed chasm :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 39
002 |     elif:
003 |         ^
004 | SyntaxError: invalid syntax
#

:incoming_envelope: :ok_hand: applied mute to @hushed chasm until 2020-04-03 20:20 (9 minutes and 59 seconds) (reason: newlines rule: sent 126 newlines in 10s).

formal sandal
#

oof

haughty halo
#

!unmute 186436642356068352

night quarryBOT
#

:incoming_envelope: :ok_hand: pardoned infraction mute for @hushed chasm.

hushed chasm
#

thanks

#

so I gotta wait 10 seconds between pastes ey

#

I like your name bro

haughty halo
#

thanks

hushed chasm
#

🔥

#

!e

import sys
from io import StringIO
newin = StringIO("2\nplus\n")
sys.stdin = newin

def get_input():
    try:
        return input()
    except EOFError:
        return None

print("Do you want 2 or 3 values?")
z = get_input()
if z == 'two' or z == '2':
    #code for the values
    print("Value 1:"); a = int(get_input())
    print("Value 2:"); b = int(get_input())
    print("Choose your operator (plus, minus, multiply, divide, or equals).")
    #calculation code
    op = get_input()
    if op == "plus":
        print(a+b)
    elif op == "minus":
        print(a-b)
    elif op == "multiply":
        print(a*b)
    elif op == "divide":
        print(a/b)
    elif op == "equals":
        if (a==b):
            print('True.')
        elif (a>b):
            print("False, a > b.")
        else:
            print('False, a < b.')
    #else code/error
    else:
        print("Sorry about that. Looks like you made a typo. Try again.")
else:
    #code for the values
    print("Value 1:"); a = int(get_input())
    print("Value 2:"); b = int(get_input())
    print("Value 3:"); c = int(get_input())
    print("Choose your operator (plus, minus, multiply, or divide).")
    #calculation code
    op = get_input()
    if op == "plus":
        print(a+b+c)
    elif op == "minus":
        print(a-b-c)
    elif op == "multiply":
        print(a*b*c)
    elif op == "divide":
        print(a/b/c)
    #else code/error
    else:
        print("Sorry about that. Looks like you made a typo. Try again.")
night quarryBOT
#

@hushed chasm :x: Your eval job has completed with return code 1.

001 | Do you want 2 or 3 values?
002 | Value 1:
003 | Traceback (most recent call last):
004 |   File "<string>", line 16, in <module>
005 | ValueError: invalid literal for int() with base 10: 'plus'
hushed chasm
#

!e

import sys
from io import StringIO
newin = StringIO("2\n1\n2\nplus\n")
sys.stdin = newin

def get_input():
    try:
        return input()
    except EOFError:
        return None

print("Do you want 2 or 3 values?")
z = get_input()
if z == 'two' or z == '2':
    #code for the values
    print("Value 1:"); a = int(get_input())
    print("Value 2:"); b = int(get_input())
    print("Choose your operator (plus, minus, multiply, divide, or equals).")
    #calculation code
    op = get_input()
    if op == "plus":
        print(a+b)
    elif op == "minus":
        print(a-b)
    elif op == "multiply":
        print(a*b)
    elif op == "divide":
        print(a/b)
    elif op == "equals":
        if (a==b):
            print('True.')
        elif (a>b):
            print("False, a > b.")
        else:
            print('False, a < b.')
    #else code/error
    else:
        print("Sorry about that. Looks like you made a typo. Try again.")
else:
    #code for the values
    print("Value 1:"); a = int(get_input())
    print("Value 2:"); b = int(get_input())
    print("Value 3:"); c = int(get_input())
    print("Choose your operator (plus, minus, multiply, or divide).")
    #calculation code
    op = get_input()
    if op == "plus":
        print(a+b+c)
    elif op == "minus":
        print(a-b-c)
    elif op == "multiply":
        print(a*b*c)
    elif op == "divide":
        print(a/b/c)
    #else code/error
    else:
        print("Sorry about that. Looks like you made a typo. Try again.")
night quarryBOT
#

@hushed chasm :white_check_mark: Your eval job has completed with return code 0.

001 | Do you want 2 or 3 values?
002 | Value 1:
003 | Value 2:
004 | Choose your operator (plus, minus, multiply, divide, or equals).
005 | 3
formal sandal
#

You can reduce the number of newlines by inlining some ifs

hushed chasm
#

@ivory torrent

#

got your code working with @proper vault's help

#

Thanks for advice @formal sandal I'm just running oddrogue's code not bothered on making it better

#

I'd reduce that quite a lot if it were my code

marsh void
#

Uhm

formal sandal
#

If you just want to run the code, you can do that in #bot-commands

marsh void
#

You sure you need a calculator in esoteric python

#

I mean, with eval you can make calculator in what, 7 lines

formal sandal
#
print(eval(input()))
marsh void
#
allowed = set('0123456789.+-/*( )')
while True:
    try:
        print(eval(''.join(char for char in input() if char in allowed)))
    except Exception:
        print('error')```
#

6 lines

#

no one-liners intended

#
(lambda allowed: any(print(eval(''.join(char for char in input() if char in allowed))) for _ in iter(int, 1)))(set('0123456789.+-/*( )'))``` okay well
bitter iris
#

AST way of calculators

#
import ast
SAFE_NODES = (ast.BinOp, ast.Constant, ast.UnaryOp, ast.operator, ast.unaryop)
while True:
    tree = ast.parse(input(), mode="eval")
    if any(not isinstance(node, SAFE_NODES) for node in ast.walk(tree.body)):
        print("error")
    else:
        print(eval(compile(tree, "<calc>", "eval")))
ivory torrent
#

works for me

marsh void
#

Was not a matter of working or not

#

@bitter iris ohh, you should've written a parser instead!

ivory torrent
#

oh

vague gust
#

@marsh void ```py
from ctypes import *

text = input().encode()
orig_length = len(text)
text += b"\0" * ((8 - orig_length % 8) % 8)
length = len(text)
long_length = length // 8
print(
f"from ctypes import *\nprint(cast(pointer(ARRAY({long_length}, c_longlong)({repr(cast(pointer(ARRAY(length, c_char)(*text)),POINTER(ARRAY(long_length,c_longlong)))[0][:long_length])[1:-1]})), POINTER(ARRAY({length}, c_char)))[0][:{orig_length}].decode())"
)

#

I don't know how it works

#

or why it works

#

I saved it from here a while ago iirc

marsh void
#

haha

#

!e py import ctypes t = 0, ctypes.c_longlong.from_address(id(t) + 24).value = id(t) print(t)

night quarryBOT
#

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

((...),)
marsh void
#

@vague gust hey have you seen this one though

vague gust
#

huh

marsh void
#

yup

#

self-containing tuple

brisk zenith
#

you can do that with the python API without wonky memory fiddling.

#

!e py import ctypes t = (0,) ctypes.pythonapi.PyTuple_SetItem( ctypes.c_void_p(id(t)), ctypes.c_ssize_t(0), ctypes.c_void_p(id(t)) ) print(t) print(t[0] is t)

night quarryBOT
#

@brisk zenith :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 | SystemError: Objects/tupleobject.c:169: bad argument to internal function
brisk zenith
#

wot

#

wait the bot was updated a while ago, it might be that. i'll look into getting it working though

#

PyTuple_SetItem is definitely a thing though.

marsh void
#

Yeah just read about it

#

okay

rugged sparrow
acoustic zinc
#

what happens if you do @property and @staticmethod on something?

acoustic zinc
#

!e

class a:
    @property
    @staticmethod
    def b():
        return 1

print(a.b)
night quarryBOT
#

@acoustic zinc :white_check_mark: Your eval job has completed with return code 0.

<property object at 0x7f1c44cfc360>
acoustic zinc
#

weird

#

!e

class a:
    @staticmethod
    @property
    def b():
        return 1

print(a.b)
night quarryBOT
#

@acoustic zinc :white_check_mark: Your eval job has completed with return code 0.

<property object at 0x7fbaf832b360>
brisk zenith
#

@marsh void who said i disliked this channel being flooded with C? i quite like it if it's being used to mess with stuff :D

marsh void
#

I heard someone complaining about esoteric-python being pretty much esoteric-cpython

#

I swear it was ya :D

brisk zenith
#

haha, yes i remember that. i think it was me and pastebean trying to do something that was dodgy in C which, although it would help us do something dodgy in python by extension, wasn't directly related to python itself in any way

#

i think it was trying to find all references to a specific C function pointer in memory and replacing them with a different function pointer using C

#

which of course, isn't python.

marsh void
#

haha yep

brisk zenith
#

but using C specifically to mess with cpython internally is fine by me. i think some of the higher staff may disagree with that so don't take my word for it though.

acoustic zinc
#

anyone know how the @ staticmethod and @property decorators work when you use both?

brisk zenith
#

hmm..

#

well, i expect it depends on the order in which you call them.

#

i don't really know much about the behaviour of this sort of thing internally so i'm not sure myself

acoustic zinc
#

fair enough

edgy kelp
#

I'd guess they need an instance

#

would check the docs for descriptors if you want to look at it more

stark fable
#

hmmmmmm

#

well i'm fairly sure staticmethod would expect a callable

#

which a property isn't

#
>>> @property
... def test(self):
...     return 4
...
>>> test(4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'property' object is not callable```
brisk zenith
#

yup, that's why i said it depends on the order

#

if you do property(staticmethod(method)) then it might be functional

tribal moon
#

GUI

#
(lambda _del: _del((lambda start: start((lambda file: file.write('''x=msgbox ("SomeDude rules" ,0, "and u know it")'''))(open('onelinegui.vbs', 'w+'))))(lambda _s: __import__('subprocess', level=0).__dict__['call']('onelinegui', shell=True))))(lambda _r: __import__('os', level=0).__dict__['remove']('onelinegui.vbs'))```
clever matrix
#

when I feel depressed I always lurk this channel

#

it fills me with even more dread so the thing I was worried about just clears up, like a stuffed nose

spark marsh
clever matrix
#

indeed

formal sandal
#

Is there a problem in programming that cannot be solved by creating a new domain-specific language?

#

Basically it's a series of logical statement. Each change made to the post will be filtered through this metapermission system. If it violates one of the logical equations, the change will be denied.

#

When creating some object, you can select your metapermission that can't be changed later.

#

Of course, the end user can choose from a list of options. But under the hood they will be expressed in this DSL.

bitter iris
#

Import expressions implementation with freesyntax

from freesyntax.factory import RuleFactory
from freesyntax.grammar import Match, Optional, Or, Rule, Token, Unit
from freesyntax.structs import (
    AutoLeaf,
    Call,
    Name,
    Node,
    String,
    Symbols,
    Tokens,
)

factory = RuleFactory()
factory.register_token("!", "FUCKOFF")


@factory.trailer(
    Or[
        Unit[Match["("], Optional[Rule["arglist"]], Match[")"],],
        Unit[Match["["], Rule["subscriptlist"], Match["]"],],
        Unit[Match["."], Token["NAME"],],
    ],
    Optional[Token["FUCKOFF"]],
)
def fix_trailer(trailer):
    if trailer.children[-1].type == Tokens.FUCKOFF:
        trailer.children[-1].remove()
        start = trailer.parent.children.index(trailer)
        children = trailer.parent.children[: start + 1]
        for child in children[1:]:
            child.remove()

        import_module = "".join(map(str, children))
        import_module = String(repr(import_module.strip()))
        children[0].replace(Call(Name("__import__"), [import_module]))


print(
    factory.transform(
        """
with open('file') as file:
    data = file.read()  # read a file!
    editor = gd.api!.Editor.from_string(data)
"""
    )
)
formal sandal
#

This goes well with FUCK codeblocks.

#

Oh, you did them as well.

bitter iris
#

looks like highlighter can't highlight multiline decorators properly

stark fable
#

probably because it just sees an @ at the beginning of a line and goes "oh a decorator" and colours the rest of the line red

#

instead of actually looking at brackets or looking for a def or anything like that

fallen heath
#

It's because it's an older version of highlight.

vague gust
#

huh that's cool

thin trout
#

TIL that if obj is an instance of MyClass and .method() an instance method of MyClass, then

obj.method()```is equal to
```py
MyClass.method(obj)```The dot method on an instance is actually just syntax sugar
#

It is useful to know for things like distributed computing, where you could map MyClass.method to a list of instance of MyClass

crystal mica
#

It's always been there on the self tag iirc

#

!self

night quarryBOT
#

Class instance

When calling a method from a class instance (ie. instance.method()), the instance itself will automatically be passed as the first argument implicitly. By convention, we call this self, but it could technically be called any valid variable name.

class Foo:
    def bar(self):
        print('bar')

    def spam(self, eggs):
        print(eggs)

foo = Foo()

If we call foo.bar(), it is equivalent to doing Foo.bar(foo). Our instance foo is passed for us to the bar function, so while we initially gave zero arguments, it is actually called with one.

Similarly if we call foo.spam('ham'), it is equivalent to
doing Foo.spam(foo, 'ham').

Why is this useful?

Methods do not inherently have access to attributes defined in the class. In order for any one method to be able to access other methods or variables defined in the class, it must have access to the instance.

Consider if outside the class, we tried to do this: spam(foo, 'ham'). This would give an error, because we don't have access to the spam method directly, we have to call it by doing foo.spam('ham'). This is also the case inside of the class. If we wanted to call the bar method inside the spam method, we'd have to do self.bar(), just doing bar() would give an error.

crystal mica
#

Yep, and yeah it is actually very useful to know that

potent comet
#

@thin trout It's not actually syntactic sugar, doing obj.method creates a method object which contains a reference to the object and function. Calling that does the method insertion. This uses the descriptor protocol (__get__), the same way property works.

gilded orchid
#
def p(n):
 a,b,c=[2]*n*4,'',[]
 for d in range(n):
  a=[*map(10 .__mul__,a)]
  for i in range(n*4-1):
   d=n*4-i-1
   a[i+1]+=a[i]//(d*2+1)*d
   a[i]%=d*2+1
  q=a[-1]//10
  if q>9:b+=''.join(map(lambda x:str(-~x%10),c));c=[0]
  elif q<9:b+=''.join(map(str,c));c=[q]
  else:c+=[9]
  a[-1]%=10
 return'3.'+b[1:]

a terrible golfed pi function

#

(also it should work for any number of digits as it doesn't use any floats)

proper vault
#

I am pretty sure 2 of the map calls would be shorter as comprehensions

gilded orchid
#
def p(n):
 a,b,c=[2]*n*4,'',[]
 for d in range(n):
  a=[*map(10 .__mul__,a)]
  for i in range(n*4-1):
   d=n*4-i-1
   a[i+1]+=a[i]//(d*2+1)*d
   a[i]%=d*2+1
  q=a[-1]//10
  if q>9:b+=''.join([str(-~x%10)for x in c]);c=[0]
  elif q<9:b+=''.join(map(str,c));c=[q]
  else:c+=[9]
  a[-1]%=10
 return'3.'+b[1:]

only 1 of them was shorter

#
def p(n):
 a,b,c=[2]*n*4,'',[]
 for d in range(n):
  a=[*map(10 .__mul__,a)]
  for i in range(n*4-1):d=n*4-i-1;a[i+1]+=a[i]//(d*2+1)*d;a[i]%=d*2+1
  q=a[-1]//10
  if q>9:b+=''.join([str(-~x%10)for x in c]);c=[0]
  elif q<9:b+=''.join(map(str,c));c=[q]
  else:c+=[9]
  a[-1]%=10
 return'3.'+b[1:]

also I can use semicolons to save indentation

formal sandal
#

Is the length of a fixed?

proper vault
#

[*map(10 .__mul__,a)]
[10*x for x in a]
and [str(-~x%10)for x in c] -> str(-~x%10)for x in c

gilded orchid
#

it's always 4*n length

formal sandal
#

[x*10for x in a]

gilded orchid
#

smart

#

down to 288 bytes

formal sandal
#

c+=[9] => c+=9,

proper vault
#

and I think if you added sth like u=''.join into the initial variables, it would be shorter. Maybe making those initial variables arguments could help as well

formal sandal
#

!e

a = [1, 2, 3]
a+=4,
print(a)
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

[1, 2, 3, 4]
gilded orchid
#

any ideas on how to make this section shorter?

  if q>9:b+=''.join(str(-~x%10)for x in c);c=[0]
  elif q<9:b+=''.join(map(str,c));c=[q]
  else:c+=9,
formal sandal
#

c=[0] => c=0,
c=[q] => c=q,

#

!e

a=0,
a+=1,
print(a)
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

(0, 1)
gilded orchid
#
def p(n):
 a,b,c,j=[2]*n*4,'',[],''.join
 for d in range(n):
  a=[x*10for x in a]
  for i in range(n*4-1):d=n*4-i-1;a[i+1]+=a[i]//(d*2+1)*d;a[i]%=d*2+1
  q=a[-1]//10
  if q>9:b+=j(str(-~x%10)for x in c);c=0,
  elif q<9:b+=j(map(str,c));c=q,
  else:c+=9,
  a[-1]%=10
 return'3.'+b[1:]

done that and assigned ''.join to j

#

anything else I could assign to save bytes?

formal sandal
#

Maybe range?

#
rangerange
rr r=range

nope, doesn't change anything

distant wave
#

You could swap that range for a while

#

it's shorter as long as you never touch the value

gilded orchid
#

I use d and i at various points

#

so I think I do need the range

distant wave
#

You assign to d, but not i

#

oh, I forgot about the initial set, hm

gilded orchid
#

oh wait, I used 2 identical variable names on accient

#
def p(n):
 a,b,c,j=[2]*n*4,'',[],''.join
 for d in[0]*n:
  a=[x*10for x in a]
  for i in range(n*4-1):d=n*4-i-1;a[i+1]+=a[i]//(d*2+1)*d;a[i]%=d*2+1
  q=a[-1]//10
  if q>9:b+=j(str(-~x%10)for x in c);c=0,
  elif q<9:b+=j(map(str,c));c=q,
  else:c+=9,
  a[-1]%=10
 return'3.'+b[1:]

I don't need range for the first one

formal sandal
#

true

gilded orchid
#

actually, I can put the q=a[-1]//10 at the end of the for loop to save a few bytes

#
def p(n):
 a,b,c,j=[2]*n*4,'',[],''.join
 for d in[0]*n:
  a=[x*10for x in a]
  for i in range(n*4-1):d=n*4-i-1;a[i+1]+=a[i]//(d*2+1)*d;a[i]%=d*2+1;q=a[-1]//10
  if q>9:b+=j(str(-~x%10)for x in c);c=0,
  elif q<9:b+=j(map(str,c));c=q,
  else:c+=9,
  a[-1]%=10
 return'3.'+b[1:]
#

it's a bit less efficient but it saves some bytes

vestal solstice
#

there's no way to tell if you have tabs or 2 spaces there

#

it should be tabs though

gilded orchid
#

you can't do that in python 3 due to 'Inconsistent use of tabs and spaces in indentation'

vestal solstice
#

ah

#

unradical

formal sandal
#
def p(n):
 a,b,c,j=[2]*n*4,[''],[],''.join
 exec("""a=[x*10for x in a]
for i in range(n*4-1):d=n*4-i-1;a[i+1]+=a[i]//(d*2+1)*d;a[i]%=d*2+1;q=a[-1]//10
if q>9:b[0]+=j(str(-~x%10)for x in c);c=0,
elif q<9:b[0]+=j(map(str,c));c=q,
else:c+=9,
a[-1]%=10
"""*n)
 return'3.'+b[0][1:]

apparently this is 1 char shorter

#

I don't understand how exec works with scopes.

#

!e

def f():
  b = ''
  exec("b='abc'")
  print(b)
f()
night quarryBOT
#

@formal sandal :warning: Your eval job has completed with return code 0.

[No output]
gilded orchid
formal sandal
#
def p(n):
 a,j,b,*c=[2]*n*4,''.join,[]
 exec("""a=[x*10for x in a]
for i in range(n*4-1):d=n*4-i-1;a[i+1]+=a[i]//(d*2+1)*d;a[i]%=d*2+1;q=a[-1]//10
if q>9:b+=j(str(-~x%10)for x in c),;c=0,
elif q<9:b+=j(map(str,c)),;c=q,
else:c+=9,
a[-1]%=10
"""*n)
 return'3.'+j(b[2:])

reduced to 257 chars

#

a,j,b,*c=[2]*n*4,''.join,[]
this is black sorcery...

#

I did pi in 314 characters. But I'm not smart enough to use an actual pi computation algorithm.

#

Also, 314 ~= 100pi

#

Actually, i can remove the z variable and only use 309 chars

vestal solstice
#

index works on a list, do you need the join?

formal sandal
#

What do you mean?

vestal solstice
#

a = [*map(chr...)]

formal sandal
#

true

#

The solution is way more than 1000 bytes, but still 303 characters

vestal solstice
#

yeah, that's the quirk of the site

formal sandal
#

Basically i express pi in a different base.

vestal solstice
#

do you need n? You can convert backwards, like x*=49900;x+=a.index(i)

#

have to reverse everything though

hot crypt
#

it never occured to me that you could map ' '.join to a variable

gilded orchid
#

it's the same as any other function

marsh void
#

primo-ppcg is so damn golfing :D

grizzled cloak
#

hmm

#

3 .__pow__(.5) returns NotImplemented

#

but 3 ** .5 works

#

why does int.__pow__ not fall back if other is not a int

#

ah

#

hm

#

i would assume it falls back to __rpow__

#

seems to be the same with almost everything

#

3 .__mul__(2.) also throws a error

snow beacon
#

The operators must be what do the fallback logic.

grizzled cloak
#

weird

proper vault
#

If it was the methods doing it, it would make implementating them a pain

grizzled cloak
#

fair enough

bitter iris
#

3 .__mul__(2.) also throws a error
@grizzled cloak

I couldn't reproduce the error, can you share what it throws?

grizzled cloak
#

it doesnt throw a error

#

it just returns NotImplemented

bitter iris
#

oh, okey.

grizzled cloak
#

sorry about that confusion

#
3 .__mul__(2.)
Out[20]: NotImplemented```
brisk zenith
#

when a dunder method returns NotImplemented it's supposed to automatically raise NotImplementedError (at least, when they're implicitly called with operators for example)

#

that's what i've seen with user-defined classes, at least

bitter iris
#

NotImplemented allows python to fallback into other methods

#

If lhs __x__ returns NotImplemented it fallbacks to rhs__rx__etc etc

nocturne saddle
#

Yes, it's important to not the difference between NotImplementedError and NotImplemented and the role they play in te data model.

thin trout
#

!e

print({True: 'true', 1: 'or', 1.0: 'not?'}) ```
night quarryBOT
#

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

{True: 'not?'}
grizzled cloak
#

they all have the same hash huh?

#

yup

proper vault
#

well, hash would not do it

#

however True == 1 == 1.0

thin trout
#

Hash and equal

proper vault
#
In [21]: class U:
    ...:     __hash__ = lambda *_: 2
    ...:
In [25]: U() == U()
Out[25]: False

In [26]: hash(U())
Out[26]: 2

In [27]: {U(): 1, U(): 2, U(): 3}
Out[27]:
{<__main__.U at 0x225b5386e20>: 1,
 <__main__.U at 0x225b579a640>: 2,
 <__main__.U at 0x225b579a880>: 3}
thin trout
#

!e

print(hash(True) == hash(1) == hash(1.0))
print(True == 1 == 1.0)```
night quarryBOT
#

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

001 | True
002 | True
thin trout
#

And make them equal now

proper vault
#
In [31]: class V:
    ...:     __eq__ = lambda *_: True
    ...:     __hash__ = lambda self: id(self)//4
    ...:

In [32]: {V(): 4, V(): 3}
Out[32]: {<__main__.V at 0x225b53abe50>: 4, <__main__.V at 0x225b53ab5b0>: 3}

In [33]: class W:
    ...:     __eq__ = lambda *_: True
    ...:     __hash__ = lambda self: 4
    ...:
    ...:

In [34]: {W(): 5, W(): 6}
Out[34]: {<__main__.W at 0x225b57a8310>: 6}
#

ye, both need to be true

formal sandal
#

That makes sense.

#

Because of hash collisions.

#

If two elements accidentally have the same hash in a huge dict, it's a nasty heisenbug

snow beacon
#

Hash collisions are planned for. The bad part is when two equal elements have different hashes.

formal sandal
#

Well, technically this requirement isn't enforced.

#

You can't check it.

potent comet
#

It can't be enforced, but dicts/any code using the hashes will do the wrong thing and seem to break.

fiery hare
#

I don't know if this is esoteric per se, but I made a change to a file in cpython's _collectionsmodule.c , recompiled it without errors, and added the name of the class that I created to collections.py

#

however that class still can't be imported and I'm wondering to what extent I fundamentally misunderstand how this all works.

bitter iris
#

Well if you share a diff of your changes, we might help @fiery hare

fiery hare
#

@bitter iris thanks, I'll push it to github right now.

#

This is the expected behavior:

#
from collections import defaultdict

class dynamicdict(defaultdict):

    def __missing__(self, key):
        return self.default_factory(key)```
#

this code works, but the fact that it's not implemented in C drastically adds to the runtime of importing collections.

#

My C implementation is largely a copy of the implementation for defaultdict, but the default_factory is supposed to use the key as an argument.

#

I wanted to implement it in a way that's would mirror how subclassing defaultdict might look in OOP to reduce the amount of redundant code, but I'm not adept at C.

acoustic zinc
#

can't you just write a default factory function

#
def defaultfactory(func, key):
    def new_func(*args, **kwargs):
        if not args and not kwargs:
            return func(key)
        else:
            return func(*args, **kwargs)
    return new_func
acoustic zinc
#
def decomaker(key):
    def defaultfactory(func):
        def new_func(*args, **kwargs):
            if not args and not kwargs:
                return func(key)
            else:
                return func(*args, **kwargs)
        return new_func
    return defaultfactory
#

alternatively you can use a decorator

fiery hare
#

@acoustic zinc the defaultdict class doesn't pass the missing key to the default_factory callable.

acoustic zinc
#

you can do something like this though

fiery hare
#

but overriding the __missing__ method changes this with few lines of Python code. However if it were to be integrated into the standard library, I imagine they'd want it to be implemented in C to speed up the runtime.

acoustic zinc
#

but your code doesn't work