#esoteric-python
1 messages ยท Page 140 of 1
I've done it before
i have a game idea
XD
https://ganer.xyz/s/0b7697da1f7ce6de?e ok this is kinda fun
i kinda want to do something esoteric tho
I think last time I ran the script I got a 14 pounds cat
!e ```py
def ():
(:=[,import('collections').defaultdict(int),0,0,0,import('sys').stdin.read,{}])[-1]|={'+':lambda:([2],*[0for [1][[2]]in[([1][[2]]+1)%256]]),'-':lambda:([2],[0for [1][[2]]in[([1][[2]]-1)%256]]),'<':lambda:([2]-1,0),'>':lambda:([2]+1,0),'.':lambda:(_[2],[0for{}[()]in[print(end=chr([1][[2]]))]]),',':lambda:([2],*[0for [1][[2]]in[ord(5)]]),'[':lambda:([2],not [1][[2]]),']':lambda:([2],-bool([1][[2]]))}
while [4]in range(len([0])):
([0for [3]in[[3]+([0][[4]]=='[')-([0][[4]]==']')]]if [3]else 0)
[[0for [i]in[.setitem(i_,[-1].get([0][[4]],lambda:([2],0))())]]for i_ in range(2,5)if not [3]]
[0for [4]in[[4]+1-2*([3]<0)]]
return int(not [4]==len([0]))
_("++++++++++[>+++>++++>++++++++>+++++++++>++++++++++>+++++++++++>++++++++++++<<<<<<<-]>>>++++.>>++++.+.>+++++.<<<<<++.>>>>>+.<----.>-.+.<<<<<.>>>>+++.<+++++++.>>-.<<<<<.>>>++.>>----.<+++++.>+.<-.-------.>++++.<.-.<<<<.>>>>>-.++.<<..>+.>--..<+.>++.<++++++..>>+.<<<<<++++++.")
@sly root :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 8, in <module>
003 | File "<string>", line 6, in _
004 | TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
also so literally there is zero reason why you can't use walrus in the itterator part of a comprehension
which is reallllllllllly annoying
hm yes
[_ for _ in (a:=[1, 2, 3])]
``` nope
```py
(lambda a:[_ for _ in a])((a:=[1,2,3]))
``` yes (edit: i made it betterer)
i am going to write code that writes more code that rhymes
@floral meteor what's wrong here?
([
0 for _[3] in [
_[3] + (_[0][_[4]]=='[') - (_[0][_[4]]==']')
]]
if _[3]
else 0)
remember one level up the else only evaluates if the if condtion returns false
i dont know if that's relevant to your issue though
alternative for if:... else:...
([...]if a else 0);([...]if not a else 0)
if a:
this()
else:
that()
to
[that,this][bool(a)]()
for more than two way comparison, use a dictionary instead
!e ```py
def ():
(:=[,import('collections').defaultdict(int),0,0,0,import('sys').stdin.read,{}])[-1]|={'+':lambda:([2],*[0for [1][[2]]in[([1][[2]]+1)%256]]),'-':lambda:([2],[0for [1][[2]]in[([1][[2]]-1)%256]]),'<':lambda:([2]-1,0),'>':lambda:([2]+1,0),'.':lambda:(_[2],[0for{}[()]in[print(end=chr([1][[2]]))]]),',':lambda:([2],*[0for [1][[2]]in[ord(5)]]),'[':lambda:([2],not [1][[2]]),']':lambda:([2],-bool([1][[2]]))}
while [4]in range(len([0])):[([0for [3]in[[3]+([0][[4]]=='[')-([0][[4]]==']')]]),[[0for [i]in[.setitem(i,[-1].get([0][[4]],lambda:([2],0))())]]for i_ in range(2,5)]][bool([3])];[0for [4]in[[4]+1-2*([3]<0)]]
return int(not [4]==len([0]))
_("++++++++++[>+++>++++>++++++++>+++++++++>++++++++++>+++++++++++>++++++++++++<<<<<<<-]>>>++++.>>++++.+.>+++++.<<<<<++.>>>>>+.<----.>-.+.<<<<<.>>>>+++.<+++++++.>>-.<<<<<.>>>++.>>----.<+++++.>+.<-.-------.>++++.<.-.<<<<.>>>>>-.++.<<..>+.>--..<+.>++.<++++++..>>+.<<<<<++++++.")
@sly root :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 5, in <module>
003 | File "<string>", line 3, in _
004 | TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
if a:
this()
elif b:
that()
else:
nope()
to
{bool(b):that,bool(a):this}.get(1,nope)()
three way comparison
what's the point of for i_ in range(2,5)?
_[2:4]
which has a length of two, not three
slices work the same as ranges
i, t = (...)(i)
in the version with "normal" variables
how does this work
1 and True are basically the same thing
!e ```py
print(1==True)
print({True:'Hello'}[1])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | True
002 | Hello
i meant meant more "how can i run it"
ah thanku
i has funny idea
one person writes code
the other person estorifies it
then the first person esoteries it more
and so on
print("hi")
print(f"{''.join([chr(n+103) for n in range(1,3)])}")
we picked up some more followers ๐ฅณ
what does := even do ? 
i kept googling everywhere,
my brain is stupid to understand the walrus
inline variable set
assign and return
!e q = (a := 5) + 2
print(q)
print(a)
@west cipher :warning: Your eval job has completed with return code 0.
[No output]
@west cipher :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | `py
003 | ^
004 | SyntaxError: invalid syntax
ffs
!e ```py
for (a := 5) in range(5):
print(a)
@umbral prism :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | for (a := 5) in range(5):
003 | ^^^^^^
004 | SyntaxError: cannot assign to named expression
e
!e
q = (a := 5) + 2
print(q)
print(a)
@west cipher :white_check_mark: Your eval job has completed with return code 0.
001 | 7
002 | 5
finally
thanks
i haven't slept in too long
"inline variable set" was enough lol
!e py for i in range((a:=5)):print(i,a)
@sly root :white_check_mark: Your eval job has completed with return code 0.
001 | 0 5
002 | 1 5
003 | 2 5
004 | 3 5
005 | 4 5
๐
fcaas - fat cats as a service
i cant find any cat adoption sites that state the weight of the cat
i want to squish that fat cat ):
!e
from base64 import b64encode
from hashlib import sha256
from sys import exit
while 'q' in globals() or (q := []) or 1:
q += [w := memoryview(bytes()), q := sha256((w:=str(b64encode(bytes([((a:=int(str(w)[-8:-1],16)%2**16)//(2**8)),(a+4)%2**8][::-1]))).lower()[2:4]).encode('utf-8')).hexdigest()=="8f434346648f6b96df89dda901c5176b10a6d83961dd3c1ac88b59b2dc327aa4" and (print(w) or exit(0))]
what
@west cipher :white_check_mark: Your eval job has completed with return code 0.
hi
now i somewhy need to golf it
ok
!e ```py
while'q'in globals()or(q:=[])or 1:q=import("hashlib").sha256((w:=str(import("base64").b64encode(bytes([((a:=int(str(memoryview(bytes()))[-8:-1],16)%216)//(28)),(a+4)%2**8][::-1]))).lower()[2:4]).encode('utf-8')).hexdigest()=="8f434346648f6b96df89dda901c5176b10a6d83961dd3c1ac88b59b2dc327aa4"and(print(w)or import("sys").exit(0))
@sly root :warning: Your eval job timed out or ran out of memory.
[No output]
lol
xd
bruh
i'm just going to not edit anything you written since i dont want my computer to like
explode
or something
!e py def _(_): (_:=[_,__import__('collections').defaultdict(int),0,0,0,__import__('sys').stdin.read,{}])[-1]|={'+':lambda:(_[2],*[0for _[1][_[2]]in[(_[1][_[2]]+1)%256]]),'-':lambda:(_[2],*[0for _[1][_[2]]in[(_[1][_[2]]-1)%256]]),'<':lambda:(_[2]-1,0),'>':lambda:(_[2]+1,0),'.':lambda:(_[2],*[0for{}[()]in[print(end=chr(_[1][_[2]]))]]),',':lambda:(_[2],*[0for _[1][_[2]]in[ord(_[5](1))]]),'[':lambda:(_[2],not _[1][_[2]]),']':lambda:(_[2],-bool(_[1][_[2]]))} while _[4]in range(len(_[0])):[([0for _[3]in[_[3]+(_[0][_[4]]=='[')-(_[0][_[4]]==']')]]),[[0for _[i_]in[_.__setitem__(i_,_[-1].get(_[0][_[4]],lambda:(_[2],0))())]]for i_ in range(2,4)]][bool(_[3])];[0for _[4]in[_[4]+1-2*(0>_[3]if _[3]is not None else 1)]] return int(not _[4]==len(_[0])) _("++++++++++[>+++>++++>++++++++>+++++++++>++++++++++>+++++++++++>++++++++++++<<<<<<<-]>>>++++.>>++++.+.>+++++.<<<<<++.>>>>>+.<----.>-.+.<<<<<.>>>>+++.<+++++++.>>-.<<<<<.>>>++.>>----.<+++++.>+.<-.-------.>++++.<.-.<<<<.>>>>>-.++.<<..>+.>--..<+.>++.<++++++..>>+.<<<<<++++++.")
@sly root :warning: Your eval job has completed with return code 0.
[No output]
still not works
you win
i just cant
wait i just realised what its doign
thats literally insane
jesus christ
omg thats literally insane
my thing?
yes
i just kept hashing memory addresses until I got a hi lol
honestly i dont really see any way i could make this worse unless i completely rewrote it
make a neural network that detects letters, hash something builtin and that when passed into some function that draws stuff makes the neural network guess "hi"
perhaps
im going to stick with the way you esesntially brute forced it to write h
count_a,count_b,power_a,power_b = 200,200,200,200
for a1 in range(count_a):
for a2 in range(count_b):
for b1 in range(power_a):
for b2 in range(power_b):
try:
c = chr(((a1**b1)*(a2**b2)))
except:
pass
if c == "h":
print(f"success\n{a1}^{b1}|{a2}^{b2}")
i think i am getting somewhere
you see its esoteric if its un feasible anything will ever be able to run it
!e
from itertools import product
q = 200
for a1, a2, b1, b2 in product(range(q), repeat=4):
print(a1)
@west cipher :x: Your eval job has completed with return code 143 (SIGTERM).
001 | 0
002 | 0
003 | 0
004 | 0
005 | 0
006 | 0
007 | 0
008 | 0
009 | 0
010 | 0
011 | 0
... (truncated - too many lines)
Full output: too long to upload
xd
all i need to do is convert this to a list comp, create 2 combinations of characters instead, and then replace every number with stupid bullshit
so
code golf contest is live https://emkc.org/contests/67/making-squares
how did you get your 72 byte solution ๐คจ
im stuck at 81
answers are revealed when the contest ends
though late solutions are accepted for no points as well
I'm bracing myself for when someone submits a 50 byte solution and I die inside
probably lyndon
hehe
can someone in this channel test python >asm translation?
echo "print('Hello World!')" > hello.pyx
cython -l -t -f -v -p --gdb -D -a --line-directives -3 --lenient hello.pyx
gcc -O -fverbose-asm -S $(pkg-config --cflags --libs python3) hello.c
gcc -c hello.s -o hello.o```
gcc -O -fverbose-asm -S $(pkg-config --cflags --libs python3) hello.c
this line doesnt work
D:\_>gcc -O -fverbose-asm -S $(pkg-config --cflags --libs python3) hello.c
gcc: error: $(pkg-config: No such file or directory
gcc: error: python3): No such file or directory
gcc: error: unrecognized command line option '--cflags'
gcc: error: unrecognized command line option '--libs'
gcc -O -fverbose-asm -S "$(pkg-config --cflags --libs python3)" hello.c this also doesnt work
replace $(...) with your python src location
for me its -I/usr/include/python3.10
$() is bash syntax, you're trying to run it in cmd
@floral meteor do you have an esoteric version of with statement? i need to make listcomp with with expression
for m in i:
with __import__("contextlib").suppress(AttributeError,IndexError):
...```
class structure:
def __rs(s,exc,msg,*a,**kw):raise exc(msg,*a,**kw)
def __init__(s,cls):s.__dc=__import__("copy").deepcopy;s.__cls=cls;s.__al=list(cls.__annotations__.items());cls.__cls=s.__cls;cls.__repr__=lambda s:"<structure %s, %s>"%(s.__cls.__name__,s.__f)
def __call__(s,**i):__cls=s.__dc(s.__cls)();__cls.__f=i;return __cls if[setattr(__cls,kwn,kwi)if(type(kwi)==v)else s.__rs(Exception,"type mismatch, required %s, got %s"%(v,type(kwi),))if(k==kwn)else 0for(k,v)in s.__al for(kwn,kwi)in list(i.items())]is not None else None
def __getitem__(s,i):
__cls=s.__dc(s.__cls)();__cls.__f={}
for m in i:
with __import__("contextlib").suppress(AttributeError,IndexError):(_nop:=lambda s,*a:0)(setattr(__cls,f[0],m),__cls.__f.update({f[0]:m}))if((f:=s.__al[(ix:=i.index(m))])[1]==type(m))else s.__rs(Exception,"type mismatch, required %s, got %s"%(f[1],type(m)))setattr(__cls,nf[0],None)if getattr(__cls,(nf:=s.__al[ix+1])[0])is not None else 0
return __cls```
@rapid sparrow added repr as requested
Well, a with statement is mostly syntactic sugar for a try-finally block.
Hey, I just made small copy of wordle
"[A] - Letter in correct place, (B) - Letter exists but it is in a wrong place, {C} - Letter does not exist."
import random as r
x,y,g=list(open('i')),"",0
z=r.choice(x)
while(y!=z.strip() and g<6):
y,i,f=input()[:5],0,""
if(len(y)>4):
for _ in y:
if y[i]==z[i]:f+=f"[{_}]"
elif _ in z:f+=f"({_})"
else:f+='{'+_+'}'
i+=1
print(f);g+=1
print(f"{g}/6")
any ideas how to golf it even more?
Does it support multiple of the same letter?
231 bytes
import random as r
x,y,g=[*open('i')],0,0
z=r.choice(x)
while y!=z.strip() and g<6:
y,f=input()[:5],""
if len(y)>4:
for a,b in zip(y,z):
f+=f"[{a}]"if a==b else f"({a})"if a in z else'{'+a+'}'
print(f);g+=1
print(f"{g}/6")
227
import random as r
z,y,g=r.choice([*open('i')]),0,0
while y!=z.strip() and g<6:
y,f=input()[:5],""
if len(y)>4:
for a,b in zip(y,z):
f+=f"[{a}]"if a==b else f"({a})"if a in z else'{'+a+'}'
print(f);g+=1
print(f"{g}/6")
it doesnt matter what the intial value is as it gets assigned an value within the loop
so we can save a char
ah i see
Can I somehow do something like
p=print()
#and then
p(x)
oh i can
import random as r
z,y,g,p=r.choice([*open('i')]),0,0,print
while y!=z.strip() and g<6:
y,f=input()[:5],""
if len(y)>4:
for a,b in zip(y,z):
f+=f"[{a}]"if a==b else f"({a})"if a in z else'{'+a+'}'
p(f);g+=1
p(f"{g}/6")
still 227 chars ;p
space before and
226
no newline after for
and also from random import*
from random import*
z,y,g,p=choice([*open('i')]),0,0,print
while y!=z.strip()and g<6:
y,f=input()[:5],""
if len(y)>4:
for a,b in zip(y,z):f+=f"[{a}]"if a==b else f"({a})"if a in z else'{'+a+'}'
p(f);g+=1
p(f"{g}/6")
221
z,g,p=y=r.choice([*open('i')]),0,print
-2
what happened here
y can be assigned with anything at the start, so it's set to the 3-tuple
ah
thats cool
didn't know u can assign like this in python
(219chars)
from random import*
z,g,p=y=choice([*open('i')]),0,print
while y!=z.strip()and g<6:
y,f=input()[:5],""
if len(y)>4:
for a,b in zip(y,z):f+=f"[{a}]"if a==b else f"({a})"if a in z else'{'+a+'}'
p(f);g+=1
p(f"{g}/6")
i think there was even shorter way to import random
__import__('random') is longer
okay
or the same length actually
is the len(y)>4 check really necessary? cant we just assume the user will give correct input? :)
we caaan assume
also, z.strip() can be made into z[:5] if you only care about length
yeah, this does that aswell... assuming correct input :)))
202
from random import*
z,g,p=y=choice([*open('i.txt')]),0,print
while y!=z[:5]and g<6:
y=input()[:5]
if len(y)>4:p(*[f"[{a}]"if a==b else f"({a})"if a in z else'{'+a+'}'for a,b in zip(y,z)]);g+=1
p(f"{g}/6")
outputs the result with spaces tho:
[h] [e] [l] [l] [o]
like this
without .txt it is 202
oh yeah yeah yeah
mb
y=input()[:5]
if len(y)>4:
to this
y=input()
if len(y)=5:
is -4 chars
need to be ==5
right. still -3
I wonder how people on code.golf get something like 100 chars but 95 bytes
back to the old for-loop and printing, this is 199:
from random import*
z,g,p,w=y=choice([*open('i')]),0,print,"{}[]()"
while y!=z.strip()and g<6:
y,f=input()[:5],""
for a,b in zip(y,z):h=w[2*(a==b)+2*(a in z):];f+=h[0]+a+h[1]
p(f);g+=1
p(f"{g}/6")
and it looks better
I don't like these long lines
thats some black magic
w[2*(a==b)+2*(a in z):]
yea i wanted to get rid of the if-else-if-else and all the extra quotes and f-string {} so i focused mostly on that region.
That's what i came up with ๐
mind explaining how it works?
The original idea was that h becomes {}, [] or () and f+=h[0]+a+h[1] could be used.
To do that, instead of storing 3 strings,i used 1 longer one to save on quotes w="{}[]()"
And then I need string splicing h=w[0:2] for {} etc.
Because we only do h[0] and h[1] we don't need the second number in the splice, if h is equal to "{}[]()" then it would still print {} which is fine.
So all that's left is calculating the right digit for h=w[0:]
The last thing you need to know is that a boolean automatically casts to 0 or 1 when interacting with numbers. So 2* True is 2, and 2*false is 0.
And then it's just some clever boolean maths really.
okey
gotta make notes
for golfing
cuz there is so many cool tricks
boolean automatically casts to 0 or 1 when interacting with numbers. So 2* True is 2, and 2*false is 0.
178 with funky printing again:
from random import*
z,g,p,w=choice([*open('i')]),1,print,"{[(}])"
while(y:=input()[:5])!=z[:5]and g<6:p(*[(h:=w[(a==b)+(a in z):])[0]+a+h[3]for a,b in zip(y,z)]);g+=1
p(f"{g}/6")
ahhh the new := i would've never thought of that one.
edited with input being assigned in the while declaration
:=
thats something new
good to know that it exists
i needed something like this before
also changed {}[]() to {[(}])
that way you can remove the 2* in the w thingy
You do sadly miss the last print/evaluation with the y:= tho
removing it and reverting is +2
And I see that you skipped input length check
i mean.. it still works, and gives the correct information from a 3 letter word
true true
removing the w variable gives -4
okey
from random import*
z,g,p=choice([*open('i')]),1,print
while(y:=input()[:5])!=z[:5]and g<6:p(*[(h:="{[(}])"[(a==b)+(a in z):])[0]+a+h[3]for a,b in zip(y,z)]);g+=1
p(f"{g}/6")
Like this?
ye
then it doesn't work correctly
works on my end
abcde
{a} {b} {c} {d} [e]
eeeee
[e] [e] [e] (e) [e]
Can you send your code?
So I can compare
from random import*
z,g,p=choice([*open('i')]),1,print
while(y:=input()[:5])!=z[:5]and g<6:p(*[(h:="{[(}])"[(a==b)+(a in z):])[0]+a+h[3]for a,b in zip(y,z)]);g+=1
p(f"{g}/6")
whats the matter?
"[A] - Letter in correct place, (B) - Letter exists but it is in a wrong place, {C} - Letter does not exist."
use "{([})]" then
yeah, now it works correctly
last improvement then im gone:
replacing with a map lambda is 1 char shorter:
*[(h:="{([})]"[(a==b)+(a in z):])[0]+a+h[3]for a,b in zip(y,z)]
*map(lambda a,b:(h:="{([})]"[(a==b)+(a in z):])[0]+a+h[3],y,z)
what does the * do?
basically makes the output into a tuple, which can be printed.. instead of it being a map function and printing as: <map object at 0x7f90db2c8640>
someone else here probably has a better explanation
nah, i understood
Vapoursynth - Installation of correct version for Python 3.6.9:
Running Ubuntu 18.04 on a remote server with default Python 3.6.9. Need the 18.04 for XFCE4+X2GO to work smoothly. Problem: I need a way to install the correct version of Vapoursynth for this set-up. Installing the latest version of vs (R57) leads to problems when trying to install vs plugins, for eg. ffms2
yes.
finding out about this was such a mistake. i havent gotten any work done today lol
lol it's easy to spend all day optimizing
i got it down to 77 with some exec and fstring nonsense but I have no idea how you guys got like 71/72
I had to give up and get to work
lyndon is a beast
I am excited to see what they did tho I hope it isn't an easy trick I missed somehow
New in terrible-ideas: slicing, but with floats!
>>> from terrible_ideas import float_slicing
>>> "wat"[0.5:]
'vat'
at the moment this is done in a dumb, hardcoded way, but maybe I could draw the relevant character with Pillow, slice it to the nearest pixel and then find the closest character ๐ค
thats awful and amazing
@restive void in theory you could do it for arbitrary containers too by taking the item, converting to string, passing to pillow, attempting to parse back into string, then call constructor of the item on the string
so that [8][0.5:] -> [3]
finally, intuitive slicing
:D
I see how it would work for ints, but what would [None][.5:] do?
>>> 'o'[0.5:]
'โ'
>>> 'o'[:0.5]
'c'
>>> '8'[:,:0.5]
'o'
``` slicing in vertical direction
>>> 'E'[0.5:]
'โก'
Yes, I thought about multi-dimensional slicing as well..
>>> '='[0.5]
':'
at the moment, it works only with a few characters and only with .5
>>> aa * 0.5
a
does it need to serve any purpose?
while True:
bre + (e if False else ak)
```?
lol
modify globals() to make break and continue variables
when you try access this variable from globals(), it breaks or continues
x = 1
def func1():
print("1")
def func2():
print("2")
def func3():
print("3")
while x <= 3:
func + x + ()
x++
for i in range(3):
func{i}()
You could even define your own dunder __fraction__(self, fraction: float)
Then you can implement fractional slicing for arbitrary Sequence types
it will save one char when golfing
i+=1
When f-strings came out, I built "f-lists" and "f-tuples" :D
doable if you switch to pre-inc/decrement
no empty f-lists 
f{1,2,3} - proposed syntax for frozensets
Though you would still have to override getitem on the containers you wanted hmmm
whatever
add new dunders for everything
it's part of the style guide
why not #def syntax?
or ##def
it is valid syntax, so it will not confuse python-related tools (formatters + type-checkers)
Lmao
!e
def f(n):
try:
1 // n
f(n - 1)
except ZeroDivisionError:
1 // 0
f(900)
@analog shadow :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in f
003 | ZeroDivisionError: integer division or modulo by zero
004 |
005 | During handling of the above exception, another exception occurred:
006 |
007 | Traceback (most recent call last):
008 | File "<string>", line 4, in f
009 | File "<string>", line 6, in f
010 | ZeroDivisionError: integer division or modulo by zero
011 |
... (truncated - too many lines)
Full output: too long to upload
dear god what did I created:
def cleanDICT(Config):
keys = []
values = []
tuples = []
for key in Config.keys():
keys.append(key)
for value in Config.values():
values.append(value)
for x in range(0, len(Config)):
tuples.append((keys[x], values[x]))
return tuples
from replit import db # this works for replit users
results = []
test_dicts = [{'test1': 90}, {'test2': 89}, {'test3': 87}]
for test in test_dicts:
test = cleanDICT(test)
results.append(test)
for result in results:
for key, value in result:
db[key] = value
for viewing database on Replit:
from replit import db
for num, key in enumerate(db.keys()):
print(num, key)
for num, val in enumerate(db.values()):
print(num, val)
I could preprocess easily, but if you want everything in one line you'll have to find something builtin that handles errors and work around that.
Someone has previously in this channel made a rather clunky try-except lambda expression, unfortunately that's the best we can do in python until the developers realise how badly we need inline error handling
okay, thanks
nice
namespace Test:
class abcdef:
constructor(self):
pass;
self::onCall(self):
<--("hello world");
Test::abcdef test();
test();```
โฏ py comp.py test.py --compile
preprocessed output:
import rich,_io
rich_print=getattr(rich,"print")
__dump__,__getch__=lambda*args:rich_print(*args),lambda*args,**kwargs:input(*args,**kwargs)
class Test:
class abcdef:
def __init__(self):
pass
def __call__(self):
__dump__("hello world")
test:Test.abcdef=Test.abcdef()
test()
โฏ ./test.o
hello world```
btw compiling is done using cython and gcc
it just gets down to asm and then compiles it
regex for matching c-like function definitions: ((\ |\t?)+(((\w+)((?:\:\:\w+)?)+)\ (.*)(\((.*)\))))
regex for matching rust-like decorators: (((\ +)?|(\t+)?)\#\[(.*)\])
for matching c-like variable definitions: ((\ |\t?)+((\w+((?:\:\:\w+)?)+)\ (\w+)\ ?\=\ ?(.*);))
for matching c-like type annotations (class initializations): ((\ |\t?)+(((\w+)((?:\:\:\w+)?)+)\ (\w+)(\((.*)\));))
matches any name(args), then moving groups to python-style will give def name(args)->any
#[any]->@any
type name = "Hello World";->name:type="Hello World"; (any specified type must be moved to python style annotation)
class::path name(args);->name:class.path=class.path(args)
What is difference between cython and cpython ?
cython is python to c transpiler while cpython is the main python implementation
Ah i see.
how just make the preprocessor initialise
a, i, tab = {0:0}, 0, 0
then translate brainfuck characters to their python counterparts, using tab to keep track of the indent level
so that the translation of
print("Hello World!")
to brainfuck:
++++++++++[>+++>+++++++>++++++++>++++++++++>+++++++++++<<<<<-]>>++.>>+.+++++++..>+.<<<<++.>>+++++++.>>.+++.<.--------.<<<+.
translates to
a, i = [0,0,0,0,0,0], 0
a[i] = a[i] + 10 % 256
while a[i]:
i += 1
a[i] = a[i] + 3 % 256
i += 1
a[i] = a[i] + 7 % 256
i += 1
a[i] = a[i] + 8 % 256
i += 1
a[i] = a[i] + 10 % 256
i += 1
a[i] = a[i] + 11 % 256
i -= 5
a[i] = a[i] - 1 % 256
i += 2
a[i] = a[i] + 2 % 256
print(end=chr(a[i]))
i += 2
a[i] = a[i] + 1 % 256
print(end=chr(a[i]))
a[i] = a[i] + 7 % 256
print(end=chr(a[i])*2)
i += 1
a[i] = a[i] + 1 % 256
print(end=chr(a[i]))
i -= 4
a[i] = a[i] + 2 % 256
print(end=chr(a[i]))
i += 2
a[i] = a[i] + 7 % 256
print(end=chr(a[i]))
i += 2
print(end=chr(a[i]))
a[i] = a[i] + 3 % 256
print(end=chr(a[i]))
i -= 1
print(end=chr(a[i]))
a[i] = a[i] - 8 % 256
print(end=chr(a[i]))
i -= 3
a[i] = a[i] + 1 % 256
print(chr(a[i]))
If I made a transpiler I would make it raise
TranspilerError: transpiler finished with non-zero indent level.
I would also build in a variant of a brainfuck interpreter that doesn't print or input anything but instead returns how many memory cells the script is likely to use; maximum i minus minimum i
It's great for making obfuscated python code if you can write in brainfuck
!e ```py
import ctypes as c
class memaddr:
init=lambda s,addr:s.setattr("addr",addr)
def write(s,d):
return 0if((lambda a:True if a is None else False)(({
int:c.c_int,
str:c.c_char_p,
bytes:c.c_char_p,
float:c.c_float,
}.get(type(d))).from_address(s.addr+type(d).basicsize).setattr("value",d)))else 1
get=lambda s,t:(t).from_address(s.addr)
repr=lambda s:"[memoryaddr: %s]"%(hex(s.addr),)
class mem_impl:
init=lambda s:s.setattr("cells",[])
def getitem(s,*cls):
with import("contextlib").suppress((SkipExc:=type("SkipExc",(Exception,),{"init":lambda s:None}))):raise[Exception("expected memaddr object, got %s"%(type(c),))if not isinstance(c,memaddr) else SkipExc for c in cls][0]
s.cells=cls[0]if type(cls[0])is tuple else cls
return s
get=lambda s,c:s.cells[c]
repr=lambda s:"[memorypack%s%s]"%(";"if len(s.cells)<1else": "," ".join([c.repr()for c in s.cells]),)
mem=mem_impl()
var = 20
a = memaddr(id(var))
b = mem[a]
print(a, b)
print(b.get(0))
b.get(0).write(10)
print(var)
@sly root :white_check_mark: Your eval job has completed with return code 0.
001 | [memoryaddr: 0x7fa5e4ba0350] [memorypack: [memoryaddr: 0x7fa5e4ba0350]]
002 | [memoryaddr: 0x7fa5e4ba0350]
003 | 10
!e ```py
import ctypes as c
class memaddr:
init=lambda s,addr:s.setattr("addr",addr)
def write(s,d):
return 0if((lambda a:True if a is None else False)(({
int:c.c_int,
str:c.c_char_p,
bytes:c.c_char_p,
float:c.c_float,
}.get(type(d))).from_address(s.addr+type(d).basicsize).setattr("value",d)))else 1
get=lambda s,t:(t).from_address(s.addr)
repr=lambda s:"[memoryaddr: %s]"%(hex(s.addr),)
class mem_impl:
init=lambda s:s.setattr("cells",[])
def getitem(s,*cls):
with import("contextlib").suppress((SkipExc:=type("SkipExc",(Exception,),{"init":lambda s:None}))):raise[Exception("expected memaddr object, got %s"%(type(c),))if not isinstance(c,memaddr) else SkipExc for c in cls][0]
s.cells=cls[0]if type(cls[0])is tuple else cls
return s
get=lambda s,c:s.cells[c]
repr=lambda s:"[memorypack%s%s]"%(";"if len(s.cells)<1else": "," ".join([c.repr()for c in s.cells]),)
mem=mem_impl()
var = b"Test"
a = memaddr(id(var))
b = mem[a]
print(a, b)
print(b.get(0))
b.get(0).write(b"TEST")
print(var)
@sly root :white_check_mark: Your eval job has completed with return code 0.
001 | [memoryaddr: 0x7f6d2ecf46f0] [memorypack: [memoryaddr: 0x7f6d2ecf46f0]]
002 | [memoryaddr: 0x7f6d2ecf46f0]
003 | b'TPI\xcf'
ohh
!e ```py
import ctypes as c
class memaddr:
init=lambda s,addr:s.setattr("addr",addr)
def write(s,d):
return 0if((lambda a:True if a is None else False)(({
int:c.c_int,
str:c.c_char_p,
bytes:c.c_char_p,
float:c.c_float,
}.get(type(d))).from_address(s.addr+type(d).basicsize).setattr("value",d)))else 1
get=lambda s,t:(t).from_address(s.addr)
repr=lambda s:"[memoryaddr: %s]"%(hex(s.addr),)
class mem_impl:
init=lambda s:s.setattr("cells",[])
def getitem(s,*cls):
with import("contextlib").suppress((SkipExc:=type("SkipExc",(Exception,),{"init":lambda s:None}))):raise[Exception("expected memaddr object, got %s"%(type(c),))if not isinstance(c,memaddr) else SkipExc for c in cls][0]
s.cells=cls[0]if type(cls[0])is tuple else cls
return s
get=lambda s,c:s.cells[c]
repr=lambda s:"[memorypack%s%s]"%(";"if len(s.cells)<1else": "," ".join([c.repr()for c in s.cells]),)
mem=mem_impl()
var = b"hello world"
a = memaddr(id(var))
b = mem[a]
print(a, b)
print(b.get(0))
b.get(0).write(b"test")
print(var)
@sly root :white_check_mark: Your eval job has completed with return code 0.
001 | [memoryaddr: 0x7fd071c006f0] [memorypack: [memoryaddr: 0x7fd071c006f0]]
002 | [memoryaddr: 0x7fd071c006f0]
003 | b'hP\t\xc0q\xd0\x7f\x00\x00ld'
wtf
you broke it harder!
you managed to turn ascii into mojibake
xd
if it works with single char
lol
so it works normally when changing ints
and it doesn't works if target string is not bytes
!e ```py
import ctypes as c
class memaddr:
init=lambda s,addr:s.setattr("addr",addr)
def write(s,d):
return 0if((lambda a:True if a is None else False)(({
int:c.c_int,
str:c.c_char_p,
bytes:c.c_char_p,
float:c.c_float,
}.get(type(d))).from_address(s.addr+type(d).basicsize).setattr("value",d)))else 1
get=lambda s,t:(t).from_address(s.addr)
repr=lambda s:"[memoryaddr: %s]"%(hex(s.addr),)
class mem_impl:
init=lambda s:s.setattr("cells",[])
def getitem(s,*cls):
with import("contextlib").suppress((SkipExc:=type("SkipExc",(Exception,),{"init":lambda s:None}))):raise[Exception("expected memaddr object, got %s"%(type(c),))if not isinstance(c,memaddr) else SkipExc for c in cls][0]
s.cells=cls[0]if type(cls[0])is tuple else cls
return s
get=lambda s,c:s.cells[c]
repr=lambda s:"[memorypack%s%s]"%(";"if len(s.cells)<1else": "," ".join([c.repr()for c in s.cells]),)
mem=mem_impl()
var = b'test'
memaddr(id(var)).write(b'g\x00e\x01\x01Vk')
print(var)
@sly root :white_check_mark: Your eval job has completed with return code 0.
b't\x00H\xa3'
it even got messed up with bytes lol
!e ```py
import ctypes as c
class memaddr:
init=lambda s,addr:s.setattr("addr",addr)
def write(s,d):
return 0if((lambda a:True if a is None else False)(({
int:c.c_int,
str:c.c_char_p,
bytes:c.c_char_p,
float:c.c_float,
}.get(type(d))).from_address(s.addr+type(d).basicsize).setattr("value",d)))else 1
get=lambda s,t:(t).from_address(s.addr)
repr=lambda s:"[memoryaddr: %s]"%(hex(s.addr),)
class mem_impl:
init=lambda s:s.setattr("cells",[])
def getitem(s,*cls):
with import("contextlib").suppress((SkipExc:=type("SkipExc",(Exception,),{"init":lambda s:None}))):raise[Exception("expected memaddr object, got %s"%(type(c),))if not isinstance(c,memaddr) else SkipExc for c in cls][0]
s.cells=cls[0]if type(cls[0])is tuple else cls
return s
get=lambda s,c:s.cells[c]
repr=lambda s:"[memorypack%s%s]"%(";"if len(s.cells)<1else": "," ".join([c.repr()for c in s.cells]),)
mem=mem_impl()
var = b'test'
memaddr(id(var)).write(b'g\x00e\x01\x01Vk')
print(memaddr(id(var)).get(c.c_char_p))
@sly root :white_check_mark: Your eval job has completed with return code 0.
c_char_p(3)
lambda a:True if a is None else False -> lambda a: a is None
i remembered my problem about inline ifs in python because of this lol
i'll add preprocessing step to my pseudo lang
str a = "hello world" if b```->```py
a:str="hello world" if b else(lambda:a.__del__()if a is not None)()if not b else None```
or will be better with normal ternary operator ?:
simple regex for it ((\ |\t?)+(.*)\ ?\?\ ?(.*)\ ?\:\ ?(.*))
group 2 is the captured indent
namespace Test:
class abcdef:
constructor(self):
pass;
self::onCall(self):
<--("hello world");
Test::abcdef test();
test() ? 1 : <--("test");
converts to this:
import rich,_io
rich_print=getattr(rich,"print")
__dump__,__getch__=lambda*args:rich_print(*args),lambda*args,**kwargs:input(*args,**kwargs)
class Test:
class abcdef:
def __init__(self):
pass
def __call__(self):
__dump__("hello world")
test:Test.abcdef=Test
test()if(1)else __dump__("test")```
but nested ternaries are a problem for this
because then regex must be very complicated, with repeating patterns and lookaheads/behinds to check if theres another ternary
I'll be working on it
example: __dump__("works")?1:(__dump__("first")?2:(__dump__("second")if(3)else __dump__("third")))
so it replaced only the last ternary
wtf is esoteric python
imagine Python but you're like deep down the rabbit hole for python
Correct
Ok I'm lost and need help, but I think this is "out of the ordinary" of what most people would do with python.. So..
Why does this:
print(f"--Executing: {self.cmd}")
End up in this data:
output = os.read(self.child_fd, 8192)
Where the child_fd is different from sys.stdout.fileno() and is created with:
self.pid, self.child_fd = pty.fork()
(full code here: https://github.com/archlinux/archinstall/blob/c64bc3a1f2d294f97cde8008111c1406ebdb8702/archinstall/lib/general.py#L354-L357)
archinstall/lib/general.py lines 354 to 357
self.pid, self.child_fd = pty.fork()
os.chdir(old_dir)
print(f"--Executing: {self.cmd}")```
Why wouldn't it?
You fork and therefore execute the print in both parent and child. The child's output ends up in its fd
Note the if not pid: below, which contains the code only to be executed by the child.
The parents sys.stdout.fileno() is different from the childs sys.stdout.fileno() is it not?
I don't know what pty does specifically, but normally file descriptors are inherited after a fork
https://docs.python.org/3/library/pty.html#pty.fork specifies that the new pseudo-terminal gets a new file descriptor. So I assumed that they did not inherit the same file descriptors : /
Ok. Nevertheless, you read from the child's file descriptors
yea but print to another? Or is the print() code executed in the context of the child?
Both
That's just how forking works
Then what's the point of os.write() to the specific child file descriptor, if print outputs to both :S
Both child and parent continue at the same place
print outputs to both before the if not pid:
Like it's not that the one print call writes to both
print gets called twice, once in each process
Oh f*** me xD haha, ok that's a huge miss on my part then.
If I move the print to after os.execve, will that still hold True? Or is it anything up to the point of os.close(child_fd)?
os.execve replaces the current process with the new process given by args
If you only want to print in the parent, move it to an else branch (so if pid is not falsy)
Yea that worked, I think. I think I have code, that depends on this - that might output something.. some how.. between pty.fork() and os.execve(), meaning it's not "in the else"..
Btw huge thank you for explaining this in pretty good detail. 50% of it is still black magic that I guess I haven't wrapped my head around (thought I had..).
But at least this sheds clarity to what's going on and where to look for the bug ๐ So thank you!
Yeah, no problem. This is also very unesoteric and has nothing to do with Python, that's just how unix' fork() works
I hear you loud and clear on that one, I guess I can only apologize and claim lack of knowledge thought this was python-dark-arts things messing with me.
Oh no, don't take this as a "how dare you post this in #esoteric-python", just for "where to look next if still unclear"
I'm having a discussion with a member here who thinks that the behavior of ```py
all_equal([])
should possibly not resolve to ```py
True
as a philosophical point. I tried explaining that the function is not trying to assert that there are some elements equal to each other, but instead is validating that every element in the list meets some criteria. Since there are no elements in the list, they all do meet the criteria. I cited this:
https://en.wikipedia.org/wiki/Vacuous_truth
Then I ran out of steam, but the user is still not convinced and is seeking more explanations or other opinions. Can anyone else help with this?
cheers
@balmy night
In mathematics and logic, a vacuous truth is a conditional or universal statement (a universal statement that can be converted to a conditional statement) that is true because the antecedent cannot be satisfied. For example, the statement "all cell phones in the room are turned off" will be true when no cell phones are in the room. In this case,...
I mean it really depends on the definition of the function. But I'd expect it to return True on empty input.
That is true, it does depend on the definition of the function. Let's maybe focus on the statement For example, the statement "all cell phones in the room are turned off" will be true when no cell phones are in the room.
Donut believes this could be resolved to False instead of True. Thoughts?
So this is where pragmatics comes into play
Evaluated purely in a logical/semantic fashion you are of course correct, but pragmatics (in this case probably the maxim of relevance) implies that there are cell phones in the room.
True, there is an implication that cell phones are in the room in natural language
but in the case where that implication doesn't hold, what do we do?
Well I didn't say it has to be False but there's an argument to be made:
because if no elements are equal to each other, then not all elements are equal to each other!
see, that's not correct
it is true that all elements of an empty set are equal to each other
Logically, you would be incorrect there, @nova sun โxโy x=y holds.
"For all x, for all y, x is equal to y", would be the translation of this statement into predicate logic (with equality)
And that statements evaluates to truth when the universe is empty
if for example the iterable was [1,2,3]
how could you reason with me that all elements are equal? "logically" of course
No, because I can find two elements (1 and 2) that are not equal
because if no elements are equal to each other, then not all elements are equal to each other
this statement hold true
it does not
how come?
Show me that it does
if 1 is not equal to 2
and
2 is not equal to 3
then all of the elements are not the same, because there is at least pair 1 which is not equal
Yes, obviously. When the universe contains more than one element, then it depends on the nature of those elements whether the statement is true
I don't argue the [1, 2, 3] case
But in general it is not true that if there are no elements equal to eachother, not all elements are
not all elements are
are what? are blue? yeah I agree
...equal to eachother
(do we maybe want to take this to an off-topic channel? not really esoteric python)
give me an example and do a walkthrough with your logic and that example
Well, the two examples are an empty universe, and one containing only one element.
Let's do the latter for a change:
if the iterable is [1], then would you say that all elements are equal?
yes of course
this logic:
then all of the elements are not the same, because there is at least pair 1 which is not equal
holds here
Alright, then only the empty iterable case remains. For all elements x in the iterable, for all elements y in the iterable, they are identical.
!e
def all_equal(iterable):
for x in iterable:
for y in iterable:
if x != y:
return False
return True
print(all_equal([]))
@restive void :white_check_mark: Your eval job has completed with return code 0.
True
yes, I understand that, like the implementation on all([])
I don't argue that you're wrong, I argue that there're two truths...
arguing that there are two possible interpretations is arguing that we're wrong; the situation is that there are not two interpretations
There are (at least) two ways of translating the human language sentence "all elements in the iterable are equal" into logics, yes
because as I told usidore the blue, English is not my native tongue. you guys have a "home court advantage "
can anyone try to convince us that my point of view can be right too?
maybe you can @restive void
can you do that?
you could say that the natural language implication is that there are elements in the set, but this is cultural, language specific, and not part of formal logic
kind of. The original statement is not written in formal logic though
it's the name all_equal which (until defined one way or another) undergoes human interpretation, including pragmatics
Personally, I would certainly interpret it in the way you do, @inner blade. But I also am not a native speaker of English (but of a very related language)
I think this wiki page really covers the nuance of this pretty well, and explains how it could be misleading in natural language
In mathematics and logic, a vacuous truth is a conditional or universal statement (a universal statement that can be converted to a conditional statement) that is true because the antecedent cannot be satisfied. For example, the statement "all cell phones in the room are turned off" will be true when no cell phones are in the room. In this case,...
I don't know
But that is only once you accepted the logical interpretation I gave above in symbolic language
who decides what's formal logic, If let's say someone said that vacuous truth should be false
meaning ""all cell phones in the room are turned on and turned off", then it's false because there are no cell phones to be turned off"
would you still argue with me?
You could interpret it also as: โxโyโz x=z โง x=y
chief I barely understand English...
that example is only true when there are no cellphones in the room :D
that's my point,
two truths, society decides one, don't mean the other one is wrong or false
It's not an axiom; nobody decided. There are axioms but this is not one of them.
again, I am explaining/expressing myself poorly...
Vacuous truths are true, there's no other valid opinion about that. The question is whether a given statement leads to a vacuous truth.
(But I think I've said everything I have to say about the topic at least once, I'm gonna go; y'all have fun)
I don't think you are expressing yourself poorly. You asked why we defined the vacuous truth to be true. The answer is that we didn't. It is true.
""all cell phones in the room are turned on when there are no cell phones in the room" is a false statement because there are no cellphones that are turned on
I did, because I didn't paste the right phrase. lol
I recommend reading the wiki page, and the top answer on stackexchange, and giving them some time
I'm sorry I couldn't do more for you
I also really don't have anything else to offer
do you agree with this statement?
no
why?
because it isn't false
Who says if it's not false, it's true?
one could say if something is not true, it's false
then your "vacuous true" are false
don't reply to me with the link
let this thought float in your head for a sec
it doesn't matter what people say; it's not an opinion; vacuous truths are true - we don't define them to be true, it's an inherent characteristic
Who says if it's not false, it's true?
This actually may be pushing up against an axiom of propositional logic; not false is true, that might axiomatic
>>> not False
True
no it's not, who "inherented" the characteristic?
some person / society early on
then you just get stuck with that "solid rule" who says?
no; there are axioms, and then there are truths derived from those axioms; you assume the axioms to be true, but non-axiomatic statements either resolve to True or False under the axioms
so you assume all([]) to be an axiom yet you say it should return true?
no, ```py
all([])
is not axiomatic, but it relies on the axioms as do all statements. If you have a philosophical issue with ```py
>>> not False
True``` you should definitely focus on that
it is simply more useful to have the notion of for every element, P hold for 0 elements. It makes inductive proofs reasonably possible.
you could of course define your own system of predicates where forall entails exists, but GL actually using it
that's python interpretation of it, if I am not a girl then I must be a boy?
I could be both / neither
well, no. If you are not a girl, then you are not a girl. It makes no statement on anything else
exactly
then
not False is not always True
not False is True by the definition of a boolean
its just that boolean is not always the correct way to describe a fact
that's axiomatically true, by definition; if you don't like the definition that's actually okay
It was an example... like the boy and girl
you don't have to like the definition but it will break computer science because compsci is built on that axiom
it'll break propositional logic as well
eh, you could just rewire the axioms, it just makes things more complicated
you could create a new logic and write axioms, yes
you could derive all kinds of statements or whatever
a complete logic system is complete regardless of what insane building blocks you use
right
you are getting side tracked, you could create a world like meta and program everybody to follow you
what's the point?
True and False are booleans and are defined to have only two states. If it's not the one state, it must be the other.
all asks if every element is true, in other words, it asks whether there isn't any False, or whether it isn't true that False is in the list
I gave the example you gave, I could also give the boy / girl example
and clearly, whether False is in a list can't change by adding more True
that's why I said:
two truths, society decides one, don't mean the other one is wrong or false
thinking of all in terms of folding over an iterable with and may help (this intuitively leads to True as a default value)
so all([]) and all([True]) should have the same result
similarly, any is an or-fold, yielding a default value of False
yeah any is means that at least one element in the set meets some predicate
all([]) and any([])
``` should be False
they're just friendly names for forall & exists
any([]) is false wtf,
indeed, no element of [] is True
correct
did you read the and-folding
how does that follow your https://en.wikipedia.org/wiki/Vacuous_truth?
In mathematics and logic, a vacuous truth is a conditional or universal statement (a universal statement that can be converted to a conditional statement) that is true because the antecedent cannot be satisfied. For example, the statement "all cell phones in the room are turned off" will be true when no cell phones are in the room. In this case,...
in other words, every element of [] is False
forall vs exists
yes, what you said made perfect sense to me
the trick is that the negation of all(x) is not any(not y for y in x)
"there are some cellphones, therefore some of them are turned off"
no
you have changed the definition from exists to subset
since some cellphone doesn't exist
that is a different statement
well that's simply not a valid stream of logic
wait, revert that
yeah cellphones don't exist then y all of them are turned off?
the point is, natural language is not rigorous
because it makes math easier that way
and more consistent
if you define things differently, predicates get more complicated
basically it avoids having to add special cases to every empty set
this is a very natural way to form these predicates
ok then I made my point!
you just decided that, I could decided the opposite
and you can't say my decision is false or wrong
tl;dr is it the (mathematically) natural definition
and thus maths & much of programming follows the convention
of course, you can do whatever definitions you want
conventions are not facts
so what
it is wrong under the axioms, but one of those axioms is not False == True
I started reading this and it reminded of how people explain why 0 factorial equals one x)
I rest my case
well, definitions aren't truths
definitions are true by definition :>
they are simply helpers to express things
which still proves my point
if your point was that it is valid to invent a forall which entails exists, sure
i'm not sure what this argument stems from since I dropped in late, but I hope I have been able to explain some of the mathematical reasoning for the convention
if it's a personal gripe then i couldn't care less though
.
let me pose a fun little problem: under your formalism, what is the negation of every cellphone in the room is off?
I didn't understand that.
but my point is that all([]) doesn't have to be True it can be False,
we decided that it would be True
but saying that the result is False is not false or wrong (maybe by convention, but we decided a convention)
.
wdym?
write a statement that is the opposite of every cellphone in the room is off
every cellphone in the room is not off
under the conventional definitions, it is there is a cellphone in the room that is on
well, that's wrong
because what if we have one cellphone that is on, and another that is off
then not every cellphone is off, but your statement also isn't true
so it isn't the opposite
again who decided the โจconventionโจ ?
No, but in this case it is just logic
lets not worry about that. Your negation was wrong in an objective way
let me help you, we did!
don't mean it's the only truth
@balmy night i recommend that you focus on the example provided, they're trying to help give you an insight
in the same way I can define the absolute value in terms of distance from the value 1+4j, you can define your predicates differently. Doesn't make it actually useful or meaningful
who said that true is true?
we, we could have said that true is false
it's not an axiom...
ok yours is correct
under your definitions, it isn't
why not?
are you perhaps interpreting all(X for X in Y if Z) similarly to "is the proportion of X in Y that satisfy Z 100%"?
well, for a room with no cellphones, you state that not all are off. My negation is that there is at least one which is on, which is also not true
therefore, not a negation
please examples are not great,
focus on my statement:
two truths, society decides one, don't mean the other one is wrong or false
this isn't a society thing tbh
truth is objective
it's a "overwhelmingly common mathematical convention" thing
it just lies on how we describe it
you can write the same statements under any weird mix of definitions
yes, but why it must be 100% correct?
didn't we make mistakes in the past?
I am very confused
you are kind of missing the point
the statement under your definitions would be written in mathematical language like so there is at least one phone, and all the phones are off
again english is not my native tongue
maybe can someone brave try to "move" to "my side"?
it's the same statement as all phones are off under your understanding of all
like, sure you can e.g. divide by zero if you just define it to work
but, like, you lose a lot of interesting properties of real numbers that way, and it turns out the maths becomes more complicated, and it's not as useful of a tool as what you had originally
just written differently because well, definitions differ
actually, I should check
the truth of a statement is objective, the way to write that statement depends on definitions
is formal logic + "empty forall is false" even a consistent (non-contradictory) system of logic lol
it might not
here, even look at your sentence...
who said I am missing the point, did you make the point for me to miss?
I am aiming for my point
why tf would I aim for yours?
it trivially is tbh
you can just add a disjunction to every forall allowing for an empty set by negating exists: 1
and you are back to how we were before
so such a system is structurally equivalent, just phrased differently
no takers?
there are 2 different things at play here. What a given statement means, and how we write a given statement
the meaning is objective, the notation is not
so there aren't really 2 truths
just like the same sequence of letters can mean different things depending on language
this is a difficult question: for all has a definition and its definition isn't part of formal logic; you could write marbles instead and set things up to work... I know this is probably isn't what you were getting at
i meant like I see
โ
again, notation is ambiguous
@earnest wing under the defined meaning + axioms, empty has to be True or the logic is inconsistent
there is a reason math doesn't use english
I don't get what notation is here, did I make any?
yes, english is notation
not a very good one from a formal perspective, since, as you demonstrated, it is ambiguous
yeah I mean you have this symbol; this symbol has a meaning, and under that meaning if you also define the application of that symbol to an empty set with some predicate as False, then you won't have a consistent logic anymore
also kind of complicated to manipulate, in contrast to sth like predicate logic
logic is a notation too
I also found interesting resources
indeed
then you can't say there's no two truths!
there are no two truths
just two ways to write one truth
facts don't change, our ways to describe them do
and when we say predicate logic, we mean the conventional definitions, including forall being true for empty sets.
just because otherwise communication breaks down
python, all, any, are all notation that we interpreted one way, but we could have easily interpret them the other
.
sure, but then those functions mean different things entirely, and thus are new notation which describe different underlying logic
same word, but you give it a new meaning
You have a better case with all thenany, any strictly has to be "do any of the objects in this equal true" which should be false for an empty sequence
everything we: think, hear, see, write, and so on
are all interpretations! you can't say that only one way is correct,
you have to define what is correct which is again also a notation
therefore everything is a notation and nothing is "all ways true"
under some notation, you can get objective truths
without definitions, notation is useless
not always in the kind we think, always - all the ways
only in the sense that you could define 0 == 1 to be True
no
but well, in the way all is defined, all([]) is True
if you change the definition, it doesn't have be True
I define a list will all true values to have:
- elements
- all elements must be true
you can always change the definition; are you asking if we could change the word all to marbles? We could do that.
then you changed the definition, and now have a new idea, distinct from what all means in python right now
we could replace the word all in the dictionary with smoarea, but all has a meaning and if we focus on the meaning rather than the term, then we're still faced with the same problem
And I quote "two truths, society decides one, don't mean the other one is wrong or false"
vacuous truth is still truth no matter what words we use
it's not
you can of course invent your own terms, even reusing existing terms, in which vacuous truths are explicitly forbidden by attaching an implicit there is at least one
depends on how you define true?
I mean, I would agree with them that you could say that if you start from the point that all propositions are false until proven otherwise, you could say that "all elements must evaluate to true" should be false
if there are no elements
ok well, I gave it my best shot, I don't have anything else to offer, I'm sorry
@inner blade okay right yeah \forall x \in X . P(x) desugars to \forall x . x \in X -> P(x) and the subset statement is always false for empty sets, therefore the whole expression is true by explosion
and you can't make that false without changing a lot more
that's very clear now
You guys can be funny, but my point stands...
good luck
the negation of all elements are true is at least one element is false, which is trivially proven false, therefore the original statement holds
the true isn't really a "default"
wouldn't the actual negation be "one or more" ?
just curious ๐
well, one element is false is also another natural language gotcha
if all elements are true, and the opposite is one element is false
it doesn't says s.. about nothing does it?
this is why we invented predicate logic
well, one element is false is clearly not true for an empty list
there is no one element that is false
I am trying too, but try thinking about it this way, he put the all() into a proposition
Lets find a way to negate that
neither is it for "all elements are true" ?
every single element of an empty list is true
all elements are true and all elements are false are both True for an empty list
both conditions are not met, then why is it true?
well if X and ~X are both false you don't have a conventional system of logic
answer please
^
this is the moment we all lived for
is {ร} truthy? if so why? no elements to compare to
it should be in a state of limbo, no?
do you mean a singleton set of an empty set?
what plain old - not wiki pages -"logic" has to say?
that is a non-empty set, so it is not really weird in this way
@inner blade ?
well, if both conditions are not met, then clearly we didn't find a negation
{ร} is the empty set
I don't understand your question, could you write it again in a different way? @balmy night
isn't the empty set generally {} or ร? Not both
isnt that the set that contaisn the empty set
ร yeah this is the empty set iirc
youre right, i got it mixed up, my bad
regardless, the empty set is falsey according to python, but any statement about its elements will hold
still. my point stands
because if X is empty, then "element x is inside X, therefore Condition(x) is true" always has "false" on the left side
and the systems of logic we use define "false, therefore [literally anything]" to always be true
it's called the principle of explosion
if you don't have 1 apple
and you don't have any apple that is red
how many apples do you have?
this is an example, don't expliot it
yeah, the implication example is a good one
are you asking if the empty set by itself should resolve to True or False? That's not a propositional logic question
I either have 0 apples or 2 apples or 3 apples or any number of apples more than 3; just not exactly one apple
assuming i can only have whole integer number of apples
in order for all(x) to be True, this must hold: if an element is in x, it must be True.
every english example is just another piece of linguistic ambiguity about to confuse this conversation

- all elements in set are true
- there are no elements in the set
conclusion: is the set true?
is how i think about it
sets don't have true or false values; they're a data structure, not propositional logic
well truthiness can be defined in many ways, while forall and exists have rigid definitions
If list, ls:
- doesn't have at least one element is false (at least one element is false -> False)
- and not all elements are true (all elements are true -> False)
is ls True or False?
if all elements of a set meet some requirement for truthyness a set would be considered true, no?
"complete" or smthing
I have rephrased it
I don't know about you, but I couldn't tell you...
same
that doesn't make sense, you're saying ls is a list/set/etc but asking if it's a boolean?
not in propositional logic; the set itself doesn't have a truth value, it's a data structure; the only structures we have on propositional logic are propositions and operators; propositions are statements that are either or True or False, and operators are things like 'and', 'or', 'not' that take one or more proposition statements as input and produce either True or False as an output.
exactly, then why all([]) is True?
it's not, all([]) is
all I meant
it is not though?
oh you edited
nvm
If you can't answer this, how can you answer all([]) ?
seems like an unfair comparison to be fair
the thing that you guys don't get.
it can be the exact same thing.
think about that
@severe canyon we can say things like:
P is True, therefore P is not False.
P and (if P then Q), therefore Q
what's the easiest way to mutate locals programmatically?
Then i would still be able to construct this with only boolean evaluations as you define propositions as:
- A set is truthy if all its elements meet a requirement for truthyness
- A set is false if any of its elements fail to meet the requirement for truthyness
- The set is empty
assuming 3. is True, what would 1 and 2 evaluate to?
(without assignment ofc, assuming string keys etc)
eval
did you mean to ask if 1 and 2 are true?
sure
- is a true statement about the set (all satisfy the condition)
- is a false statement about the set (there is not a single element that fails the condition)
or I don't understand, how am I supposed to evaluate whether A set is truthy if all its elements meet a requirement for truthyness is True or not based on a set being empty?
if no elements exist, how can they meet a requirement
that's been explained about a dozen times in chat over the past hour
it mightve been, i kinda just jumped on this in the middle xD
haha
please link to the message, and ill show myself out :)
This wiki page is probably the best explanation https://en.wikipedia.org/wiki/Vacuous_truth
In mathematics and logic, a vacuous truth is a conditional or universal statement (a universal statement that can be converted to a conditional statement) that is true because the antecedent cannot be satisfied. For example, the statement "all cell phones in the room are turned off" will be true when no cell phones are in the room. In this case,...
ill take a look
it goes into some of the nuance and explains why it can be unintuitive
I was convinced by that alone lol
what does all check?
if all elements are True right?
in the case that list = []
are there any False elements? No
are all elements True? Well, there are none.
so if there are no False value, "why all elements" is True?
(this is the question all "answers")
it can be either False or True; I couldn't tell you
so you are saying it should be false right? Or are you saying there is no answer?
if all elements are True right?
no, that would be circular logic; all cannot be defined to check if all @balmy night
i think the wiki page is the clearest answer for that
so like, check out the wikipedia link
it's not
you mean it's kinda recursion?
that's not its definition; we can't define the behavior of all using all
all(iterable)
Return True if all elements of the iterable are true (or if the iterable is empty)
from docs :)
otherwise we have to evaluate all in the definition, we have to agree what it actually means first
we can't just agree that all means all as a starting point; it has to actually mean something
and if you agree that is should equal False, you lead to a contradiction
therefor it should be true
Ok, then it's defined that way, but let's say it doesn't we are making a new language....
No the thing if it doesnt have a definition
could you tell me is it True or False?
then your new language has boolean logic that creates contradictions
unless it's True of course
how does it ?
then there's no contradiction
No because you havent defined it
You have said "all checks if all"
you cannot define something like that, it is like asking what a word means and saying it means itself
exactly, this is my point...
you can't tell me; unless it's defined / we define it as something....
honestly, maybe this is an English problem, maybe you don't know what all means
we cannot define it as false
because it leads to a contradiciton
therefor it is not that we want to define it as true
we just kinda have to
maybe;
maybe you don't know...
it's all definitions, notations...
this is my point
this is my point.
my axiom is everything is false
we live in a simulation :O
?
we have to agree what it should be equal to
otherwise what is the point of having all to begin with
It must be defined
There is only one way to define it, that wont lead to a contradiction
when I say "all" you view it one way, I can view it the other.
and to a baby who isn't biased in any way, can see both "all"s as legitimate...
Consider the suggestion that all([]) and any([]) shoud both be false
The famous DeMorgon's law states that all(y) == not any(not x for x in y).
Let y be empty. Then:
all([]) == not any(not x for x in [])
all([]) == not any([])
False == not False
False == True
intuition is subjective...
"all"s as legitimate... no, because only one of them don't lead to a contradiction where unicorns exist
logic is not subjective :>
the "intuitive sense" bit was just trying to explain why the law is true at a glance
who defined "unicorn"? ?it can be defined as a horse, have you seen one?
Bruh
๐
could you provide some code context?
or maybe just describe it more
well there you go
you are giving examples, I am returning you a "favor".
it sounds stupid to you. but it can happen, use a bit of imagination
imagination is a bad choice of words, but you get me
the return value of locals() doesn't actually control the locals
it's just a copy
i remember there was a library or something that did that
well it was
I didnt know that
interesting
I thought it was just like globals but for local scopes
i think it's because of how cpython implements them
Nah it doesnt work on a function
It does work on the global scope though
Humm, can't you use the inspect module to get the stack of the function?
I dont know if it is mutable though
Hey maybe this?
Nvm the answer is right under it, you can only modify it, not add new variables
Hang on your confusing me here I expected the last three characters to be z=y.
Also this does not hold true for [1, 1]
As it seems to require three elements to exist
Swinging around these logic statements when the target audience isn't guaranteed to be able to interpret them is one thing, making a seemingly irrelevant proposition like that is another.
Also did this need to happen in #esoteric-python?
I moved to #help-lollipop
so for all x and y, x is equal to y and a third element z
!e ```py
globals().clear()
builtins={}
no brackets after this
build_class=lambda*a:None
name='main'
sub = ....class.base.subclasses
@sub.class.call
@lambda _:sub
class a:0
@a.getitem
@lambda _:104
class a:0
@a.load_module
@lambda _:'sys'
class a:0
@a.stdout.write
@lambda _:"Hello World!\n"
class a:0
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
(no, because only the existential quantifier makes something exist. The formula implies existence of at least one thing)
alright, but in that case, for all x and for all y something exists, but if there's no x and there's no y, then nothing needs to exist at the something exists expression because it parses 0 times
therefore it returns true for an empty set
because there's nothing in the set which makes the proposition false
!e
print(0**0)
print(all([]))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | True
you can't argue against mathematics and win.
everything to power of zero is 1
there's no difference between 1**0 and 0**0 because the first term is eliminated by the zeroness of the second term
hence leaving the multiplicative identity
1 * x = x
0 + x = x
x ** 0 = 1
x * 0 = 0
x + 0 = x
I don't see what is so confusing about 0**0 = 1
it's not like 0**x = 0, that's just a pattern, it doesn't hold true for x = 0
same way a/a = 1 doesn't hold true for a = 0
x ** 0 on the other hand is always 1
it is not, when the limit tends to zero then it is inderterminate
absolute 0โฐ is 1
0/0 is inderterminate
obviously 0/0 is taboo
I once had a username Negative Zero Divided By Zero
just to see how many people I could get to hate me on that basis alone, then befriend them because obviously they're the smarter ones
you do not divide by zero
Thou shalt divideth not by zero
yessss
?
example?
the other people need to prove it that so
like i say 2+2=4 someone says it is 5 then how is it inderterminate
You are right, the existential should have been in front
did you get this^
theres always one there
and the indice denotes how many times the number is going to be there
for 2ยฒ there going to be 2 two
there's zero terms of the first number, therefore it has no importance in the evaluation of the result, as there only leaves behind the multiplicative identity
yes
for exponenet belongs to I
no
wait if 0**-0 is equivalent to 0 /0 0 times, and 0**-0 can be simplified to 0**0, then that means 0\0 = 0*0 = 0
wait now my brain is fried
oh yea
-0 is 0
how?
absolute 0โฐ is not indeterminate
lim x->0 x^x is indeterminate
-0 is not a thing
0 divided by zero, zero times
that is a beautiful concept: zero doesn't get divided by zero
0**-0 is the very concept of zero not being divided by itself
also when did esoteric-python turn into esoteric-mathematics?
see this the arrow above means it tends to zero
and ex means exact
there is an implicit exp==1*exp for each exp that is reduce(multiply, iterable)
therefore if 0 is multiplied by zero zero times, that is
reduce(multiply, [0]*0)
then we have 1*(nothing)
which is just 1
yes
because 1 is the multiplicative identity
just like 0 is the additive identity, and our intuition is familiar with the linear scale, which is why we naturally feel an expression mutating 0 zero times should evaluate to 0
0**0 = 1
0**-0 => 1/0**0 = 1/1
but we're working with a different scale here, one where 1 is where everything revolves around
yes, very good, not to mention the fact that -0=0
you see in a system where 0**0, everything makes sense, except for 0/0 and related phenomena
however undefining 0**0 would just make another 0/0 issue for no reason other than your small brains find 0**0=1 unintuitive
0**a is 0 unless a is 0
!e ```py
print(import('math').log(0))
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | ValueError: math domain error
0 cant be a base
log(1)/-infinity tends to -0
its not in the domain
therefore log(1)/log(0) tends to 0
it can only be evaluated with limits
but limits tend it to 0 from the negative side
as lim h->0 log(h) -> -inf therefore lim h->0 log(1)/log(h) -> 0
someone please write something on paper typing up mathematics is unpleasant
It has been decide that in the empty set element equality problem, "all elements are equally nonexistent"
no logic whatsoever, completely intuitive argument for all_equal([]) = True
"also did this need to happen in #esoteric-python" bestie it moved channels and u brought it back
oops
!e ```py
from ctypes import py_object
p = py_object.from_address(id(0)+8)
class Int(p.value):
def truediv(self, other):
return super().truediv(other)if other else print("Hello World!")
p.value = Int
0/0
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
The only correct answer
There we go I have proved that 0/0 = Hello World!
that should scare the mathematicians out of this channel
I broke maths, and I can break it harder
!e ```py
from ctypes import*
cursed = py_object.from_address(id(0)+8)
class BreakPython(cursed.value):
def truediv(self, victim):
return super().truediv(victim)if victim else string_at(0)
cursed.value = BreakPython
0/0
@floral meteor :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
that's what dividing by zero should do in python
it should make the computer either blue screen or kernel panic depending on OS
I like your style
ty, me too
:)
I am waiting for someone to implement i++, i--
!e hmm
_ = [__import__('ctypes')]
_=[_[0].py_object.from_address(id(0)+8),*_]
class __(_[0].value):
def __truediv__(_0,_1):
return super().__truediv__(_1)if _1 else _[1].string_at(0)
_[0].value = __
0/0
@floral meteor :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
!e ```py
_ = [import('ctypes')]
=[[0].py_object.from_address(id(0)+8),*]
class __([0].value):
def truediv(0,):
return super().truediv(_)if _ else print("what")
_[0].value = __
0/0
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
what
XD
++i, --i are syntactically possible, however i++, i-- are not
why not?
!e i++
@floral meteor :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | i++
003 | ^
004 | SyntaxError: invalid syntax
that
yeah i know that
!e ++i
@fleet bridge :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 'i' is not defined. Did you mean: 'id'?
you see that's possible because no syntaxerror
thats why i said that someone should make a lib for it
++i has been done before iirc
