#esoteric-python
1 messages · Page 84 of 1
so this would convert the float literal 12. into 12 ., to allow things like 12._add__
Yea
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
@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
Interesting
Only one object version : https://paste.pythondiscord.com/iqayigiwug.py
can you get the full email spec to work
Have you seen the 'official' email regexp? :)
email isnt even regular, as comments can afaik be nested
Very cool - I've never come across the @ operator before (didn't even know it was one) - what is it's purpose/use-case?
It is the matrix multiplicator operator
It isn't used in any stdlib object, but its purpose is to multiply matrix
Nice, never knew that before!
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)@_
Yes I know my code is really bad
@formal sandal can you turn your catcher into a lambda tho?
without imports 😛
I don't think so...
Well...
I can use sys.excepthook
How can you do it without imports in 3.7?
__import__? :P
Unless sys has already been imported somewhere?
!e
print(isinstance(Warning, Exception))
print(Warning.__bases__)
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 | False
002 | (<class 'Exception'>,)
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
Is sys used in site? If so, it'll be in the module list already.
It's for injecting stuff at interpreter startup so I'd be surprised if it didn't use the module for communicating with it
@formal sandal you can get a ContextDecorator from object.__subclasses__() on some platforms of python3.6-3.7
(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
!e (lambda: "esoteric python")()
@bitter carbon :warning: Your eval job has completed with return code 0.
[No output]
@bitter carbon :white_check_mark: Your eval job has completed with return code 0.
esoteric python
cool
!e exec('{'*3000 + '}'*3000)
@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
square root function
without using square root
allowed to use any method
halley, newton, euler e.g
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
a=lambda b,i=1:[i:=(i-(i*i-b)/2/i)for _ in range(100)][-1]
oneliner
gonna add error
sqrt = lambda i:int(i**.5) @proper vault @sick hound
thats not allowed
shut
lol forgot to mention it
!e exec(int(["20"][0])+int(["80"][0]))
@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
!e int(["20"][0])+int(["80"][0])
@bitter carbon :warning: Your eval job has completed with return code 0.
[No output]
!e print(int(["20"][0])+int(["80"][0]))
@bitter carbon :white_check_mark: Your eval job has completed with return code 0.
100
lol
anyone here good at code golf?
many people are
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
"""
))
god damn it
funcdef: 'def' NAME parameters ['->' test] 'FUCK' suite 'FUCK'
``` I only changed funcdef on the original grammar and 🎉
👍
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
!e
import sys
sys.excepthook = lambda *_: print("do bracket thingy")
from __future__ import brackets
@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
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")
@formal sandal :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | SyntaxError: not a chance
future imports are handled at compile time rather then run time
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
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)
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
~~!e
import dis
dis.dis('''
from future import braces
a = 1
print(a + 1)''')```~~
@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
Interesting, the rest of the code is still parsed, even if braces is imported
!e ```python
import dis
dis.dis('''
from future import braces
a = 1
print(a + 1)''')
@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
Nevermind, discord markdown fooled me
You can get it to do stuff through site before the main code is parsed and compiled
!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]
])
@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
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(____),*____]))),___))
what are the characters in the second one?
Cyrillic letters.
йцукенгшщзхъфывапролджэячсмитьбю
ай хев эн айдиа, мейби ви куд мейк зис ченел ивен мор изотерик иф инстед ов юзинг плейн инглиш ви юзд сырилик транскрипшен оф инглиш ин аур дискашенс.
ординари пипл вил онли бе эйбл ту андерстенд ус юзинг google translate.
текникли ит вонт вайолейт зе серверс рулз абаут онли инглиш биинг аллауд, синс ви вуд ток ин инглиш, джаст риттен ин э дифферент формат.
Пайтон экчули супортс сырилик керектерс эз вериэбл неймс. Вай вуд ит ду зет?
!e
вериэбл = 123
@formal sandal :warning: Your eval job has completed with return code 0.
[No output]
@formal sandal because it is defined like that. no idea why you wrote it in russian-transcript
@thin trout :warning: Your eval job has completed with return code 0.
[No output]
@formal sandal :warning: Your eval job has completed with return code 0.
[No output]
Intersting
!e print(𝓔)
@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
!e py e = 4 print(𝓔)
@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
!e py E = 4 print(𝓔)
@sick hound :white_check_mark: Your eval job has completed with return code 0.
4
!e py 𝓔 = 4 print(E)
@sick hound :white_check_mark: Your eval job has completed with return code 0.
4
!e py print('𝓔')
@sick hound :white_check_mark: Your eval job has completed with return code 0.
𝓔
!e ```py
class Test:
def getattr(self, x):
print(x)
Test().𝓔```
@sick hound :white_check_mark: Your eval job has completed with return code 0.
E
huh
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
1
!charinfo 𝓔
\U0001d4d4: MATHEMATICAL BOLD SCRIPT CAPITAL E - 𝓔
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
!e
𝓔 = 1
E=2
print(𝓔)
@hot crypt :white_check_mark: Your eval job has completed with return code 0.
2

[(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
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)
...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```
@sick hound your earlier solution isn't equivalent to my code :/
baar baar
ie, it has to print(yes) after exiting the loop
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])```
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
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
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
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)
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | [2, 3, 4]
!e
import ast
print(ast.Module._fields)
del ast.Module._fields
print(hasattr(ast.Module, "_fields"), ast.Module._fields, "???")
del ast.Module._fields
@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
!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)
@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
This is kinda like reduce...
You can load some initial state into Step(1) and then mutate in
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
!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?
To index within the directory of the list object. Presumably pop is the 43rd in alphabetical order.
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?
!e ```python
print(dir([1,2,3,4])[40:50])
@snow beacon :white_check_mark: Your eval job has completed with return code 0.
['index', 'insert', 'pop', 'remove', 'reverse', 'sort']
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]
oh okay
so if that was to be
!e
(lambda x:x.__getattribute__(dir(x)[42])([1,2,3,4])(0)
@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 :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
hm, how?
Wait I think it's
!e
(lambda x, i: x.__getattribute__(dir(x)[42])(i))([1,2,3,4],0)
@cursive plover :warning: Your eval job has completed with return code 0.
[No output]
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)
@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 :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']
oh, I see
dir already returns a list, FYI.
@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
Does it only work on classes?
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'}))
@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']
oh, dictionaries don't have a __dict__ either? :/ what does then
all I can find in the docs is this
Lists and dictionaries don't have writable attributes.
what do have them then?
oh, uh a user defined class
right?
and by writable attribute you mean like, a user defined attribute?
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"
@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'
!e ```python
1..as_integer_ratio = (0, 0)
@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
User defined classes, mostly.
Code objects, and I believe functions also.
Quitters are also writable.
I didn't find much on what a quitter is on google, do you mean like sys.exit()?
You can also prevent monkey patching / defining new attributes via __slots__ as well, for user defined classes
code objects are immutable, fwiw
Oh, I must be thinking of the way you can overwrite a function's code object with a different one.
(cross-post from #help-coconut since it might be interesting as a challenge)
Trying to render text with VTE100 escape codes to a string; e.g. I get https://pastebin.com/v5Zbakh0 (split by newlines)
Is there a library or an easy way to render all of these to a multiline string?
Is this like what colorama does?
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
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)
Is there a bash command you could incorporate using os.system()?
!e
import os
os.system("")
@formal sandal :warning: Your eval job has completed with return code 0.
[No output]
!e ```python
import os
os.system('echo "bash!"')
@snow beacon :warning: Your eval job has completed with return code 0.
[No output]
!e ```python
import os
x = os.popen('echo "bash?"').read()
print(f"returned {x}")
@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
There's a way, I expect.
hello
>>> 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)```
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)
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
<class '__main__.C'>
!e py import os os.exec('/bin/bash', ['bash', '-c', 'echo "bash?"'])
@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'
!e py import os os.execv('/bin/bash', ['bash', '-c', 'echo "bash?"'])
@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 :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 :warning: Your eval job has completed with return code 0.
[No output]
!e py import os print(os.listdir('/'))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
['usr', 'snekbox', 'lib64', 'lib', 'etc']
!e py import sys print(sys.executable)
@sick hound :white_check_mark: Your eval job has completed with return code 0.
/usr/local/bin/python
!e py import os print(os.listdir('/usr/local/bin'))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
['python3.8', 'python3', 'python']
haha
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
!e
import os
print(os.system("cat /proc/sys/kernel/pid_max "))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
-1
>>> 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
that's genius
that doesn't work for me :/
The offset is most probably version dependent
ah
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
You're asking me as if I knew that much about ctypes :P remembered that, it worked, was happy
what = love = object()
where's the object() coming from?
It is Py_Object right?
object here is just to get a generic object so that what is love is true
anything could be there in place of the object()
Why tiny?
dunno, might make a new immutable thing if it isn't some stored constant, maybe not, i don't understand implementation details
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
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
but that's not a=b=val
ye, a = b = x will always have all of them the same reference
when used like that it creates one val and then passes it to those names
(well, unless one of the assignments does more than just assign, e.g. c_longlong.value)
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?
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
is that an enum or something?
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
so my initial statement is still true 😛
descriptor fun
@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
@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?
@cursive plover the c_void_p line replaces the class of True from bool to NoMore
>>> 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"
what and love are both the same object() instance
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
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
Can't tell you why the actual reason for the offset but it doesn't work without it so that's enough for me
so id(True) gets the address of the beginning of the True object, +8 is the index of the True object's class
@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?
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
>>> 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
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.
oh yeah
because one of the challenge restrictions was "don't use imports"
and so joe didn't. :D
clever
you had esoteric challenges?! that sounds neat
i wish we had #define in python
what for?
@acoustic zinc yes, there are challenges. you can still view them here: https://github.com/python-discord/esoteric-python-challenges
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
might try it at some point, sounds really cool
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е)
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
False
>>> 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
>>> ```
huh
Can you also add support for evaluating lambda calculus?
That would be convenient
yea as long as the first character throws an exception
Maybe : (expression)
!e ```py
: ()
@rugged sparrow :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | : ()
003 | ^
004 | SyntaxError: invalid syntax
True
$?` should be good tokens
can be pretty much anywhere
and you'll get a nice syntax error
i need a way to continue after that line tho
Just insert a space, it will complain about indentation.
Would need to put in your own exception handlind system that would let you continue I think
with .pth?
you can have it in sitecustomize.py/usercustomize.py in the site packages dir for a simpler solution, think pth only allows imports
you can do import (module);'any onelined code'
well still more convenient there 😄
true true
What if someone made a site encoding that runs a file as if in the interpreter?
the reason it works in the interpreter is because of how the interpreter handles exceptions differently
and lets you define the excepthook before a syntax error is triggered during compilation
^ that too
An interpreter encoding would let you do things like <> not equals in a script.
No, it's interpreter only.
!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'))```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
<module 'os' from '/usr/local/lib/python3.8/os.py'>
@brisk zenith does that count as not using imports?
actually i guess help probably uses import internally
well, the interpreter itself uses import internally
so let's just get rid of that too
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?
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)
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]
a not defined
But you're using some really smart stuff I hadn't thought of lmao
@formal sandal
!e
print([y:=x+5 for x in range(100) if y%2 == 1])
@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
!e
print([y for x in range(100) if (y:=(x+5))%2 == 1])
@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]
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]
You're welcome @last locust
Yay! Now my needlessly complex typecheking library supports de Morgan's optimizations.
not ((not a) or (not b)) = a and b
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
no
It looks very cool
I am very impressed actually
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
Maybe it's overkill, but you could use lark-parser
lark-parser is a parsing framework that uses EBNF notation
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
And then you can transform any text source using a convenient transformer
i dunno what that is
oh, i see, i might update my own regex language and try to use it to specify boolean grammar
one day
Your own regex language?
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
You can recursively parse a subset of XML with regexp...
https://regex101.com/r/FyrACj/1
But, unfortunately, not in python-flavoured regex.
Regex101 allows you to create, debug, test and have your expressions explained for PHP, PCRE, Python, Golang and JavaScript. The website also features a community where you can share useful expressions.
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
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
@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.
Output:
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
i accept any variable name currently
i think i like it better from scratch though
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
Or you could substitute \
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 │
└────┴────┴────┴────┴──────────────────────────────────────────────────────────────┘
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
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 │
Maybe karma exists...
See this?
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
[ A A + B]
[ B B ]
this is close to the fibonacci matrix
Well, it will show a fibonacci pattern.
Actually, most of these equations will
Well, not most. Many
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
lark is thicc
In fact,
aaa math
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
wow, last messages are mind blowing
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.
Check out my latest opus
https://pastebin.com/arPVcXqb
Scroll to line 52 to see the business logic.
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.
someone here should make a coronavirus class, that requires you to washHands() every so often otherwise bad ctypes stuff starts happening
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)
Maybe an infected class should randomly infect other classes it interacts with.
I guess you could mess with stack frames.
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
it is not easy enough
very informative indeed
the best i can do is randomly infect attributes if they have a __getattr__ method
i'm not the best esoteric pythonista
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.
Okay I am working on a funny thing
basically takes all your code and rotates it π/2 counter-clockwise
i appreciate the radians
same 💪
radians is objectively worse than degrees
false
0-1 best angle system
radians are by far the most intuitive
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
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?
my argument for radians is always "yes but can you do calculus with it"
Radians are only useful if you want to do some calculus, like trigonometry
ye, for higher math radians all the way.
If not, that's just painful
use some calculus, like trigonometry
lmao
what
:D
if you walk 1/8 of a unit circle, you walked tau * 1/8 units of distance
i like degrees
people that like degrees were taught wrong, and i sympathize
gradians :^)
whenever i have to respond in radians on a test (high schooler) i just do it in degrees then convert
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
our teacher made us memorize values for sin/cos/tan for pi/2, pi/3, pi/4, pi/6 * n
Ew...
sin'(degrees) = pi / 180 * cos(degrees)
most teachers did that I would hope
eh
i don't like memorization\
so it makes no difference
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
sin^2(pi/4) = 1/2
sin^2(pi/6) = 1/4
That's it.
Then just imagine a unit circle in your head.
1/sqrt(2) i think
they said sin²(...)
indeedy
makes it faster to get cos from it
true enough.
well, it's the same for pi/4
honestly, if I am actually doing trig, I just draw a unit circle, makes it faster for me
My new encryption algorithm. Can you guess how it works?
https://pastebin.com/8MRE6aKA
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]: '[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]][[[[[[[[[[[[]]]]]]]]]]]][[]][[[]]][[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]][[[[[[]]]]]][[]][[[[[]]]]][[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]][[[[]]]][[]][[[[[]]]]][[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]][[[[[[[[[[[[]]]]]]]]]]]][[]][[[]]][[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]][[[[]]]][[]][[[]]][[[[[[[[]]]]]]]][[[[[[[[[[[[[]]]]]]]]]]]]][[]][[]]'
¯_(ツ)_/¯
)_/¯ツ¯\_(
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]
Other examples
https://pastebin.com/q5dnsdwv
It seems like if the number of brackets is useful number, it has a x4 overhead
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.
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
A little hint
bruh
well, the grouping size seems to be between 1-27
I meant 'the number of output numbers'
Another batch:
https://pastebin.com/UKRSvSkq
I'll give you a hint that this encryption algorithm has something to do with natural language processing
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
Don't know what that is.
1
11
21
1211
111221
312211
this sequence
Yes, I've looked it up
famous in recreational mathematics, probably because conway
You probably shouldn't waste time on this encryption... It sounded better in my head, like most of my ideas here
are all the small numbers junk
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?
yep
and the start of the group is usually the biggest number
You can try and convert all the messages in a batch
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)
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
{'a': 1, 'b': 2, 'c': 3}
heh
!e
import sys
print(sys.version)
@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]
Can someone tell me how this server executes the code?
more suited to #dev-contrib or maybe #community-meta but it's through https://github.com/python-discord/snekbox
Thanks I saw the command here so thought I’d ask in the same place, still exploring all the channels, there’s so many
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
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?
We don't allow advertising so unless the server is whitelisted you will not be able to post the link
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.
I can't say I've heard of it. Is it a big server?
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
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.")
I doubt that will work with input()
it does
!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()}")
@proper vault :white_check_mark: Your eval job has completed with return code 0.
you sent Hello World, Peter age 24
Dude! Where’s my car?! That’s amazing I did not know we could do that
I take it it reads by lines
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
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
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
!e
import sys
from io import StringIO
newin = StringIO("Hello World\nPeter\n666\n")
sys.stdin = newin
while a:=input():
print(f"{input()}")
@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
Oops my bad
ye, input() is not meant for non-stdin stuff
!e
import sys
from io import StringIO
newin = StringIO("Hello World\nPeter\n666\n")
sys.stdin = newin
while a:=input():
print(f"{a}")
@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
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")
@hushed chasm :white_check_mark: Your eval job has completed with return code 0.
001 | Hello World
002 | Pyro
003 | 666
004 | nothing left
Booyah
@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)
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
{'hello': 'world', 'my_func': <function MyClass.my_func at 0x7f4bfc148ca0>}
This (hacky, admittedly) way, you can register your states without creating a separate method for creating them and packing them in a dict.
@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).
oof
!unmute 186436642356068352
:incoming_envelope: :ok_hand: pardoned infraction mute for @hushed chasm.
thanks
🔥
!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.")
@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'
!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.")
@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
You can reduce the number of newlines by inlining some ifs
@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
Uhm
If you just want to run the code, you can do that in #bot-commands
You sure you need a calculator in esoteric python
I mean, with eval you can make calculator in what, 7 lines
print(eval(input()))
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

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")))
Was not a matter of working or not
@bitter iris ohh, you should've written a parser instead!
oh
@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
haha
!e py import ctypes t = 0, ctypes.c_longlong.from_address(id(t) + 24).value = id(t) print(t)
@marsh void :white_check_mark: Your eval job has completed with return code 0.
((...),)
@vague gust hey have you seen this one though
huh
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)
@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
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.
https://github.com/python/cpython/blob/master/Objects/tupleobject.c#L156 @brisk zenith this is probably what the issue is
what happens if you do @property and @staticmethod on something?
!e
class a:
@property
@staticmethod
def b():
return 1
print(a.b)
@acoustic zinc :white_check_mark: Your eval job has completed with return code 0.
<property object at 0x7f1c44cfc360>
@acoustic zinc :white_check_mark: Your eval job has completed with return code 0.
<property object at 0x7fbaf832b360>
@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

I heard someone complaining about esoteric-python being pretty much esoteric-cpython
I swear it was ya :D
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.
haha yep
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.
anyone know how the @ staticmethod and @property decorators work when you use both?
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
fair enough
I'd guess they need an instance
would check the docs for descriptors if you want to look at it more
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```
yup, that's why i said it depends on the order
if you do property(staticmethod(method)) then it might be functional
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'))```
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

indeed
Is there a problem in programming that cannot be solved by creating a new domain-specific language?
I don't see what's wrong with a metapermission system...
And the parser is happy with it
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.
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)
"""
)
)
looks like highlighter can't highlight multiline decorators properly
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
It's because it's an older version of highlight.
huh that's cool
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
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.
Yep, and yeah it is actually very useful to know that
@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.
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)
I am pretty sure 2 of the map calls would be shorter as comprehensions
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
Is the length of a fixed?
[*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
it's always 4*n length
[x*10for x in a]
c+=[9] => c+=9,
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
!e
a = [1, 2, 3]
a+=4,
print(a)
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
[1, 2, 3, 4]
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 :white_check_mark: Your eval job has completed with return code 0.
(0, 1)
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?
You could swap that range for a while
it's shorter as long as you never touch the value
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
true
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
there's no way to tell if you have tabs or 2 spaces there
it should be tabs though
you can't do that in python 3 due to 'Inconsistent use of tabs and spaces in indentation'
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()
@formal sandal :warning: Your eval job has completed with return code 0.
[No output]
how on earth have people done https://code-golf.io/π#python in 58 bytes?
Code Golf is a game designed to let you show off your code-fu by solving problems in the least number of characters.
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
index works on a list, do you need the join?
What do you mean?
a = [*map(chr...)]
yeah, that's the quirk of the site
Basically i express pi in a different base.
do you need n? You can convert backwards, like x*=49900;x+=a.index(i)
have to reverse everything though
it never occured to me that you could map ' '.join to a variable
it's the same as any other function
primo-ppcg is so damn golfing :D
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
The operators must be what do the fallback logic.
weird
If it was the methods doing it, it would make implementating them a pain
fair enough
3 .__mul__(2.)also throws a error
@grizzled cloak
I couldn't reproduce the error, can you share what it throws?
oh, okey.
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
NotImplemented allows python to fallback into other methods
If lhs __x__ returns NotImplemented it fallbacks to rhs__rx__etc etc
Yes, it's important to not the difference between NotImplementedError and NotImplemented and the role they play in te data model.
!e
print({True: 'true', 1: 'or', 1.0: 'not?'}) ```
@thin trout :white_check_mark: Your eval job has completed with return code 0.
{True: 'not?'}
Hash and equal
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}
!e
print(hash(True) == hash(1) == hash(1.0))
print(True == 1 == 1.0)```
@thin trout :white_check_mark: Your eval job has completed with return code 0.
001 | True
002 | True
And make them equal now
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
That makes sense.
Because of hash collisions.
If two elements accidentally have the same hash in a huge dict, it's a nasty heisenbug
Hash collisions are planned for. The bad part is when two equal elements have different hashes.
https://docs.python.org/3/reference/datamodel.html#object.__hash__
The only required property is that objects which compare equal have the same hash value
Well, technically this requirement isn't enforced.
You can't check it.
It can't be enforced, but dicts/any code using the hashes will do the wrong thing and seem to break.
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.
Well if you share a diff of your changes, we might help @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.
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
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
@acoustic zinc the defaultdict class doesn't pass the missing key to the default_factory callable.
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.
but your code doesn't work