#esoteric-python
1 messages · Page 136 of 1
import re,numpy as N
m,z=map,N.zeros(2*[999])
for _ in open("i"):
x,y,c,u=m(int,re.findall("\d+",_))
d,f=m(N.sign,(c-x,u-y))
while(x,y)!=(c+d,u+f):
z[x][y]+=1
x,y=x+d,y+f
print((z>1).sum())
Can you index by [x,y]?
import sys
for i in sys.argv[1:]:print({'Alabama':'AL','Alaska':'AK','Arizona':'AZ','Arkansas':'AR','California':'CA','Colorado':'CO','Connecticut':'CT','Delaware':'DE','District of Columbia':'DC','Florida':'FL','Georgia':'GA','Hawaii':'HI','Idaho':'ID','Illinois':'IL','Indiana':'IN','Iowa':'IA','Kansas':'KS','Kentucky':'KY','Louisiana':'LA','Maine':'ME','Maryland':'MD','Massachusetts':'MA','Michigan':'MI','Minnesota':'MN','Mississippi':'MS','Missouri':'MO','Montana':'MT','Nebraska':'NE','Nevada':'NV','New Hampshire':'NH','New Jersey':'NJ','New Mexico':'NM','New York':'NY','North Carolina':'NC','North Dakota':'ND','Ohio':'OH','Oklahoma':'OK','Oregon':'OR','Pennsylvania':'PA','Rhode Island':'RI','South Carolina':'SC','South Dakota':'SD','Tennessee':'TN','Texas':'TX','Utah':'UT','Vermont':'VT','Virginia':'VA','Washington':'WA','West Virginia':'WV','Wisconsin':'WI','Wyoming':'WY'}[i])```
how is it possible to golf this
import re,numpy as N
m,z=map,N.zeros(2*[999])
for _ in open('i'):
x,y,c,u=m(int,re.findall('\\d+',_));d,f=m(N.sign,(c-x,u-y))
while (x,y)!=(c+d,u+f):z[x][y]+=1;x,y=x+d,y+f
print((z>1).sum())```
any1 know a guide to golfing
or something like it
i want to start having fun with golfing
well, i dont follow any guide or anything like that. I just know some tricks and i check if i can apply them to my code
simple example would be using
if:
l
if:
a
if:
l
if:
a
spaces instead of tabs
where did you find out about those tips
this discord
and
yup
people are dropping random tricks sometimes
i changed one more thing in it and it is 191chars now
import re,numpy as N
m,z=map,N.zeros(2*[999])
for _ in open('i'):
x,y,c,u=m(int,re.findall('\\d+',_));d,f=m(N.sign,(c-x,u-y))
while (x,y)!=(c+d,u+f):z[x,y]+=1;x,y=x+d,y+f
print((z>1).sum())
while(
very easy way to start is put it into https://python-minifier.com/
oh yeah, you are right
missed it
190 chars
hmmm, sad that i cant do something like this
x,y+=d,f
I thought that if you can create variables like this x,y=d,f it would also work
I was sure evaluation order is very specifically defined in c++, but it's just a huge chart that takes almost a page, of a normal sized manual, with about two pages worth of footnotes.
(This is not me being a c++ apologist, this is me being pedantic.)
now thats epic
wait no
it should be "there is a mistake in your code... have fun finding it!!!"
I like ? more, it reminds me of ed(1) :D
Idk about c++ but versions of the c standard definitely don't define it
True and false swapped
indexing starts at 2
implicit multiplication between floats and integers with brackets
swapping \ and /
only walrus for assignment, == is replaced with :==
all global variables
close and open paren and braces reversed
precedence is reversed```
that's what i got so far
undefined names are treated as the name as a string (very useful for accidentally creating bugs)
explain
making my own python language... with python
It’s a random text encoding
It would be a major source of bugs for people trying to use your fake Python
what is random text encoding
i like the term fake python
I googled a list of text encodings and picked a random one
The idea is that people won’t be able to write or read from files easily
For everyone who hasn't googled this yet: https://en.wikipedia.org/wiki/Big5
Big-5 or Big5 is a Chinese character encoding method used in Taiwan, Hong Kong, and Macau for traditional Chinese characters.
The People's Republic of China (PRC), which uses simplified Chinese characters, uses the GB 18030 character set instead.
Big5 gets its name from the consortium of five companies in Taiwan that developed it.
epic
issue is
taiwan doesn't exist
how will i get my language to china
it wont be xi jing ping approved
hello
You could turn the dictionary into two long strings, split them by some character, zip them together, then use dict on the result, which would save on quote marks.
dict(zip("Alabama-Alaska".split("-"),"AL-AK".split("-")))
You'd have to fix the "of" in "District of Columbia", but it could also be shorter to only write the names, and store the acronym using capitalisation e.g. "ALabama". Then you could extract all the uppercase letters to be the acronym, and recapitalise the name with .title().
print>>open(*"ww"),"Python"
Writes Python to a file called "w"
I need a pop filter
Graph: https://www.desmos.com/calculator/l1zv3va9gh
Music: https://youtu.be/2MtOpB5LlUA
#Desmos #DesmosGraphingCalculator
This what I mean
C++ sees your non-apology and raises you a pedant
!e
def nginx():
location / {
rеturn: 400
}
@formal sandal :warning: Your eval job has completed with return code 0.
[No output]
how would I do this?
I have the string with the names capitalised but now im not sure how to match it to the input
"ALabama-AlasKa-AriZona-ARkansas-CAlifornia-COlorado-ConnecTicut-DElaware-District of Columbia-FLorida-GeorgiA-HawaiI-IDaho-ILlinois-INdiana-IowA-KansaS-KentuckY-LouisianA-MainE-MarylanD-MAssachusetts-MIchigan-MiNnesota-MiSsissippi-MissOuri-MonTana-NEbraska-NeVada-New Hampshire-New Jersey-New Mexico-New York-North Carolina-North Dakota-OHio-OKlahoma-ORegon-PennsylvaniA-Rhode Island-South Carolina-South Dakota-TeNnessee-TeXas-UTah-VermonT-VirginiA-WAshington-West Virginia-WIsconsin-WYoming".split("-")```
it gives me a list but idk how to work it
does this still work
!e ```py
helloworld=(lambda ,__,:(lambda:[*map(lambda :(()),[*[::2],*__[1::2]])]))(import("sys").stdout.write,[72,87,101,111,108,114,108,108,111,100,44,33,32,10],chr)
helloworld()```
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Hello, World!
print("Hello World!")
but that's boring
oh here's another good one I remember this
!e ```py
mp = {'Alabama':'AL','Alaska':'AK','Arizona':'AZ','Arkansas':'AR','California':'CA','Colorado':'CO','Connecticut':'CT','Delaware':'DE','District of Columbia':'DC','Florida':'FL','Georgia':'GA','Hawaii':'HI','Idaho':'ID','Illinois':'IL','Indiana':'IN','Iowa':'IA','Kansas':'KS','Kentucky':'KY','Louisiana':'LA','Maine':'ME','Maryland':'MD','Massachusetts':'MA','Michigan':'MI','Minnesota':'MN','Mississippi':'MS','Missouri':'MO','Montana':'MT','Nebraska':'NE','Nevada':'NV','New Hampshire':'NH','New Jersey':'NJ','New Mexico':'NM','New York':'NY','North Carolina':'NC','North Dakota':'ND','Ohio':'OH','Oklahoma':'OK','Oregon':'OR','Pennsylvania':'PA','Rhode Island':'RI','South Carolina':'SC','South Dakota':'SD','Tennessee':'TN','Texas':'TX','Utah':'UT','Vermont':'VT','Virginia':'VA','Washington':'WA','West Virginia':'WV','Wisconsin':'WI','Wyoming':'WY'}
hash = lambda s:sum(ord(c)*i for i,c in enumerate(s))
def collapseinner(l):
i = 0
for v in l:
if v == 0:
i+=1
else:
if i:
yield str(i)
i = 0
yield v
def collapse(l):
return ' '.join(collapseinner(l))
def find(mp, e=2000):
lowest = None
for i in range(1, e):
if len(set(hash(k)%i for k in mp))==len(mp):
_mp = {hash(k)%i:v for k,v in mp.items()}
m = min(_mp)
_mp = {hash(k)%i-m:v for k,v in mp.items()}
l = [0] * (max(_mp) + 1)
for k in _mp:
l[k] = _mp[k]
if lowest is None or lowest[-1] > len(collapse(l)):
lowest = [i, m, _mp, len(collapse(l))]
return lowest[:3]
def compile(mp):
import inspect
i, m, _mp = find(mp)
l = [0] * (max(_mp) + 1)
for k in _mp:
l[k] = _mp[k]
s = collapse(l)
hsrc = 'sum(ord(c)*i for i,c in enumerate(s))'
return f'lambda s:sum(([v]*int(v)if v.isdigit()else[v]for v in {s!r}.split()),[])[{hsrc}%{i}-{m}]'
print(compile(mp))
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
lambda s:sum(([v]*int(v)if v.isdigit()else[v]for v in 'NJ 2 ME 6 AK 1 ID 5 ND 2 HI 2 SD 3 VT 5 MN KY 3 WA 2 MO 6 AL 4 TX 13 NH OR 2 MI 2 KS 1 WI 5 IN 4 OK 2 VA 1 NE CT 1 UT NC 5 SC 8 FL 1 IA 6 OH GA 5 NM 1 DE 4 MD CA MT 9 PA CO 3 MS 6 WV 4 DC 10 LA 5 MA 9 AR 4 WY 7 AZ NY 6 RI 6 NV 17 TN 1 IL'.split()),[])[sum(ord(c)*i for i,c in enumerate(s))%256-14]
!e py l = lambda s:sum(([v]*int(v)if v.isdigit()else[v]for v in 'NJ 2 ME 6 AK 1 ID 5 ND 2 HI 2 SD 3 VT 5 MN KY 3 WA 2 MO 6 AL 4 TX 13 NH OR 2 MI 2 KS 1 WI 5 IN 4 OK 2 VA 1 NE CT 1 UT NC 5 SC 8 FL 1 IA 6 OH GA 5 NM 1 DE 4 MD CA MT 9 PA CO 3 MS 6 WV 4 DC 10 LA 5 MA 9 AR 4 WY 7 AZ NY 6 RI 6 NV 17 TN 1 IL'.split()),[])[sum(ord(c)*i for i,c in enumerate(s))%256-14] print(l('Alabama'))
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
AL
@snow beacon built an arbitrary dict compressor for str keys and values
could be smaller with a specialized hash function
(cant use the builtin hash because it isnt constant across startups)
how does this work?
it expands the big string into a list, numbers are dead space. then it calculates an index with s (modulo 256, minus 14)
so if its expanding and it sees a 7, it expands that into 7 slots that are unused
What's going on here?
and return has a special e char
An esoteric programming language (sometimes shortened to esolang) is a programming language designed to test the boundaries of computer programming language design, as a proof of concept, as software art, as a hacking interface to another language (particularly functional programming or procedural programming languages), or as a joke. The use o...
this is fire
esolang is now my new hobby
xD
@sick hound then you will enjoy https://esolangs.org/wiki/Main_Page
that is really cool
right so I want to recreate python in python (as closely as possible) and then make it really esoteric and upside down
started with something like that once (but didn't get to making it esoteric): https://github.com/L3viathan/nohtyp
True and false swapped, open and closed paren, braces and curly braces swapped, association and precedence swapped
etc.
that link brings a 404 error
sadly
oh, it was private. fixed
i like the description, "forgive me father, for I have sinned"
it's not the worst sin I've committed (heh) to be honest
if you think you are a real python sinner with that code then you will be asking the admins to give me a sea of holy water to bathe in
import SevenEyedLambda
tnirp)"olleh"(```
normally would be py print("hello")
backwards string reading
now imagine writing entire programs in that code
IMAGINE WRITING ESOTERIC CODE WITH MY ESOTERIC LANGUAGE
sorry for the caps but this is epic
im reading craftinginterpreters right now and soon I will understand language dev and begin building my python replica
any way to golf this further?
for j in range(51):
x=sum(map(int,bin(j)[2:]))
if [i for i in range(1,x)if x%i<1]==[1]:print(j)```
like this
for i in range(5):
print("hello world")```
better then py for i in range(5): print("hello world")
1 space instead of a tab
print(*(filter(lambda x:bin(x).count("1")!=1,range(1,51))),sep="\n")
print(*(x for x in range(1,51)if bin(x).count("1")>1),sep="\n"), 62 bytes
theres no difference
If using literal tabs, correct. If using four spaces, there is.
im using tabs
I guess Discord auto-expands
yeah it does
these also dont work
!e they do?
print(*(x for x in range(1,51)if bin(x).count("1")>1),sep="\n")
@restive void :white_check_mark: Your eval job has completed with return code 0.
001 | 3
002 | 5
003 | 6
004 | 7
005 | 9
006 | 10
007 | 11
008 | 12
009 | 13
010 | 14
011 | 15
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/avagarovis.txt?noredirect
Oh, I misinterpreted what the original code does, then
adds the digits of the binary expansionn of every nnumber from 0-50 and prinnts them if theyre prime
got it to 93
for j in range(51):
x=bin(j)[2:].count("1")
if[i for i in range(1,x)if x%i<1]==[1]:print(j)```
89 sinnce i dont need the [2:] anymore
print(*(x for x in range(1,51)if bin(x).count("1")in[2,3,5]),sep="\n"), 69
right, that exists. print(*(x for x in range(1,51)if x.bit_count()in[2,3,5]),sep="\n"), 65
some people can do that in 40 bytes wtf man 😭
If you want to get it down further, post it on codegolf.stackexchange.com :D
its so fun slowly figuring it out sometimes though
like this one here that frownyfrog helpped me with https://code.golf/divisors#python
got it to 55 bytes
back to multiline:
for x in range(51):
if x.bit_count()in[2,3,5]:print(x)
back to single line: for x in range(51):x.bit_count()in[2,3,5]and print(x), 53
what how does that work
and is lazy: it doesn't evaluate the second half unless the first half is truthy
anyone have any idea how to reduce either of these 2?
[print(i)for i in range(51)if~i.bit_count()&1]
[print(i)for i in range(51)if i.bit_count()&1]
Nope, map(print,filter(lambda i:i.bit_count()&1,range(51))) is much longer.
So is, map(lambda i:print(i) if i.bit_count()&1 else 0,range(51)
theres a way to remove 6 bytes from both butit already looks so compact
If you're going to do both, you can define p=print and b=lambda i:i.bit_count()&1 before hand, but that barely saves anything.
kk.
@sick hound :warning: Your eval job has completed with return code 0.
[No output]
the smallest c quine is also the smallest python quine
nice
why does pip return an error when downloading the url package in windows 10
the empty file is typically not counted as a quine :P
had a problem, probably because the devs forgot to include it in the apt
it's a "cheating Quine"
I see the "Golf you a quine for great good" rules as canonical: https://codegolf.stackexchange.com/questions/69/golf-you-a-quine-for-great-good
cheating quines are quines that read its own source code not compute it
@restive void also what do you think about this?
What is it doing? I have to think about ascii offsets, ord(i) is 105?
ihspj?
Don't understand how that's supposed to work
oh, nevermind, I skipped something :)
I have another cheaty quine, but it might not work for you without modification:
File "/Users/l3viathan/scratch/quine.py", line 1
File "/Users/l3viathan/scratch/quine.py", line 1
IndentationError: unexpected indent
!e
def do_thing(divide):
x = divide(11, 2)
y = divide(61, 11)
for _ in range(100):
z = 111 - divide(1130 - divide(3000, x), y)
x = y
y = z
return float(x)
from fractions import Fraction
from operator import truediv
print("oh", do_thing(truediv))
print("no", do_thing(Fraction))
@restive void :white_check_mark: Your eval job has completed with return code 0.
001 | oh 100.0
002 | no 5.999999987925326
we have for else, but why not for elif
like rare use case but its weird that it doesn't exist but for else does
if we need an example
for pre in meta_prefixes:
if msg.startswith(pre):
msg = msg.premoveprefix(pre).lstrip()
break
elif not (msg.reference and msg.reference.id == bot.user.id):
return
Also, why not this syntax?
import system from os
it lets you actually chain together imports but allows renaming
Because it breaks auto-completion
im sure theres a way to set it up
probably to make the grammar simpler tbh
like the alternate options would always be seperate, so import s would prompt sys before system from os
but this makes things simplier
the grammar is more complex
as you now have an extra epsilon rule
which is always a pita
I don't understand the advantage you claim?
say you only use subprocess and time.time()
just do
import time from time, subprocess
What do you mean by chaining together imports?
rather than
import subprocess
from time import time```
which is uglier
Disagree
currently, imports look like
<import> ::= import <id>
| from <id> import <id>
``` (slightly simplified, relative imports exist)
if your proposal, you now get a potentially empty tail
which is annoying to deal with in an LL grammar
with the new parser it would be fine
import time from time, subprocess is parsed by my brain as from time, subprocess import time
wait a sec
wait ur right
wait
wait no
QED
wait
you are
import subprocess, time from time is ambigious
nvm forget all i said
except for this
k
why
how often does this construct come up
and for-else is already confusing enough for beginners, now you want to add an elif too?
given that for-else exists it makes less sense that for-elif doesn't exist
beginners don't even see this type of thing anyway as its used rarely, why not make it function as one would expected
haha, but shouldn't elif be a second for loop?
has this been fully dropped as of yet?
I suppose it's possible some language features (e.g. pattern matching) aren't being used in the stdlib yet if there's still some tooling that's yet to catch up
!e
_=()==()
__=(_+_)+(_+_)
___=((_+_)+(_+_)+(_+_)+(_+_)*(_+_)+(_+_)+(_+_)+(_+_))
____="%c"*(_+_+_+_+_)%(((_+_)*((___*__+(__+__))//(_+_))),((_)*((___*__+(__+__)-(_+_+_)))),((_+_)*((___*__+(__+__)+(__))//(_+_))),((_+_)*((___*__+(__+__)+(__))//(_+_))),((_)*((___*__+(__+__)+(__+_+_+_)))))+" "+"%c"*(_+_+_+_+_)%(((_)*((___*__+(__+__)+(__+__+__+_+_+_)))),((_)*((___*__+(__+__)+(__)+(_+_+_)))),((_+_)*((___*__+(__+__)+(__)+(_+_+_)+(_+_+_))//(_+_))),((_+_)*((___*__+(__+__)+(__))//(_+_))),((_+_)*((___*__+(__+__)-(__))//(_+_))))
print(____)
@fossil estuary :white_check_mark: Your eval job has completed with return code 0.
HELLO WORLD
nice
I coded this in about 2 mins, thought it would be interesting to put it against a typing test
typing bot i guess
How badly am I violating PEP8 if I have a 301 char condition?
(utils.move(tx[t],ty[t],tx[t]+dx,ty[t]+dy) and board[tx[t]+dx][ty[t]+dy]==' ')or(utils.move(tx[t],ty[t],tx[t]+dx,ty[t]+dy) and utils.move(tx[t]+dx*2,ty[t]+dy*2,tx[t]+dx,ty[t]+dy) and board[tx[t]+dx][ty[t]+dy]=='S' and board[tx[t]+dx*2][ty[t]+dy*2]==' ')
For a pet project
It is documented though
honestly if you add some spacing and newlines your fine
You have at least 4 unnecessary spaces there smh
(the ands)
nicely cursed
i don't know if that's against the rules specifically
it probably should wrap at 79 chars, though
How it is printing Hello world?
strange
the %c is the only letter there, lol
very convoluted process, evidently

going from True to the character code is my guess
how is True + True == 2, is what I'd like to know
and True + False == 1
Because issubclass(bool, int)
HIstorically, Python didn't even have True and False and just used 1 and 0 in their place
!e
# C++.py
import sys
class iostream:
def __lshift__(self, other):
sys.stdout.write(other);
return self;
def __rshift__(self, other):
other.write(sys.stdin.readline());
cin = cout = iostream();
endl = "\n";
...
cout << "Hello World!" << endl;
@restive void :white_check_mark: Your eval job has completed with return code 0.
Hello World!
love it
!e
print("%c"*(1)%(67))
@rich hound :white_check_mark: Your eval job has completed with return code 0.
C
like that
oh, by ASCII
a more complicated way of chr(67)
!e
exec('%c'*10%(((((((([]==[]))*(([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[])))*(([]==[])+([]==[])))*(([]==[])+([]==[])))*(([]==[])+([]==[])),((((((([]==[]))*(([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[])))*(([]==[])+([]==[])))*(([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[])),((((((([]==[]))*(([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[])))*(([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[])))*(([]==[])+([]==[])))*(([]==[])+([]==[]))+([]==[]),((((((([]==[]))*(([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[])))*(([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[])),((((((([]==[]))*(([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[])))*(([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[])))*(([]==[])+([]==[])),(((((([]==[])+([]==[])))*(([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[])))*(([]==[])+([]==[])))*(([]==[])+([]==[])),(((((([]==[])+([]==[])))*(([]==[])+([]==[])))*(([]==[])+([]==[])))*(([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[])),((((((([]==[]))*(([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[])))*(([]==[])+([]==[])))*(([]==[])+([]==[])))*(([]==[])+([]==[])))*(([]==[])+([]==[]))+([]==[]),(((((([]==[])+([]==[])))*(([]==[])+([]==[])))*(([]==[])+([]==[])))*(([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[])),(((((([]==[])+([]==[])))*(([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[])))*(([]==[])+([]==[])))*(([]==[])+([]==[]))+([]==[]),))
@rich hound :white_check_mark: Your eval job has completed with return code 0.
a
a.
True + True = 2
[print(i)for i in range(201)if sum(j for j in range(2,i)if i%j<1)>i]```
how can I golf this further
OMG
!e
def get_power_of_2(n: int) -> int:
assert n
cnt = 0
while n % 2 == 0:
cnt += 1
n //= 2
return cnt
def int2esoteric(n: int) -> str:
if n == 0:
return '()==[]'
if n == 1:
return '[]==[]'
if n == 2:
return f'({int2esoteric(1)})+({int2esoteric(1)})'
if get_power_of_2(n) == 0:
return f'({int2esoteric(n - 1)})+({int2esoteric(1)})'
if get_power_of_2(n) == 1:
return f'({int2esoteric(n // 2**get_power_of_2(n))})*({int2esoteric(2)})'
if get_power_of_2(n) == 2:
return (
f'({int2esoteric(n // 2**get_power_of_2(n))})*({int2esoteric(2)})*({int2esoteric(2)})'
)
else:
return f'({int2esoteric(n // 2**get_power_of_2(n))})*({int2esoteric(2)})**({int2esoteric(get_power_of_2(n))})'
for i in range(100):
res = int2esoteric(i)
print(f'f({i}) == {res}')
# print(f'{len(str(i))} -> {len(res)}')
assert eval(res) == i
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
001 | f(0) == ()==[]
002 | f(1) == []==[]
003 | f(2) == ([]==[])+([]==[])
004 | f(3) == (([]==[])+([]==[]))+([]==[])
005 | f(4) == ([]==[])*(([]==[])+([]==[]))**(([]==[])+([]==[]))
006 | f(5) == (([]==[])*(([]==[])+([]==[]))**(([]==[])+([]==[])))+([]==[])
007 | f(6) == ((([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[]))**([]==[])
008 | f(7) == (((([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[]))**([]==[]))+([]==[])
009 | f(8) == ([]==[])*(([]==[])+([]==[]))**((([]==[])+([]==[]))+([]==[]))
010 | f(9) == (([]==[])*(([]==[])+([]==[]))**((([]==[])+([]==[]))+([]==[])))+([]==[])
011 | f(10) == ((([]==[])*(([]==[])+([]==[]))**(([]==[])+([]==[])))+([]==[]))*(([]==[])+([]==[]))**([]==[])
... (truncated - too many lines)
Full output: too long to upload
Is this where I come for python help?
When I run my code it does not want to print anything out and I do not recieve an error message. My "for line in count_files" Doesnt seem to work either.
def countLines(file_name):
get_count = 0
count_file = open(file_name, "r")
for line in count_file:
get_count += 1
count_file.close()
return get_count
#
def appendFile(file_name, original_count):
write_data = open(file_name, "a")
write_data.write(f"{file_name} had {original_count} lines of data, and now has {original_count + 1}\r")
write_data.close()
return
#
def confirmAppend(file_name):
print_file = open(file_name, "r")
for line in print_file:
print(line)
print_file.close()
return
def appendToTen():
update_counter = 0
file_name = "create_this_file.txt"
while update_counter < 9:
update_counter = countLines(file_name)
appendFile(file_name, update_counter)
confirmAppend(file_name)
return
Im going to send another code as It might help.
def createFile(file_name):
create_new = open(file_name)
create_new.close()
return
#
def writeData(file_name):
write_data = open(file_name,"wt")
write_data.write("Steps to file management:")
write_data.write("\n\t1: Open a file.\r")
write_data.write("\t2: Read or write data.\r")
write_data.write("\t3: Close the file.\r")
write_data.close()
return
#
def printData(file_name):
print_file = open(file_name,"r")
for line in print_file:
print(line)
print_file.close()
return
#
def main():
file_name = "create_this_file.txt"
createFile(file_name)
writeData(file_name)
printData(file_name)
return
main()
This one I worked on yesterday
my god
that is
jsf*ck but in python
+([]==[]) abuse
!e
print(eval('-~' * 100 + '0'))
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
100
i was making an example.
wait how
i mean i was wondering if something like this could be done
you got print() there too ?
print random garbage cryptic bs
crude solution
for i in range(200):
randomlist =[]
st =""
for i in range(30):
if random.randrange(4) == 1:
for i in range(random.randrange(4)):
randomlist.append(str(random.randrange(10)))
for i in range(random.randrange(4)):
randomlist.append(chr(random.randrange(10000)))
print(st.join(randomlist))```
also code vore
what is the shortest piece of code (in bytes) that violates every pep8 convention
no empty files xd
Random-case and no spaces around expressions
And no lines with only a newline character
yes but it wouldn't break many rules
I don't remember all by heart
guys where should i put this code to generate a Json view in my terminal ? (in a django project) import json datas = [{'title':'a cool title','artist':'john doe','year':2020},{'title':'a second music print(json.dumps(datas, indent=4))
how do I remove a char from this py for i in range(100):print(i%3//2*'Fizz'+i%5//4*'Buzz'or-~i)
!e
TIL: you can implement reduce with sum
class Accumulator:
def __init__(self, acc, func):
self.acc = acc
self.func = func
def __add__(self, new_item):
return Accumulator(self.func(self.acc, new_item), self.func)
def reduce(func, initial, iterable):
return sum(iterable, start=Accumulator(initial, func)).acc
print(reduce(lambda x, y: x * y, 1, [3, 6, 3, 5, 9, 1, 2]))
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
4860
!e
a = 2
while True:
print(a)
a = a ** a
@fleet bridge :x: Your eval job timed out or ran out of memory.
001 | 2
002 | 4
003 | 256
004 | 32317006071311007300714876688669951960444102669715484032130345427524655138867890893197201411522913463688717960921898019494119559150490921095088152386448283120630877367300996091750197750389652106796057638384067568276792218642619756161838094338476170470581645852036305042887575891541065808607552399123930385521914333389668342420684974786564569494856176035326322058077805659331026192708460314150258592864177116725943603718461857357598351152301645904403697613233287231227125684710820209725157101726931323469678542580656697935045997268352998638215525166389437335543602135433229604645318478604952148193555853611059596230656
!e
a = 1.1
while True:
print(a)
a = a ** a
@drifting oar :x: Your eval job has completed with return code 1.
001 | 1.1
002 | 1.1105342410545758
003 | 1.123478572104428
004 | 1.1397470115213453
005 | 1.1607729391766661
006 | 1.1889316398153298
007 | 1.228446926563767
008 | 1.2875662745568726
009 | 1.3846360207549393
010 | 1.5692726219691349
011 | 2.028168989455779
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/eyahufakof.txt?noredirect
!e
a = 1.01
while True:
print(a)
a = a ** a
@drifting oar :x: Your eval job has completed with return code 1.
001 | 1.01
002 | 1.0101005033417416
003 | 1.0102030422152326
004 | 1.0103076789863008
005 | 1.0104144785914753
006 | 1.0105235086716804
007 | 1.010634839714353
008 | 1.0107485452046099
009 | 1.010864701786143
010 | 1.0109833894325797
011 | 1.011104691630113
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/nehewikihe.txt?noredirect
!e
a = 1.001
while True:
print(a)
a = a ** a
@drifting oar :x: Your eval job has completed with return code 1.
001 | 1.001
002 | 1.0010010005003334
003 | 1.001002003004172
004 | 1.001003007517539
005 | 1.0010040140464815
006 | 1.0010050225970712
007 | 1.0010060331754038
008 | 1.0010070457876
009 | 1.0010080604398044
010 | 1.0010090771381874
011 | 1.0010100958889436
... (truncated - too many lines)
Full output: too long to upload
lol
!e
_ = None
class _:
_ = None
def __init__(self, *, _=None):
self._ = _
def _(self, *, _=None):
self._ = _
_ = _()
_._ = _
_(_)._ = _
@drifting oar :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 11, in <module>
003 | TypeError: '_' object is not callable
!e
_print = print
class print:
def __init__(self):
pass
def __getattribute__(self, name):
_print(name, end='')
return print()
print().h.e.l.l.o.w.o.r.l.d
@drifting oar :white_check_mark: Your eval job has completed with return code 0.
helloworld
!e
_print = print
class print:
def __init__(self):
pass
def __getattribute__(self, name):
if name[0] == '_' == name[-1]:
_print(chr(int(name.replace('_', ''))), end='')
else:
_print(name, end='')
return print()
print().h.e.l.l.o._10_.w.o.r.l.d
@drifting oar :white_check_mark: Your eval job has completed with return code 0.
001 | hello
002 | world
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Hello, World!
gj
Is there any way to deduplicate a line like this where the only change is max vs min?
def d3p1(r):
return int(''.join([max(set(e),key=e.count)for e in[([_[e]for _ in r])for e in range(len(r[0]))]]),2)*\
int(''.join([min(set(e),key=e.count)for e in[([_[e]for _ in r])for e in range(len(r[0]))]]),2)
(lambda _: _[0]*_[1])([(your long expression with `f`) for f in (min, max)])
this counts as esoteric, right?
Posting pictures of code? Yes, pretty esoteric.
!e
print(chr(((int()**int()+int()**int())**(int()**int()+int()**int())**(int()**int()+int()**int()))*((int()**int()+int()**int())**(int()**int()+int()**int())+int()**int())-((int()**int()+int()**int())**(int()**int()+int()**int()))*(int()**int()+int()**int()))+chr(((int()**int()+int()**int())**(int()**int()+int()**int())**(int()**int()+int()**int()))*((int()**int()+int()**int())**(int()**int()+int()**int())+int()**int()+int()**int())+(int()**int()+int()**int())**(int()**int()+int()**int())+int()**int())+chr(((int()**int()+int()**int())**(int()**int()+int()**int())**(int()**int()+int()**int()))*((int()**int()+int()**int())**(int()**int()+int()**int())+int()**int()+int()**int())+(int()**int()+int()**int())**(int()**int()+int()**int())+(int()**int()+int()**int())**(int()**int()+int()**int())*(int()**int()+int()**int()))+chr(((int()**int()+int()**int())**(int()**int()+int()**int())**(int()**int()+int()**int()))*((int()**int()+int()**int())**(int()**int()+int()**int())+int()**int()+int()**int())+(int()**int()+int()**int())**(int()**int()+int()**int())+(int()**int()+int()**int())**(int()**int()+int()**int())*(int()**int()+int()**int()))+chr(int(((int()**int()+int()**int())**(int()**int()+int()**int())**(int()**int()+int()**int()+int()**int()))/(int()**int()+int()**int())-int()**int())-(int()**int()<<(int()**int()+int()**int())**(int()**int()+int()**int()))))
@alpine peak :white_check_mark: Your eval job has completed with return code 0.
Hello
Hey @grave rover!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
heck
i don't think 0^0 is 1 mathematically, but i guess python doesn't care lol
x^0 = 1 is usually defined to include x=0
Hacky code challenge 1: Write a one liner to convert an integer number to a list of int digits without using map.
Challenge 2: Same question but now the restriction is on str, not on map.
Format:```py
n = 19238 # Can be any number
A single liner below
...```
n = 19238
list_of_ints = [int(s) for s in str(n)]
``` something like this?
second solution is also just py n = 19238 list_of_ints = [int(s) for s in repr(n)]
Nice!
Now you want challenge 3?
Challenge 3: Same question but now the restriction is neither on str nor on map, but on int.
should still be easy 😄
Only challenge 4 will be challenging 😉
hmm
im not quiet sure tbh
list_of_nums = [eval(n) for n in str(n)]```
this might work
Excellent!
Alternately you can also do this
!e
n = 21425
print([type(0)(n) for n in str(n)])```
@haughty nova :white_check_mark: Your eval job has completed with return code 0.
[2, 1, 4, 2, 5]
nice one
So you want the final challenge?
sure
It will still be easy
Only restriction is now
that you can't use any of the inbuilt functions
other than print of course
good thing int() isnt a function
True 🤔
Then how should I put it
ok, current restrictions: Calling any of these Callables: int, str, type.
it has to be in one line?
hm
Just see your previous answer, you already have it actually
print([(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10))-1, -1, -1)])
wow, I was just expecting eval and repr
print([eval(x) for x in repr(n)])```
exactly, gj dude
=)))
I will come with more challenges later, won't be as easy as this time 😉
cool
!e
n = 31415926535
print([0 .__class__(i) for i in n.__str__()])
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
@haughty nova
!e print(1.0//1)
@grave rover :white_check_mark: Your eval job has completed with return code 0.
1.0
@grave rover :white_check_mark: Your eval job has completed with return code 0.
[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
been trying to figure out how to eliminate int and range here
if we can replace range, int can just become //1
or if there's a way to floor floats to ints without using functions
here's a basic range function py (lambda n,a=[-1]:((lambda:a.__setitem__(0,a[0]+1) or a[0])()for _ in [0]*n)) but it still requires n to be an int (and it also uses __setitem__ I guess)
Is there any way I can golf a block like this more? (variable names and whitespace for clarity)
Where other_stuff(my_list) will pop an unpredictable number of elements in unpredictable order from my_list but will always converge to end with only 2 elements
def my_function(my_list, index = 0):
while len(my_list) > 2:
my_list = other_stuff(my_list)
index += 1
💯
I was expecting for someone to pick up on calling str and int like that for the next time I asked this with both str and repr restriction.
I mean if that's allowed, then here's a fun one:
!e py n = 31415926535 print([(n//10**j)%10for j in(lambda n,a=[-1]:((lambda:a.__setitem__(0,a[0]+1)or a[0])()for _ in [0]*n))((n**0.1+0.5).__int__())][::-1])
@grave rover :white_check_mark: Your eval job has completed with return code 0.
[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
awesome man
You want the hardest restriction I have come up with?
sure
No function calls
None
No Callable calls, to be specific
Basically no
(Callable or expression which gets a Callable)(*args)
Only print is allowed
Anything else is fair game
If you can do this, I will salute
does it still need to be a one-liner?
Yep
!e ```py
n = 31415926535
a = []
while n>0:a[:],n=[n%10]+a[:],n//10
print(a)
@grave rover :white_check_mark: Your eval job has completed with return code 0.
[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
n = 19238 # Can be any number
# A single liner below
...```
does that one count

i don't think it includes 0
iirc a^0 is defined as a^(n - n) = a^n/a^n (n being positive)
but the denominator doesn't make sense in case of 0
in python it's defined that 0^0 = 0 since the smallest amount a number can be stored in is 1 bit and when doing 0^0 with one bit the result is 0
@fair vigil :white_check_mark: Your eval job has completed with return code 0.
1
oh we were talking pow
oh yeah
I thought you meant xor
nope
yeah n**0 = 1
even in math that's a fact, not sure what @sick hound was going on about
isn't there a proof like
0^0 = (a - a)^(n - n) = ((a-a)^n)/((a-a)^n) = 1
x^x also approaches 1 when x approaches 0
isn;t it also required for stuff like combinatorics
just swap the 1st newline for a semicolon
zero can be stored in zero bits
0^0 is generally defined as 1 in most cases where it's relevant, ie., notationally when x^n is required to range over a domain including 0, 0^0 is taken as 1
many mathematical theorems require it, as-stated, eg., the binomial theorem
!e
2+type('',(),{'__getattr__':lambda*_:print(_)})()
why does this error?
@golden finch :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: unsupported operand type(s) for +: 'int' and ''
(esoteric uses obviously)
2 + type(...)
2 + x is type(2).__add__(x), which is int.__(2, x)
!e
print( 2 + type('', (int,), dict())() )
@unique rose :white_check_mark: Your eval job has completed with return code 0.
2
I'm aware of that. Why isn't the getattr method of this type being called with arguments (anonymous class instance, '__add__')?
why would int.__add__ call __getattr__ ?
int.__add__ is a monomorphic addition function, ie., it is specialised to just adding integers
you can do something similar the other way around,
!e ```py
type('', tuple(), {'add': print})() + 2
@unique rose :white_check_mark: Your eval job has completed with return code 0.
2
Shouldn't it check if the custom type implements __radd__ and this requires getting an attr?
>>> 2+type('',(),{'__radd__':lambda self,other:'foo'})()
'foo'
i.e
i think the logic around these methods is to test the underlying PyObject itself for their presence, not to look them up via getattr
that was my original answer, but i couldnt confirm it was using a slots mechanism.. but its a "neat" general principle -- slots avoid polymorphic lookups
!e
def c(n):
while n > 0:
yield n
n -= 1
for i in c(10): print(['']*(10-i)+list(c(i)))
@maiden river :white_check_mark: Your eval job has completed with return code 0.
001 | [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
002 | ['', 9, 8, 7, 6, 5, 4, 3, 2, 1]
003 | ['', '', 8, 7, 6, 5, 4, 3, 2, 1]
004 | ['', '', '', 7, 6, 5, 4, 3, 2, 1]
005 | ['', '', '', '', 6, 5, 4, 3, 2, 1]
006 | ['', '', '', '', '', 5, 4, 3, 2, 1]
007 | ['', '', '', '', '', '', 4, 3, 2, 1]
008 | ['', '', '', '', '', '', '', 3, 2, 1]
009 | ['', '', '', '', '', '', '', '', 2, 1]
010 | ['', '', '', '', '', '', '', '', '', 1]
open the curtains
Hey mate, I really appreciate the help but I've been struggling with this one. I don't understand it. Could you please break it down for me or expand it out a bit or something?
Ahhh okay, that makes more sense, thank you! I haven't quite got an intuitive understanding of walrus yet but that helps
oh yeah, I've read up on it and "understand it" but don't have the intuitive understanding yet
(obj.__setitem__(index, value), obj[index])[1]
(setattr(obj, attr, value), getattr(obj, attr))[1]
yes, your version is better
it does
thinking of making a python object that "steals" methods
s=type('sneaky',(),{...})()
>>> 3+s
6
>>> 4*s
16
>>> 5**s
3125
>>> 'abc'+s
'abcabc'
etc
this was my attempted solution
>>> s + s
*BOOM*
@sick hound :white_check_mark: Your eval job has completed with return code 0.
*BOOM*
ok)
but it isnt actually stealing methods
if s is sneaky object, s@s should raise RecursionError (@ - any binary operator)
I didn't even consider that case tbh
also what unary operators should do?
!eval```python
print(chr(sum([+([]==[]) for k in range(72)]))+chr(sum([+([]==[]) for k in range(69)]))+2*chr(sum([+([]==[]) for k in range(76)]))+chr(sum([+([]==[]) for k in range(79)]))+' '+chr(sum([+([]==[]) for k in range(87)]))+chr(sum([+([]==[]) for k in range(79)]))+chr(sum([+([]==[]) for k in range(65+17)]))+chr(sum([+([]==[]) for k in range(76)]))+chr(sum([+([]==[]) for k in range(68)])))
It doesnt run it
Why
It ran for first time
!epy print(chr(sum([+([]==[]) for k in range(72)]))+chr(sum([+([]==[]) for k in range(69)]))+2*chr(sum([+([]==[]) for k in range(76)]))+chr(sum([+([]==[]) for k in range(79)]))+' '+chr(sum([+([]==[]) for k in range(87)]))+chr(sum([+([]==[]) for k in range(79)]))+chr(sum([+([]==[]) for k in range(65+17)]))+chr(sum([+([]==[]) for k in range(76)]))+chr(sum([+([]==[]) for k in range(68)])))
turns any single a-z character into an underscore message
@dark wharf based of our code
❤️
!e ```py
(lambda self=[:=((([]==[]))+(([]==[]))) ,
:=()*((([]==[]))+(([]==[])))**//__ , :=()** ,
_____:=((())+())**((([]==[]))+(([]==[])))+(([]==[]))+(([]==[]))+(([]==[]))+(([]==[])) ,
________:=(()) , :=(()) , :=(([]==[]))+() , :=(())+ ,
______ := chr(((()))*(((())))**()+()//(())) , [[(()+((()))//()-(())+(()**()**(()))) ,
____________:=()+((()))//()-(())+(()**()**(())) ,
_________________ := ((((((((((((((_________________))))))))))))))+__ , ((),~____)]
for ___ in range() if ((_)) !=[(([]==[]))-()]]][]: eval(type(None).bool.doc))()
import fishhook
@fishhook.hook(int)
def repr(self):
stuff = {v: k for k,v in globals().items() if isinstance(v,int) and k.startswith('')} | {1:''}
x = self
nums = []
for elem in sorted(stuff.keys(),reverse=True):
while x>=elem:
nums.append(stuff[elem])
x-=elem
return ','.join(nums)
MESSAGE = 'PyDis'
slist = []
slist.append(MESSAGE)
x = 0
for i in range(len(MESSAGE)):
print(ord(slist[0][x]))
x += 1```
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | _______________________,_______,_______,_____________
002 | _______________________,____,____,____,_______
003 | _______________________
004 | _______________________,____,____,_______
005 | _______________________,____,____,_______,_______,_______
epic
!e ```py
=chr(int({}=={})*72)+chr(int({}=={})*69)+chr(int({}=={})*76)+chr(int({}=={})*76)+chr(int({}=={})*79)+" "+chr(int({}=={})*87)+chr(int({}=={})*79)+chr(int({}=={})*82)+chr(int({}=={})*76)+chr(int({}=={})*68)
print()
@sick hound :white_check_mark: Your eval job has completed with return code 0.
HELLO WORLD
!e
from timeit import timeit
x = 2001
print(timeit(lambda: f'{x}'))
@gritty anvil :white_check_mark: Your eval job has completed with return code 0.
0.14992528688162565
!e
from timeit import timeit
s = "me"
print(timeit(lambda: f'{s}'))
print(timeit(lambda: '%s' % s))
print(timeit(lambda: '{}'.format(s)))
@gritty anvil :white_check_mark: Your eval job has completed with return code 0.
001 | 0.0623846473172307
002 | 0.09247034601867199
003 | 0.139734101947397
@restive harbor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | ZeroDivisionError: division by zero
!e
import os, sys, threading
def worker():
childpid = os.fork()
if childpid != 0:
os.waitpid(childpid, 0)
else:
def daemon():
while True:
pass
d = threading.Thread(target=daemon)
d.daemon = True
d.start()
w = threading.Thread(target=worker)
w.start()
w.join()
@restive harbor :warning: Your eval job timed out or ran out of memory.
[No output]
@restive harbor :white_check_mark: Your eval job has completed with return code 0.
['Pipfile', 'Pipfile.lock', 'snekbox', 'user_base', 'config', 'tests', 'LICENSE']
@restive harbor :white_check_mark: Your eval job has completed with return code 0.
001 | MIT License
002 |
003 | Copyright (c) 2018 Python Discord
004 |
005 | Permission is hereby granted, free of charge, to any person obtaining a copy
006 | of this software and associated documentation files (the "Software"), to deal
007 | in the Software without restriction, including without limitation the rights
008 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
009 | copies of the Software, and to permit persons to whom the Software is
010 | furnished to do so, subject to the following conditions:
011 |
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/yuhaqeyira.txt?noredirect
!e
import os
print(os.uname())
@restive harbor :white_check_mark: Your eval job has completed with return code 0.
posix.uname_result(sysname='Linux', nodename='snekbox', release='4.19.0-17-cloud-amd64', version='#1 SMP Debian 4.19.194-3 (2021-07-18)', machine='x86_64')
@restive harbor :white_check_mark: Your eval job has completed with return code 0.
32512
!e
while True:
pass
@restive harbor :warning: Your eval job timed out or ran out of memory.
[No output]
@restive harbor please use #bot-commands for testing
@restive harbor :white_check_mark: Your eval job has completed with return code 0.
True
Guys, a real challange - how short, or how confusing can you write an interpreter for Chicken language?
Question is it possible to put two separate for loops in one?
I did something like this
for i in list(range(a)), list(range(b)):
print(i)
out:
[0,1,2...]
[0,1,2...]
Would it be possible to do something with this?
yes, with zip()
I was gonna just do i[x]
for a, b in zip(list(range(10)), list(range(10))):
print(a, b)
its not 2 seperate loops
Woild it be possible to use while opening a file?
wdym
Open two files while iterating through them
for line1,line2 in zip(open("file1"),open("file2")):
the open() function takes more parameters and would need .readlines to get the actual text
nope
open only requires the filename
alr
You don't need to specify 'wr+'?
thats gus to know
anyways, it should work with zip unless it needs to be converted to list type
i dont think zip takes other iterables, maybe just list and string
:)
zip takes any iterable
I'll check it out
It works thats cool
with open(x) as f1, open(y) as f2:
for a,b in zip(f1,f2):
print(a,b)```
wondwr if you can do some more weird stuff with this
how do I check the efficiency of a program? like for the amount of resources used to make the program work
i dont really know by what metric a program is efficient, but it seems like yall know
!e
import builtins
del builtins.int
import pprint
!e
import builtins
builtins.__dict__.clear()
class X: ...
!e
_print = print
import builtins
for k, v in builtins.__dict__.items():
builtins.__dict__[k] = _print
class X: ...
def f(): ...
import a
import a.b
from a.b.c import d, e
@fleet bridge :x: Your eval job has completed with return code 1.
001 | <function X at 0x7f79ca99bd90> X
002 | a Traceback (most recent call last):
003 | File "<string>", line 8, in <module>
004 | io File "<frozen importlib._bootstrap>", line 296, in _module_repr
005 | io File "<frozen importlib._bootstrap>", line 296, in _module_repr
006 | io File "<frozen importlib._bootstrap>", line 296, in _module_repr
007 | io [Previous line repeated 329 more times]
008 | RecursionError: maximum recursion depth exceeded
why?
!e
class X: ...
x = X()
x.a = 0
x._b = 1
x.__c = 2
x.__d__ = 3
print(vars(x))
x.__debug__ = 4 # syntax error
@fleet bridge :x: Your eval job has completed with return code 1.
001 | File "<string>", line 8
002 | SyntaxError: cannot assign to __debug__
why i cant have my own attr called __debug__???
it is only accessible via .__dict__['__debug__']
!e
import builtins as b
print(f'{__debug__ = }')
print(f'{b.__debug__ = }')
b.__dict__['__debug__'] = 'new debug'
print(f'{__debug__ = }')
print(f'{b.__debug__ = }')
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
001 | __debug__ = True
002 | b.__debug__ = True
003 | __debug__ = True
004 | b.__debug__ = 'new debug'
@fleet bridge :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | SyntaxError: cannot assign to __debug__
!eval ```python
print(chr(sum([+([]==[]) for k in range(72)]))+chr(sum([+([]==[]) for k in range(69)]))+2*chr(sum([+([]==[]) for k in range(76)]))+chr(sum([+([]==[]) for k in range(79)]))+' '+chr(sum([+([]==[]) for k in range(87)]))+chr(sum([+([]==[]) for k in range(79)]))+chr(sum([+([]==[]) for k in range(65+17)]))+chr(sum([+([]==[]) for k in range(76)]))+chr(sum([+([]==[]) for k in range(68)])))
@soft gyro :white_check_mark: Your eval job has completed with return code 0.
HELLO WORLD
!e 79 ? why not 7900
print(chr(sum([+([]==[]) for k in range(72)]))+chr(sum([+([]==[]) for k in range(69)]))+2*chr(sum([+([]==[]) for k in range(76)]))+chr(sum([+([]==[]) for k in range(7900)]))+' '+chr(sum([+([]==[]) for k in range(87)]))+chr(sum([+([]==[]) for k in range(79)]))+chr(sum([+([]==[]) for k in range(65+17)]))+chr(sum([+([]==[]) for k in range(76)]))+chr(sum([+([]==[]) for k in range(68)])))
@maiden river :white_check_mark: Your eval job has completed with return code 0.
HELLỜ WORLD
3.10.1 changelog
is this bad ?
nvm, it's only for typing module i guess
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Hello, World!
!e
x='72O101O108O108O111O32O87O111O114O108O100O33';print(''.join([chr(int(x))for x in x.split('O')]))
@maiden river :white_check_mark: Your eval job has completed with return code 0.
Hello World!
Damn
so technically we can write all code using exec('%c'*10% and ()+=-* etc 🙀
do you want to torture yourself? if so, then you can try
this runs the hello world example, so prob other things aswell:
s=[];s+=[s]+['stdin']+[len(l.split())for l in open(0)]
i,j,k,c='s.pop()','s[-2:]=[s[-2]','s+=[',2
while c<len(s):
try:
try:exec(['exit()',f'{k}1]',f'{j}+s[-1]]',f'{j}-s[-1]]',f'{k}{i}*{i}]',f'{k}{i}=={i}]',f'{k}s[s[c+1]][{i}]];c+=1',f'a={i};s[a]={i}',f'o={i};c+=o*({i}>0)',f'{k}chr({i})]'][s[c]])
except:s+=[s[c]-10]
c+=1
except:print(s[-1]);break
not golfed at all, just a quick implementation
'stdin' is just a placeholder since i used the actual stdin to pipe the file, and the "chicken" operator pushes 1 to the stack, not 'chicken'
I wrote a function for gdb to disassemble code objects via dis, if you are debugging something with python (or python itself), just in case anyone's interested
i'm working on one to decompile the code too, but it's not stable enough yet 😄
the function define is messy that's why I posted here
nice
def get_codeobj(gdbval): gdb.set_convenience_variable("arg0", gdbval); gdb.execute("set ($co_code = $_as_string($arg0.co_code), $co_consts = $_as_string($arg0.co_consts), $co_names = $_as_string($arg0.co_names), $co_filename = $_as_string($arg0.co_filename), $co_name = $_as_string($arg0.co_name), $co_names = $_as_string($arg0.co_names), $co_firstlineno = $_as_string($arg0.co_firstlineno), $co_varnames = $_as_string($arg0.co_varnames), $co_argcount = $_as_string($arg0.co_argcount))"); return __import__("types").CodeType(*{'argcount': eval(gdb.convenience_variable("co_argcount").string()), 'posonlyargcount': 0, 'kwonlyargcount': 0, 'nlocals': 0, 'stacksize': 0, 'flags': 0, 'codestring': eval(gdb.convenience_variable("co_code").string()), 'constants': eval(gdb.convenience_variable("co_consts").string()), 'names': eval(gdb.convenience_variable("co_names").string()), 'varnames': eval(gdb.convenience_variable("co_varnames").string()) or eval(gdb.convenience_variable("co_names").string()), 'filename': eval(gdb.convenience_variable("co_filename").string()), 'name': eval(gdb.convenience_variable("co_name").string()), 'firstlineno': eval(gdb.convenience_variable("co_firstlineno").string()), 'lnotab': b""}.values());
then in ~/.gdbunit:
define pcode
p $_python("(__import__(\"dis\").dis(get_codeobj(gdb.convenience_variable(\"arg0\"))), 0)[-1]")
end
oh you need gdbhelpers too
godspeed if anyone actually tries to use it
maybe most eval's in one code in this channel?
!e
(lambda self=[___:=((([]==[]))+(([]==[]))) ,
__:=(___)*((([]==[]))+(([]==[])))**___//___ , ____:=(__)**___ ,
_______________________:=(((__))+(__))**((([]==[]))+(([]==[])))+(([]==[]))+(([]==[]))+(([]==[]))+(([]==[])) ,
_____________:=((___)) , _____________:=((___)) , _______:=(([]==[]))+(___) , _______:=((_______))+_____________ ,
______ := chr((((___)))*((((__))))**(__)+(__)//((___))) , [[((__)+(((___)))//(____)-((___))+((___)**(___)**((_______)))) ,
_________________:=(__)+(((___)))//(____)-((___))+((___)**(___)**((_______))) ,
_________________ := ((((((((((((((_________________))))))))))))))+_______ , ((_________________),~_______________________)]\
for ___ in range(__) if ((_______)) !=[(([]==[]))-(___)]]][___]: eval(type(None).__bool__.__doc__))()
import fishhook
@fishhook.hook(int)
def __repr__(self):
stuff = {v: k for k,v in globals().items() if isinstance(v,int) and k.startswith('_')} | {1:'_'}
x = self
nums = []
for elem in sorted(stuff.keys(),reverse=True):
while x>=elem:
nums.append(stuff[elem])
x-=elem
return ','.join(nums)
MESSAGE = 'Hello python!'
slist = []
slist.append(MESSAGE)
x = 0
for i in range(len(MESSAGE)):
print(ord(slist[0][x]))
x += 1```
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | _______________________,__
002 | _______________________,____,____,_
003 | _______________________,____,____,_______,_____________,_
004 | _______________________,____,____,_______,_____________,_
005 | _______________________,____,____,_______,_______,_
006 | ____,____
007 | _______________________,____,____,_______,_______,_____________
008 | _______________________,____,____,____,_______
009 | _______________________,____,____,____
010 | _______________________,____,____,__
011 | _______________________,____,____,_______,_______,_
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/osevonilup.txt?noredirect
i challenge you to make a program which decodes these underscores into the message
good luck
I'm doing it myself
hello, i have a challenge for you guys 🙂
a couple of years ago i experimented with powertowers ( https://en.wikipedia.org/wiki/Tetration )
In mathematics, tetration (or hyper-4) is an operation based on iterated, or repeated, exponentiation. It is the next hyperoperation after exponentiation, but before pentation. The word was coined by Reuben Louis Goodstein from tetra- (four) and iteration.
Under the definition as repeated exponentiation, the Rudy Rucker notation
...
i was surprised how easy you can get to the limit of computability like 3**3**3**3**3
but here's the question
let's say you still can squeeze the end result in memory, how is it possible to calculate the reverse ("root") of a power tower?
say
def power_squared(target:float, tower_height:int) -> float
with x = power_squared(target, 4); x**x**x**x == target
you're making me want to write some kind of transformer to reverse the logic of a program 😄
go on
im trying to do it myself
MESSAGE = _______________________,__
slist = []
slist.append(MESSAGE)
y = -1
y += 1
slist_num = MESSAGE[y]
x = 0
for i in range(MESSAGE[0]):
print(slist_num)
x += 1``` is what i got rn
once I figure out what power tower means I might try something with it
power tower means stacking powers x**x**x**..
same
seems interesting
I mean since you showed the original algorithm.. I think it's too complex though to actually build tho :\
eval ?
oh ok, which is not possible to write with unicode's lame superscripts
im thinking i need to eval to get the value and ord() it
MESSAGE = _______________________,__
slist = []
slist.append(MESSAGE)
x = 0
for i in range(MESSAGE[0]):
print(eval(slist[-1]))
x += 1``` this doesn't seem to work
because I cant eval the variable which i'm trying to get (the first thing in the tuple which I put into the list) because I cant eval tuples
why can't tuples be evalled
Traceback (most recent call last):
File "/home/octane22/underencryption.py", line 27, in <module>
print(eval(slist[-1]))
TypeError: eval() arg 1 must be a string, bytes or code object```
clearly it wont allow the first thing in the MESSAGE tuple
*last thing, so 2nd
oh wait -1 is last
Yeah
yeah doesn't change it
just brute force it? if its natural numbers:
f = lambda n,p,i=2:f(n,p,i+1)if eval(str(i)+'**i'*(p-1))!=n else i
You're adding a tuple to slist, and then trying to eval said tuple
but I still don't understand why I cant eval what I'm trying 2
You need to get the item out of the tuple I assume
And presumably the first part of MESSAGE is an integer, not a string which eval needs, since you're doing range(MESSAGE[0])
yeah so each _____ variable which is equal to a number has to be taken out into its own variable
now how will I do that
its supposed to be the length of the tuple
how many items in the tuple
for the time being il put 1
as theres 2 underscore variables to make the letter H
natural numbers won't get you anywhere 😉
your description doesnt say it cant just be a natural number ¯_(ツ)_/¯
let's say target is a nice and easy number like 5
which number x x ** x ** x ** x == 5?
god fucking knows
😄
you could just binary search
@last locust ```py
ORDNUMBER1 = _______________________
ORDNUMBER2 = __
slist = []
slist.append(ORDNUMBER1)
slist.append(ORDNUMBER2)
x = 0
for i in range(slist[1]):
print(eval(_______________________))
x += 1
i literally can't get the value of my variable
what should I do to get the value of it?
only with exponentiation you end up in mathematical nomansland before you can say "oh crap"
first time ive heard mathematical nomansland ever in my life
cool term
it's somewhere between underflow and overflow 😄
maths is scary...
on the other side of the number scale, that is
right 😄
i dont want that image in my head
but its going in my notebook of brain damage python programs
also you could argue that, just with square roots, you can get weird numbers like pi that don't ever stop.. but in this case, you might get a number that actually stops but you can't represent it in your memory.. it's a weird limbo between "should work in theory" and "is my calculation right or is my computer wrong"
@coral kernel
import numpy as np
import warnings
warnings.filterwarnings("ignore") #stop from printing RuntimeWarnings
d=np.double
def t(base,p):
x=d(1)
for _ in range(p):x=base**x
return x
def algo(n,p,max_iters=60,threshold=1e-300):
f = lambda x:t(x,p)-n
xl=d(min(n,1))
xu=d(2) if f(2)>0 else d(max(n,1))
fl,fu = f(xl),f(xu)
fr=xr=d(0.0)
for s in range(max_iters):
xB=(xu+xl)/2
xRF=xl if fu==np.inf else (xu*fl-xl*fu)/(fl-fu)
xr=(xB+xRF)/2 if (s%3!=0 or xu-xl>0.5 or abs(fr)>0.5) else xRF
fr=f(xr)
if fr<0:xl,fl=xr,fr
else:xu,fu=xr,fr
if xu - xl < threshold or abs(fr) < threshold:
return (xu+xl)/2
return (xu+xl)/2
i = d(input("number: "))
p = int(input("tower degree: "))
print(algo(i,p))
approximates over 60 iterations, with early terminating if uncertainty gets too low
Can be extended with the higher precision float types of numpy, here I used double
Hope this satisfies you
Esoteric challenge of the day:
Given integer N, find all integers 0 < x < N that are coprime with N (i.e. they don't share any prime factors)
cool 🙂
let's see
!e Small (albeit inefficient) solution:
import math
N=15
print([x for x in range(1,N)if math.gcd(x,N)==1])
@prisma coral :white_check_mark: Your eval job has completed with return code 0.
[1, 2, 4, 7, 8, 11, 13, 14]
tfw math has a gcd function
!e ```py
c=lambda x,y:y and c(y,x%y)or x==1
totients=lambda n:[x for x in range(1,n)if c(x,n)]
print(totients(39))
@grave rover :white_check_mark: Your eval job has completed with return code 0.
[1, 2, 4, 5, 7, 8, 10, 11, 14, 16, 17, 19, 20, 22, 23, 25, 28, 29, 31, 32, 34, 35, 37, 38]
!e
print(*(lambda c:[i for i in range(c)if(f:=lambda a,b:f(b,a%b)if b else a<2)(i,c)])(39))
@severe canyon :white_check_mark: Your eval job has completed with return code 0.
1 2 4 5 7 8 10 11 14 16 17 19 20 22 23 25 28 29 31 32 34 35 37 38
you got it working?
a shiny distracted me >.>
in form of noodles
there's some rounding errors, but i'm impressed
it's pretty good
i'm a bit at a loss how the algo works though
pretty neat maths
yeah, that question got asked 2 years ago, i fiddled with the problem way longer before that
very cool
there was a ruby implementation which i just translated to python
i think with these types of problems, approximations are king
at least for practical purposes
there's still a little itch wondering whether there's a closed form with a precise solution 😉
id be surprised
is ruby popular for math stuff?
No idea
how can I golf this
r=range(2,37);print(*sorted({l for x in r for y in r if(l:=x**y+y**x)<1e11}),sep="\n")```
you can do:
r=range(2,37);[*map(print,sorted({l for x in r for y in r if(l:=x**y+y**x)<1e11}))]
!e
r=range(2,37);[*map(print,sorted({l for x in r for y in r if(l:=x**y+y**x)<1e11}))]
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 8
002 | 17
003 | 32
004 | 54
005 | 57
006 | 100
007 | 145
008 | 177
009 | 320
010 | 368
011 | 512
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/wumigolufe.txt?noredirect
how does that work?
map gives a generator, unpacking it to a list with [*map()]evaluates it, and doing so it calls the print on each element
at least thats how i think about it, dont know if its 100% correct
how is it even possible to shave another 10 off wtf
sounds right to me
I guess I'd first isolate the setcomp
{l for x in r for y in r if(l:=x**y+y**x)<1e11}
use of the walrus operator is delicious there .
how can I make the set comp shorter?
I tried this but I can't get it working and its also longer
!e py def tetrate(): x = 2 + 2j x = x**x for i in range(10000000): x = x**x**x**x**x**x print(x) tetrate()
@sick hound :x: Your eval job has completed with return code 143 (SIGTERM).
001 | (0.9905049543076663+0.01729803735036258j)
002 | (0.9903072326746436+0.016969110737840895j)
003 | (0.9901242552062786+0.016640288224954388j)
004 | (0.9899555657339242+0.01631227486495798j)
005 | (0.989800682874218+0.015985717936909453j)
006 | (0.989659105770705+0.015661208053031707j)
007 | (0.9895303193698434+0.015339280710253502j)
008 | (0.9894137992209975+0.015020418204912631j)
009 | (0.9893090158001866+0.014705051835446677j)
010 | (0.9892154383657691+0.014393564324438458j)
011 | (0.989132538361032+0.014086292398311802j)
... (truncated - too many lines)
Full output: too long to upload
i like the way it takes a while for the numbers to be printed
if you dont mind having it all in 1 print statement:
r=range(2,37);print(*sorted({l for x in r for y in r if(l:=x**y+y**x)<1e11}))
!e
r=range(2,37);print(*sorted({l for x in r for y in r if(l:=x**y+y**x)<1e11}))
@severe canyon :white_check_mark: Your eval job has completed with return code 0.
8 17 32 54 57 100 145 177 320 368 512 593 945 1124 1649 2169 2530 4240 5392 6250 7073 8361 16580 18785 20412 23401 32993 60049 65792 69632 93312 94932 131361 178478 262468 268705 397585 423393 524649 533169 1048976 1058576 1596520 1647086 1941760 2012174 2097593 4194788 4208945 4785713 7861953 8389137 9865625 10609137 14352282 16777792 16797952 33554432 33555057 43050817 45136576 48989176 61466176 67109540 67137425 129145076 134218457 177264449 244389457 268436240 268473872 292475249 364568617 387426321 536871753 774840978 1073742724 1073792449 1162268326 1173741824 1221074418 1996813914 2147484609 2179768320 3486792401 4294968320 4295032832 4486784401 6104053449 8589935681 8804293473 10460362464 13065520825 13877119009 17179870340 17179952705 20000000000 30518337500 31381070257 33739007300 34359739593 68719478032 68719581712 69149458432 78371693632 94143190994 96951758924
problem is the output requires a newline
i'd say use the sep kwarg to print but this is golf
Hmm
!e py r = (c:=[1]*37, [j for i in c[:] if (j:=(c.remove(1), i*len(c))[1]) >= 2])[1];print(*sorted({l for x in r for y in r if(l := x**y+y**x)<1e11}))
@pastel ibex :white_check_mark: Your eval job has completed with return code 0.
8 17 32 54 57 100 145 177 320 368 512 593 945 1124 1649 2169 2530 4240 5392 6250 7073 8361 16580 18785 20412 23401 32993 60049 65792 69632 93312 94932 131361 178478 262468 268705 397585 423393 524649 533169 1048976 1058576 1596520 1647086 1941760 2012174 2097593 4194788 4208945 4785713 7861953 8389137 9865625 10609137 14352282 16777792 16797952 33554432 33555057 43050817 45136576 48989176 61466176 67109540 67137425 129145076 134218457 177264449 244389457 268436240 268473872 292475249 364568617 387426321 536871753 774840978 1073742724 1073792449 1162268326 1173741824 1221074418 1996813914 2147484609 2179768320 3486792401 4294968320 4295032832 4486784401 6104053449 8589935681 8804293473 10460362464 13065520825 13877119009 17179870340 17179952705 20000000000 30518337500 31381070257 33739007300 34359739593 68719478032 68719581712 69149458432 78371693632 94143190994 96951758924
map(print, ) somehow maybe
I don't know if this is the correct channel to ask about this doubt, but I have seen something weird in python that I don't understand
!e
a
print(a)
@full arch :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 'a' is not defined
@full arch :warning: Your eval job has completed with return code 0.
[No output]
How come this doesn't raise an error
!e
def abc(a: print(123)) -> print(123):
return a
p: print(123) = abc(123)
And how come this even works
@full arch :white_check_mark: Your eval job has completed with return code 0.
001 | 123
002 | 123
003 | 123
typehints aren't used for anything except annotations
!e
def abc(a: print(123)) -> print(123):
return a
p: print(123) = abc(123)
print(abc.__annotations__)
print(__annotations__)
@golden finch :white_check_mark: Your eval job has completed with return code 0.
001 | 123
002 | 123
003 | 123
004 | {'a': None, 'return': None}
005 | {'p': None}
Ahh, I see
Full disclosure: the code I am about to send should not be used in production and I am not responsible for anything that happens if you do
Hmmm
(one second, it's proving difficult. did I ever mention how much I hate metaclasses?)
You didn't
I'm still working on it - it's a demonstration of how you can use typehints
I'll just make a smaller recreation for now
Aaaa, suspense is killin me
tell me about it
Aren't you making something with typehints that you wanna show me?
Ye then I am waiting
it's not particularly easy to say the least
got the wrapper working now I just need to clean it up
brilliant
okay it *works but it has some leftovers
cool
!e
def wrap(f):
def getf(*args):
#first, check the arguments
for c,v in enumerate(args):
if type(v)!=[*f.__annotations__.values()][c]:
raise TypeError(f'Type of argument {v.__repr__()} does not match type hint {[*f.__annotations__.values()][c]}.')
rval=f(*args)
if 'return'in f.__annotations__ and type(rval)!=f.__annotations__['return']:
raise TypeError(f'Type of return value {rval.__repr__()} does not match type hint {f.__annotations__["return"]}.')
return rval
return getf
class foo:
@wrap
def add(a:int, b:int) -> int:
return a + b
print(foo.add(1,2))
proof of concept, needs work
@golden finch :white_check_mark: Your eval job has completed with return code 0.
3
@full arch
What the fu
How does that even work....
Oh wait...
!e
def wrap(f):
def getf(*args):
#first, check the arguments
for c,v in enumerate(args):
if type(v)!=[*f.__annotations__.values()][c]:
raise TypeError(f'Type of argument {v.__repr__()} does not match type hint {[*f.__annotations__.values()][c]}.')
rval=f(*args)
if 'return'in f.__annotations__ and type(rval)!=f.__annotations__['return']:
raise TypeError(f'Type of return value {rval.__repr__()} does not match type hint {f.__annotations__["return"]}.')
return rval
return getf
class foo:
@wrap
def add(a: int, b: int) -> int:
return a + b
print(foo.add("1", "2"))
@full arch :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 18, in <module>
003 | File "<string>", line 6, in getf
004 | TypeError: Type of argument '1' does not match type hint <class 'int'>.
It doesn't yet work for all cases but I'm working on it
but that's just a demo of one limited case
it's probably been done before
Ah
@golden finch do you want an esoteric challenge
if you do it you are smarter then einstein
this doesn't bode well given that I am not smarter than einstein, but sure
inb4 grand unified theory
(lambda self=[___:=((([]==[]))+(([]==[]))) ,
__:=(___)*((([]==[]))+(([]==[])))**___//___ , ____:=(__)**___ ,
_______________________:=(((__))+(__))**((([]==[]))+(([]==[])))+(([]==[]))+(([]==[]))+(([]==[]))+(([]==[])) ,
_____________:=((___)) , _____________:=((___)) , _______:=(([]==[]))+(___) , _______:=((_______))+_____________ ,
______ := chr((((___)))*((((__))))**(__)+(__)//((___))) , [[((__)+(((___)))//(____)-((___))+((___)**(___)**((_______)))) ,
_________________:=(__)+(((___)))//(____)-((___))+((___)**(___)**((_______))) ,
_________________ := ((((((((((((((_________________))))))))))))))+_______ , ((_________________),~_______________________)]\
for ___ in range(__) if ((_______)) !=[(([]==[]))-(___)]]][___]: eval(type(None).__bool__.__doc__))()
import fishhook
@fishhook.hook(int)
def __repr__(self):
stuff = {v: k for k,v in globals().items() if isinstance(v,int) and k.startswith('_')} | {1:'_'}
x = self
nums = []
for elem in sorted(stuff.keys(),reverse=True):
while x>=elem:
nums.append(stuff[elem])
x-=elem
return ','.join(nums)
MESSAGE = ''
slist = []
slist.append(MESSAGE)
x = 0
for i in range(len(MESSAGE)):
print(ord(slist[0][x]))
x += 1```
there is something inbetween the single quotes
_______________________,____,____,____,_______
_______________________
_______________________,____,____,_______
_______________________,____,____,_______,_______,_______``` is the output
find the message @golden finch
did you get it @sick hound
!e
exec(__import__("gzip").decompress(__import__("base64").b64decode(b'H4sIAI6GuGEC/51TsXLbMAzd+RXoZNKW5WTVnXrtkOvULumm6niKRcWsZVJH0o5zafrtBSgpqi9yh2IgQQB87wGieFsdHuoKvGqbvJBSZjnnvCjzvCiFWE2ugARYTGORWF4pWi4xu9ngguVSDvV9uAeYtUiKdYhF6/Ia/Go2PO++oyMS0i4Gaf9KUGjCpORlbnAxeYE0cUKWw3bnOB+g48Ric7E9dGKrm82Yx6tFwfvEGMNsZFkPgVW/x/txm3TM9DuN//8QZwGpL35h70rEha2m0czVJr+vPAlR/mCNdTR00AZcZR4V9QK6gb9Uwoe8mD7VOrZRliW95DIDdapaHp47xb9Zo0Qq5YO1rZTo1HZL97lgTB866wI02u921u7Zp9FLaeHaBMFq1aAUpzonJaefRWQM0Hw4Ng3k8HLKYA8keJ+cSPBjax+q1nOR6qAOuJNw7bXxoTJbxU8J4UJlatinGHPBP+mw4wu5EK/wC15uM3RfI8kZCYgzHszx4PFclPFEjKpVB6L02IWqeZSU7tUzkiZOnZTzKv/ujmqQTPa0062C88ec7k7hET+tuk6ZAaqgmlJcFJ3X8WaMORWOzsAiWaQ/rTacAHCqcWS11YF/vbu///zlLtL7Vvswyo+HkWusYn2/N6xvTk9fv1Xmreqtl87hHLl1KJbQipuyOONLGLJnWOVwy9gfGUNcAOcEAAA='))); doit("Hello")
``` @sick hound
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | _______________________,__
002 | _______________________,____,____,_
003 | _______________________,____,____,_______,_____________,_
004 | _______________________,____,____,_______,_____________,_
005 | _______________________,____,____,_______,_______,_
!e
print(“huiii”)
@sick hound :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | print(“huiii”)
003 | ^
004 | SyntaxError: invalid character '“' (U+201C)
@sick hound :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | Print(‘hi’)
003 | ^
004 | SyntaxError: invalid character '‘' (U+2018)
this is what your program looks like when it's running
well, my tweaked version. I made it return the string instead of printing
now trying to brute force it
how are you typing where it's adding "smart quotes"?
should write a quote-dumbing function
!charinfo Print(‘hi’)
\u0050 : LATIN CAPITAL LETTER P - P
\u0072 : LATIN SMALL LETTER R - r
\u0069 : LATIN SMALL LETTER I - i
\u006e : LATIN SMALL LETTER N - n
\u0074 : LATIN SMALL LETTER T - t
\u0028 : LEFT PARENTHESIS - (
\u2018 : LEFT SINGLE QUOTATION MARK - ‘
\u0068 : LATIN SMALL LETTER H - h
\u0069 : LATIN SMALL LETTER I - i
\u2019 : RIGHT SINGLE QUOTATION MARK - ’
\u0050\u0072\u0069\u006e\u0074\u0028\u2018\u0068\u0069\u2019\u0029
!charinfo print(“huiii”)
\u0070 : LATIN SMALL LETTER P - p
\u0072 : LATIN SMALL LETTER R - r
\u0069 : LATIN SMALL LETTER I - i
\u006e : LATIN SMALL LETTER N - n
\u0074 : LATIN SMALL LETTER T - t
\u0028 : LEFT PARENTHESIS - (
\u201c : LEFT DOUBLE QUOTATION MARK - “
\u0068 : LATIN SMALL LETTER H - h
\u0075 : LATIN SMALL LETTER U - u
\u0069 : LATIN SMALL LETTER I - i
\u0070\u0072\u0069\u006e\u0074\u0028\u201c\u0068\u0075\u0069\u0069\u0069\u201d\u0029
the "left" one is the issue most prob
!e
def dumb_quotes(s: str): return [s:=s.replace(k,v) for k,v in {'\u2018':'\'', '\u2019':'\'', '\u201B':'\'', '\u201C':'"', '\u201D':'"'}.items()][-1]
exec(dumb_quotes("print(“huiii”)"))
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
huiii
.bm dumbquotes
see above ^ 
jesus please explain the code
I hate it
greyblue92 has massacred my code
it actually followed pep8 for fucking once
thats your fault 😄
#python-discussion just tping
@rapid sparrow damn lets make an extremely secure code
which has varying degrees of randomness and multiple elements of bullshit esoteric python encryption rolled into one program
the enigma code will be child play after we finish this
dont you think randomness is a bit too much? xD
enigma literally means mysterious or difficult to understand, we won't put hail hitler at the end of each message and function
Damn, probably a good thing that future annotations still require the annotations to be valid syntax despite just being turned into a string
I would have abused that so much
But I think I've just come up with a workaround
lets see
One sec I'll make something cursed first
Oh god I destroyed my linters syntax highlighting
keep going
@rapid sparrow wanna make an epic encryption together
underscore code for select length
!e ```py
(lambda self=[:=((([]==[]))+(([]==[]))) ,
:=()*((([]==[]))+(([]==[])))**//__ , :=()** ,
_____:=((())+())**((([]==[]))+(([]==[])))+(([]==[]))+(([]==[]))+(([]==[]))+(([]==[])) ,
________:=(()) , :=(()) , :=(([]==[]))+() , :=(())+ ,
______ := chr(((()))*(((())))**()+()//(())) , [[(()+((()))//()-(())+(()**()**(()))) ,
____________:=()+((()))//()-(())+(()**()**(())) ,
_________________ := ((((((((((((((_________________))))))))))))))+__ , ((),~____)]
for ___ in range() if ((_)) !=[(([]==[]))-()]]][]: eval(type(None).bool.doc))()
import fishhook
@fishhook.hook(int)
def repr(self):
stuff = {v: k for k,v in globals().items() if isinstance(v,int) and k.startswith('')} | {1:''}
x = self
nums = []
for elem in sorted(stuff.keys(),reverse=True):
while x>=elem:
nums.append(stuff[elem])
x-=elem
return ','.join(nums)
MESSAGE = 'P'
slist = []
slist.append(MESSAGE)
x = 0
for i in range(len(MESSAGE)):
print(ord(slist[0][x]))
x += 1```
@sick hound :white_check_mark: Your eval job has completed with return code 0.
_______________________,_______,_______,_____________
my issue with the underscore code
length of the letter P
is that it's not standalone
elaborate?
like it can't be just run in eval by itself, I mean
oh that's true....
if we could output the bootstrap code with it, then that concern would be addressed
wdym output the bootstrap code? the ascii numbers for the letters in the message?
!e
(lambda self=[___:=((([]==[]))+(([]==[]))) ,
__:=(___)*((([]==[]))+(([]==[])))**___//___ , ____:=(__)**___ ,
_______________________:=(((__))+(__))**((([]==[]))+(([]==[])))+(([]==[]))+(([]==[]))+(([]==[]))+(([]==[])) ,
_____________:=((___)) , _____________:=((___)) , _______:=(([]==[]))+(___) , _______:=((_______))+_____________ ,
______ := chr((((___)))*((((__))))**(__)+(__)//((___))) , [[((__)+(((___)))//(____)-((___))+((___)**(___)**((_______)))) ,
_________________:=(__)+(((___)))//(____)-((___))+((___)**(___)**((_______))) ,
_________________ := ((((((((((((((_________________))))))))))))))+_______ , ((_________________),~_______________________)]\
for ___ in range(__) if ((_______)) !=[(([]==[]))-(___)]]][___]: eval(type(None).__bool__.__doc__))();print(_______________________,_______,_______,_____________)
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
68 5 5 2
that's all i meant
oh that
those numbers adding up make the ascii code for capital P
yeah i understand
That absolutely destroys my syntax highlighting
!e
class Test:
def __format__(_, format_spec):
header = format_spec.split("(")[1].split(")")[0].split(";")
header[0] = header[0].split("let ")[1]
body = "\n".join(x.strip() for x in format_spec.split("[")[1].strip().split("]")[0].strip().split("\n"))
globals()[header[0]] = 0
while eval(header[1]):
exec(body)
globals()[header[0]] += 1
return ""
let_the_world_burn = Test()
f"""{let_the_world_burn:
for (let i; i < 10; i++)[
print(i)
print("Hello world")
]
}"""
@gritty mesa :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | Hello world
003 | 1
004 | Hello world
005 | 2
006 | Hello world
007 | 3
008 | Hello world
009 | 4
010 | Hello world
011 | 5
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/wicadugili.txt?noredirect
I can make my own language inside f-strings 
!e
(lambda self=[___:=((([]==[]))+(([]==[]))) ,
__:=(___)*((([]==[]))+(([]==[])))**___//___ , ____:=(__)**___ ,
_______________________:=(((__))+(__))**((([]==[]))+(([]==[])))+(([]==[]))+(([]==[]))+(([]==[]))+(([]==[])) ,
_____________:=((___)) , _____________:=((___)) , _______:=(([]==[]))+(___) , _______:=((_______))+_____________ ,
______ := chr((((___)))*((((__))))**(__)+(__)//((___))) , [[((__)+(((___)))//(____)-((___))+((___)**(___)**((_______)))) ,
_________________:=(__)+(((___)))//(____)-((___))+((___)**(___)**((_______))) ,
_________________ := ((((((((((((((_________________))))))))))))))+_______ , ((_________________),~_______________________)]\
for ___ in range(__) if ((_______)) !=[(([]==[]))-(___)]]][___]: eval(type(None).__bool__.__doc__))();print("".join(chr(sum((_______________________,_______,_______,_____________)))))
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
P
yeah and use type() and __import__ and other magic methods bs to create keywords and methods
yes sir
🤣 haha
now those underscores are just the length for the real encryption 
how do you get a whole message, by doing one char per line?
Unlike annotations, f-string format specs don't need to be valid python syntax
So you can stick absolutely anything you want in there
what ? really
for (let i; i < 10; i++)[
print(i)
print("Hello world")
]
```Did you not see this mess
you just do it yeah
ohhh lord
esoteric channel will be having fun tonight
let ?
is that js?
!e py for (let i; i < 10; i++)[ print(i) print("Hello world") ]
@sick hound :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | for (let i; i < 10; i++)[
003 | ^^^^^
004 | SyntaxError: invalid syntax. Perhaps you forgot a comma?
Allow me to introduce myself #esoteric-python message
@rapid sparrow
holy crap
that is absolutely terrifying
yours ^
sir my hat goes off to you 👒
All one one line too
@lambda _:_()
class let_the_world_burn:
def __format__(_, format_spec):
header=format_spec.split("(")[1].split(")")[0].split(";");header[0]=header[0].split("let ")[1];body="\n".join(x.strip() for x in format_spec.split("[")[1].strip().split("]")[0].strip().split("\n"));globals()[header[0]]=0
while eval(header[1]):exec(body);globals()[header[0]] += 1
return ""
f"""{let_the_world_burn:
for (let i; i < 10; i++)[
print(i)
print("Hello world")
]
}"""
```That may be a little better, people can focus on the cursed part more now
!e
exec(__import__("gzip").decompress(__import__("base64").b64decode(b'H4sIAAGauGEC/+1aUW6DMAz93ylQf5pIFQeo1CvsAghF7aAqE5ANaM/fBDKggjISgjuY+QoU58XPL3ZSQpi89od3noY7p2pHaUE832UsDlPGCBWtE+exauZFplrNz8cgEC2v7Gu84eND1QcsLjVFzq8nE2RacSxZ3m7dTx6lRLxEPi4ZqZ4zSp0zz9RbzIlSpwSph8lYlHzxrBDNTXIsLhvq5t9ZUZpLJBG8xyGCuKX8qnt4fqMxHivR0YGDRasp0wos1TWYrgRNChHNCpqhPoAnPignoPMTwSzpWF6+VPP+IIxVdWsXNrslY6ZK1JmN83drvBbS00JyjYHAemuXWvb0F7uhLDhkuOr5ZEYJ8DCnDlLH4hxzngXRbaXxNkwIGLj/FThQ74CpnLuoQ3TbEvsKBdFS++jirmvhmi1WFqFwFA2K5o9XGFDnEGx5YLQvkeF6sCYHmfmVGbv/rpiYmbsx5MSkb2ov+qRm+EWtQ4SOzldazZAU66S8cPuJibsbQGRmmBl1g/s5hvu556JpbNfmHIItD6x3P4eJDBPZqEQGiOf7Oye8HWPyc6jOy5tTdc2JOnnogPni/bc7AOb/2fcoAAA=')));
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
Hello world!
im thinking of multiple complex ciphers and encryptions and random interchanging messy letter swapping
abridged version :p
That was the original actually
As long as it's standalone
yeah
so we can easily eval and "inspire' folks
.bm
!e ```py
@import
@lambda _: _.name
class hello: pass
@terse mortar :white_check_mark: Your eval job has completed with return code 0.
Hello world!
yeah would be epic project to complete
what I don't get is, what the heck is happening in the format spec part
Yeah don't worry about that, that's just me not knowing regex
i mean the multi-line part after the :
inside the f-string
how come python doesn't choke on it
What this? ```py
for (let i; i < 10; i++)[
print(i)
print("Hello world")
]
Or just the whole thing
After :
yeah, does it not get parsed and formstted ? the whole part after :, yeah
It just treats everything after : as a string
ohh
So you end up with two newlines then the cursed loop
and the f-string itself is quoted
Yeah
Yeah I had no idea. I kind of just assumed it was like future annotations, where everything in the annotation is converted to a string but it had to be valid Python syntax
But then I realised that's not the case with a lot of common format specs
Yeah I made it somewhat flexible
And by that I mean barely flexible but good enough
!e
@lambda _:_()
class let_the_world_burn:
def __format__(_, format_spec):
header=format_spec.split("(")[1].split(")")[0].split(";");header[0]=header[0].split("let ")[1];body="\n".join(x.strip() for x in format_spec.split("[")[1].strip().split("]")[0].strip().split("\n"));globals()[header[0]]=0
while eval(header[1]):exec(body);globals()[header[0]] += 1
return ""
f"""{let_the_world_burn:
for (let x; x < 10; x++)[
print(x)
]
}"""
@gritty mesa :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
have I mentioned how much I love the new error messages
!e @gritty mesa
@lambda _:_()
class let_the_world_burn:
def __format__(_, format_spec):
header = format_spec.strip().split("\n")[0].strip("[]").replace("for ","").strip("()").split(";");header[0]=header[0].split("let ")[1];body="\n".join(x.strip() for x in format_spec.split("[")[1].strip().split("]")[0].strip().split("\n"));exec(header[0],globals());
while eval(header[1]):exec(body);exec(header[2].strip())
return ""
f"""{let_the_world_burn:
for (let i, j = (0,1); i < 7; i+=j)[
print(i)
print(j)
print("Hello world")
]
}"""
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | Hello world
004 | 1
005 | 1
006 | Hello world
007 | 2
008 | 1
009 | Hello world
010 | 3
011 | 1
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/xarujusofa.txt?noredirect
Good lord
no need to pretend you're appauled 😄
lol
@rapid sparrow in 1 hour and 16 min i will finish making an addition to the code
xd
working on it right now
this is harder then i thought
interesting,
so with increasing height of the "power tower", the function gets recursively more in magnitude, right ?
lets say "height = 1" is exponentiation
0: x*x
1: x**x
2: x**x**x
...
and so on ?
i should just look at the wiki lol
!e
х = 9
x = 10
print(х)
print(x)
@carmine sun :white_check_mark: Your eval job has completed with return code 0.
001 | 9
002 | 10
lol, different x's
@gritty mesa why am I unable to stop thinking about your f-string format spec "mini-language" ... damnit
so basically I'm thinking the code is equivalent to
let_the_world_burn.__format__('''
for (let i, j = (0,1); i < 7; i+=j)[
print(i)
print(j)
print("Hello world")
]
''')
very interesting indeed
Hey can you help me with this? Wher am I going wrong
You are given two strings S1 and S2. You need to convert the string S1 into a palindromic string such that it contains the string S2 as its substring by using minimum number of operations. You are allowed to use only one type of operation i.e., you can replace any character of the string S1 with any other.
Consider S1 "abcad" and S2 ad We need to change some characters in S1 such that it becomes palindrome and S2 occurs as a substring in St. So if we change $1 = "dacad" ad occurs as a subtring at position 3 and S1 is a palindrome So answer 2
def minchr(S1, S2):
n, m = len(S1), len(S2)
ans = sys.maxsize
for i in range(m - n + 1):
minChar = 0
for j in range(n):
if (S1[j] != S2[i + j]):
minChar +=1
ans = min(minChar, ans)
return ans
I suggest getting a help channel for this
this channel is for writing intentionally awful code
(in terms of practicality)
No one is responding there
ask in #python-discussion ?
we see it as beautiful
yeah,I thought of saying something too lol
quixotic yeah
@sick hound the people that added these error messages love us
!e I got @gritty mesa 's code down to one line but now it doesn't do anything 
(main:=lambda format_spec: ((header := format_spec.strip().split("\x0a")[0].strip("[]").replace("for ","").strip("()").split(";")), header.__setitem__(0, header[0].split("let ")[1]), body:="\x0a".join(x.strip() for x in format_spec.split("[")[1].strip().split("]")[0].strip().split("\x0a")), exec(header[0],globals()), [(exec(body),exec(header[2].strip())) for _ in range(0, 1, -1) if eval(header[1])], "")[-1])('''
for (let i, j = (0,1); i < 7; i+=j)[
print(i, j, "Hello world")
]
''')
@rapid sparrow :warning: Your eval job has completed with return code 0.
[No output]
lol
true
i can see
honestly my underscore code thingy may be complex enough
if i challenge everyone in the discord to figure out the code with only the starting program how long do you think it will take
yep, exactly



