#esoteric-python
1 messages · Page 119 of 1
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 4, in <module>
003 | TypeError: keywords must be strings
You can do anything but you cannot change those 4 lines
Alright since you asked you can put the code before those four lines
It'd help if I got a 2d matrix, with 0s for blank cells.
That way I can plug it straight in the initialization
like, a python list?
[[8,0,0,0,0,0,0,0,0],
[0,0,3,6,0,0,0,0,0],
[0,7,0,0,9,0,2,0,0],
[0,5,0,0,0,7,0,0,0],
[0,0,0,0,4,5,7,0,0],
[0,0,0,1,0,0,0,3,0],
[0,0,1,0,0,0,0,6,8],
[0,0,8,5,0,0,0,1,0],
[0,9,0,0,0,0,4,0,0]]
Perfect, thank you
What the algorithm will do:
- create a matrix of set based cells of range 1 to 9
- iterate through inputted coordinates or array updating the data
- check everything's okay, before running reduce() until either Solved is raised, SolutionError is raised, or nothing changes
- check it's solved and print the board plus status of the puzzle
!e ```py
u=import('random').randint
def m(c,r):
o=[]
for i in range(c):o.append([u(0,9)for i_ in range(r)])
return o
print(m(10,5))```
@sly root :white_check_mark: Your eval job has completed with return code 0.
[[3, 9, 8, 8, 0], [1, 8, 2, 7, 0], [3, 9, 2, 7, 8], [4, 5, 0, 3, 1], [4, 3, 5, 9, 9], [0, 3, 6, 7, 1], [0, 6, 5, 8, 6], [4, 6, 6, 3, 8], [8, 7, 0, 6, 0], [2, 9, 0, 3, 6]]
0s for empty cells
reduce:
- calls reduce cell for each cell.
- checks all aligned cells and reduces set elements that would not satisfy a solution.
- calls eliminate for all lines columns and boxes
- if an element can only go in one place in this array, assign that element.
are sudoku tables like the thing to do in esoteric code
If you think you can turn this menace into a proper ascii sudoku table, that would be appreciated ;)
a proper table won't be the same size
Although it works as it is
Note: the cell reduction solves cells not by assigning values but taking away invalid values.
The cell class is based on set, but + overwrites the whole set with a number, - removes the respective element and index returns 0 unless the length is 1
Ooh and repr acts like integer if the length of the set is one
Essentially it's a set until it has one element then it's an integer
I have a idea about esoteric python
!m:c,r_,
o[]
i?c|o<-[u.1,9|i_?r]
<o```
! = def
: = (args)
o[] = o = []
x?x|x = for x in x:x
o<-x = o.append(x)
u.1,9 = u(1,9)
x|x?x = x for x in x
<o = return o```
import re
code = """
#random{randint@u}
!m:c,r_,
o[]
i?c|o<-[u.1,9|i_?r]
<o
"""
new = """
"""
for line in code.splitlines():
line = line.replace('#random{randint@u}', 'from random import randint as u\n')
line = line.replace('!', 'def ')
line = line.replace(':', '(')
line = line.replace('_,', '):\n\t')
line = line.replace('[]', '=[]\n\t')
line = line.replace('i?c|', 'for i in range(c):\n\t\t')
line = line.replace('o<-[', 'o.append([')
line = line.replace('u.1,9', 'u(1,9) ')
line = line.replace('|i_?r]', 'for i_ in range(r)])\n\t')
line = line.replace('<o', 'return o')
new += line```
sounds like Pyth https://esolangs.org/wiki/Pyth 
@limpid thorn this is esoteric python, where you ask for what not to do
perhaps try #❓|how-to-get-help
looks too readable for esoteric python XD
this is what the machine makes of it
[[8, {1, 2, 4, 6}, {2, 4, 5, 6, 9}, {2, 3, 4, 7}, {1, 2, 3, 5, 7}, {1, 2, 3, 4}, {1, 3, 5, 6, 9}, {9, 4, 5, 7}, {1, 3, 4, 5, 6, 7, 9}],
[{1, 2, 4, 5, 9}, {1, 2, 4}, 3, 6, {1, 2, 5, 7, 8}, {8, 1, 2, 4}, {8, 1, 5, 9}, {4, 5, 7, 8, 9}, {1, 4, 5, 7, 9}],
[{1, 4, 5, 6}, 7, {4, 5, 6}, {8, 3, 4}, 9, {8, 1, 3, 4}, 2, {8, 4, 5}, {1, 3, 4, 5, 6}],
[{1, 2, 3, 4, 6, 9}, 5, {9, 2, 4, 6}, {8, 9, 2, 3}, {8, 2, 3, 6}, 7, {8, 1, 6, 9}, {8, 9, 2, 4}, {1, 2, 4, 6, 9}],
[{1, 2, 3, 6, 9}, {1, 2, 3, 6, 8}, {9, 2, 6}, {8, 9, 2, 3}, 4, 5, 7, {8, 9, 2}, {1, 2, 6, 9}],
[{2, 4, 6, 7, 9}, {8, 2, 4, 6}, {2, 4, 6, 7, 9}, 1, {8, 2, 6}, {8, 9, 2, 6}, {8, 9, 5, 6}, 3, {2, 4, 5, 6, 9}],
[{2, 3, 4, 5, 7}, {2, 3, 4}, 1, {2, 3, 4, 7, 9}, {2, 3, 7}, {9, 2, 3, 4}, {9, 3, 5}, 6, 8],
[{2, 3, 4, 6, 7}, {2, 3, 4, 6}, 8, 5, {2, 3, 6, 7}, {2, 3, 4, 6, 9}, {9, 3}, 1, {9, 2, 3, 7}],
[{2, 3, 5, 6, 7}, 9, {2, 5, 6, 7}, {8, 2, 3, 7}, {1, 2, 3, 6, 7, 8}, {1, 2, 3, 6, 8}, 4, {2, 5, 7}, {2, 3, 5, 7}]]
i don't know the solution it's just what google gives for "hardest sudoku"
>>> [(i,j,q[i,j],q[i,j].tied) for i,j in rij if q[i,j].tied]
[(0, 1, {1, 2, 4, 5, 9}, {9: {2, 4, 5, 6, 9}}), (0, 5, {2, 4, 6, 7, 9}, {7: {2, 4, 6, 7, 9}}), (0, 6, {2, 3, 4, 5, 7}, {5: {9, 3, 5}}), (1, 4, {1, 2, 3, 6, 8}, {8: {8, 2, 4, 6}}), (1, 5, {8, 2, 4, 6}, {8: {1, 2, 3, 6, 8}}), (2, 0, {2, 4, 5, 6, 9}, {9: {1, 2, 4, 5, 9}}), (2, 5, {2, 4, 6, 7, 9}, {7: {2, 4, 6, 7, 9}}), (2, 8, {2, 5, 6, 7}, {7: {2, 4, 6, 7, 9}}), (4, 0, {1, 2, 3, 5, 7}, {5: {1, 2, 5, 7, 8}}), (4, 1, {1, 2, 5, 7, 8}, {5: {1, 2, 3, 5, 7}}), (4, 8, {1, 2, 3, 6, 7, 8}, {1: {1, 2, 3, 6, 8}}), (5, 8, {1, 2, 3, 6, 8}, {1: {1, 2, 3, 6, 7, 8}}), (6, 5, {8, 9, 5, 6}, {5: {2, 4, 5, 6, 9}}), (6, 6, {9, 3, 5}, {5: {2, 3, 4, 5, 7}}), (8, 5, {2, 4, 5, 6, 9}, {5: {8, 9, 5, 6}})]
>>> print(*_,sep='\n')
(0, 1, {1, 2, 4, 5, 9}, {9: {2, 4, 5, 6, 9}})
(0, 5, {2, 4, 6, 7, 9}, {7: {2, 4, 6, 7, 9}})
(0, 6, {2, 3, 4, 5, 7}, {5: {9, 3, 5}})
(1, 4, {1, 2, 3, 6, 8}, {8: {8, 2, 4, 6}})
(1, 5, {8, 2, 4, 6}, {8: {1, 2, 3, 6, 8}})
(2, 0, {2, 4, 5, 6, 9}, {9: {1, 2, 4, 5, 9}})
(2, 5, {2, 4, 6, 7, 9}, {7: {2, 4, 6, 7, 9}})
(2, 8, {2, 5, 6, 7}, {7: {2, 4, 6, 7, 9}})
(4, 0, {1, 2, 3, 5, 7}, {5: {1, 2, 5, 7, 8}})
(4, 1, {1, 2, 5, 7, 8}, {5: {1, 2, 3, 5, 7}})
(4, 8, {1, 2, 3, 6, 7, 8}, {1: {1, 2, 3, 6, 8}})
(5, 8, {1, 2, 3, 6, 8}, {1: {1, 2, 3, 6, 7, 8}})
(6, 5, {8, 9, 5, 6}, {5: {2, 4, 5, 6, 9}})
(6, 6, {9, 3, 5}, {5: {2, 3, 4, 5, 7}})
(8, 5, {2, 4, 5, 6, 9}, {5: {8, 9, 5, 6}})
>>>
This seems pretty easy, given it already throws an error.
Can someone explain how tf this works
Oh I think I understand, the first print will become None which is Falsy so it won't run the second print and then it will run the third print
genius way to break people minds
Im calculating
[81]
1='8-1-2-7-5-3-6-4-9'
2='9-4-3-6-8-2-1-7-5'
3='6-7-5-4-9-1-2-8-3'
4='1-5-4-2-3-7-8-9-6'
5='3-6-9-8-4-5-7-2-1'
6='2-8-7-1-6-9-5-3-4'
7='5-2-1-9-7-4-3-6-8'
8='4-3-8-5-2-6-9-1-7'
9='7-9-6-3-1-8-4-5-2'
your test case give me
[81]
1='1-2-5-8-6-9-7-3-4'
2='9-3-6-2-7-4-5-1-8'
3='4-7-8-1-3-5-6-9-2'
4='3-8-4-6-5-1-2-7-9'
5='7-1-9-4-8-2-3-5-6'
6='6-5-2-7-9-3-8-4-1'
7='8-9-7-5-4-6-1-2-3'
8='5-4-1-3-2-8-9-6-7'
9='2-6-3-9-1-7-4-8-5'
this is a dump from my text file ...
Wat is that?
That is solution...
Bruh
Next up I'm gonna make my program recognise it failed to solve and switch to the iterative method, but with a twist
It'll only add another value if it can't solve with elegant values
In other words, guess, try to solve, recurse within that
you should also keep track of the solving path the most 'iteration' will make the hardest one. But stuff like Xwing are pretty hard too ....
This is assuming each step of the process is deduced, and not just guesswork
eh, i'll throw some good ol DFS at it see what happens
actually im a little hungry im just gonna do this sort of search algorithm rn
def brute_force(self):
__class__ = self.__class__
for i,j in rij:
if not self[i,j]:
for k in self[i,j]:
m = self.matrix
m[j][i] = k
try:puzzle(m, solve_now=True).check_solved()
except Solved:return m
except SolutionError:continue
except KeyboardInterrupt:break#press ctrl-c to make it go faster ;)
return self.matrix
+-------+-------+-------+
| 8 1 2 | 7 5 3 | 6 4 9 |
| 9 4 3 | 6 8 2 | 1 7 5 |
| 6 7 5 | 4 9 1 | 2 8 3 |
+-------+-------+-------+
| 1 5 4 | 2 3 7 | 8 9 6 |
| 3 6 9 | 8 4 5 | 7 2 1 |
| 2 8 7 | 1 6 9 | 5 3 4 |
+-------+-------+-------+
| 5 2 1 | 9 7 4 | 3 6 8 |
| 4 3 8 | 5 2 6 | 9 1 7 |
| 7 9 6 | 3 1 8 | 4 5 2 |
+-------+-------+-------+
is this right?
okay so it either shows it got solved, but keeps searching, or i can make it raise a massive error when it solves
the damn thing can now attack any legit puzzle
the source code looks like i pulled it out from where the sun don't shine
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
only problem is the brute force method overrides the rollback with the solved puzzle ```py
p
[[1, 2, 5, 8, 6, 9, 7, 3, 4],
[9, 3, 6, 2, 7, 4, 5, 1, 8],
[4, 7, 8, 1, 3, 5, 6, 9, 2],
[3, 8, 4, 6, 5, 1, 2, 7, 9],
[7, 1, 9, 4, 8, 2, 3, 5, 6],
[6, 5, 2, 7, 9, 3, 8, 4, 1],
[8, 9, 7, 5, 4, 6, 1, 2, 3],
[5, 4, 1, 3, 2, 8, 9, 6, 7],
[2, 6, 3, 9, 1, 7, 4, 8, 5]]
q
[[8, 1, 2, 7, 5, 3, 6, 4, 9],
[9, 4, 3, 6, 8, 2, 1, 7, 5],
[6, 7, 5, 4, 9, 1, 2, 8, 3],
[1, 5, 4, 2, 3, 7, 8, 9, 6],
[3, 6, 9, 8, 4, 5, 7, 2, 1],
[2, 8, 7, 1, 6, 9, 5, 3, 4],
[5, 2, 1, 9, 7, 4, 3, 6, 8],
[4, 3, 8, 5, 2, 6, 9, 1, 7],
[7, 9, 6, 3, 1, 8, 4, 5, 2]]
q.rollback
[[8, 1, 2, 7, 5, 3, 6, 4, 9], [9, 4, 3, 6, 8, 2, 1, 7, 5], [6, 7, 5, 4, 9, 1, 2, 8, 3], [1, 5, 4, 2, 3, 7, 8, 9, 6], [3, 6, 9, 8, 4, 5, 7, 2, 1], [2, 8, 7, 1, 6, 9, 5, 3, 4], [5, 2, 1, 9, 7, 4, 3, 6, 8], [4, 3, 8, 5, 2, 6, 9, 1, 7], [7, 9, 6, 3, 1, 8, 4, 5, 2]]
p.rollback
[[0, 0, 0, 8, 0, 0, 0, 0, 4], [0, 0, 0, 2, 7, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 6, 9, 0], [0, 0, 0, 0, 0, 1, 0, 7, 9], [7, 0, 0, 0, 0, 0, 0, 5, 0], [0, 0, 2, 0, 0, 3, 0, 0, 1], [8, 9, 7, 5, 0, 0, 0, 0, 0], [5, 4, 1, 0, 2, 0, 0, 0, 0], [2, 6, 3, 0, 0, 0, 4, 0, 0]]
I had to make a version of Solved on steroids in order to escape the recursion
Trying to understand that really.. hurts. But I like how you "tame" the errors like that lol
!mute @magic prairie
:incoming_envelope: :ok_hand: applied mute to @magic prairie until 2021-06-28 21:06 (59 minutes and 59 seconds).
Some days I'm like an errorslinger
Some days the errors sling me
You can tell I had issues with the tied attribute of cell
It can now solve any classical 9x9 sudoku with a unique solution
And a few without unique solutions 👀
It treats any number other than 1 to 9 as a contradiction, I.e. triggers SolutionError due to ""this line not being a valid permutation of range(1,10)" would be a more accurate message than the one used
But the code reads like "a not in permutations" where permutations is an object with a contains method
Which tests all elements occur exactly once and are mutually exclusive
Rather than generating the actual permutations
Just emulate the axioms that decide if an array is contained within
Just a correction I wanna make
def tie(self, other, number):
self.tied |= {number:other}
other.tied |= {number:self}
r = {*self.tied}&{*other.tied}
if len(r)==2:
for e in{*self,*other}:
if e not in r:[
self - e,
other - e
]
Pair reduction needs pairs to be identified, hence this method
Also the method that calls this also checks for pairs with two tied numbers and reduces the intersection of alignment
silly question, is there a way to one-line try and except block with gimmicks like eval/ using ;
been searching for a way with contextlib, no luck. stackoverflow had this exact same question but no valid answers
You're in the right channel for that
@nimble heron
heck yes! awesome
It's pretty much what you were (probably) trying with contextlib
yee but better..
why do my eyes hurt after coding?
that is a cursed theme
It's called 'llamas'
okay what about this one?
I have found a new way to golf python!
"It's all Greek to me"
ez clap.
Print function that prints text using print function?!
yes.
hi
I want a switch case default suite
Smaller than my one but with range(n) support
And decorator support
And base the case class on set
Bruh I've been doing this the hard way all along
!e ```py
class hack_wrapper:
def init(self, n=0):
import sys
self.l = sys._getframe(n + 1).f_locals
def call(self, f):
name = f.name
del f
def _b():
try:return name in builtins
except TypeError:return name in builtins.dict
def b(s):
try:return builtins[s]
except TypeError:return getattr(builtins,s)
if name in self.l:
rollback = self.l[name]
return rollback
elif _b():
return b(name)
else:return None
n = 69
@lambda a:a + 351
@hack_wrapper(0)
def n(a, b, c):raise RuntimeError
@hack_wrapper(0)
def print():
try:print()
except:print()
@print
@hack_wrapper(0)
def n(_, __, ___):raise some.other-error_thingy / idk
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
420
Nub
def print():
try:print()
except:print()```
that's the most intuitive piece of code I've seen all night
OCD: bool = True
python 3 broke this
works in python 2
isn't the bot running 3?
i meant the unhacked snippet
just those three lines, in python 3 they instantly crash
in python two they do the work, counting n×2**recursionlimit seconds
very inaccurate
huh cool
turns out we're already at level 3 for some reason
better do this```py
def sleep(ms):
for i,x in enumerate(bin(ms)[:1:-1], 12):
if x == '1':
setrecursionlimit(i)
try:work()
except:pass
start at 12
so it still won't work if called from anywhere other than top
shame
def sleep(ms):
depth = len(getouterframes(currentframe(1)))+11
for i,x in enumerate(bin(ms)[:1:-1], depth):
if x == '1':
setrecursionlimit(i)
try:work()
except:pass
Set recursion limit to 99999 and it becomes a great substitute for SystemExit, except the only codes you can get are 139, 147 or 0xc0000005
Negative a billion and a bit
!e ```py
import sys
def print(a=''):
try:sys.setrecursionlimit(99999);1//0
except:print()
print("Hello World!")
@floral meteor :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
Except you then throw that in the init of a new system exit class in case you broke or deleted the old one
My genius is awesome.
I'm still waiting for that switch case default suite.
Don't make me pull out the wrapper-core set-based pattern matching switch-case-default suite with logical notation, simultaneous switching and decorator support I've been working on.
...
Maybe I'm working myself too hard. One of these days I'm gonna give myself a stroke from programming too hard.
You can make a PR ToT
Be the change you want to see!
Also I have no idea what the fuck that means
switch case default suite ??/
Oh a switch case statement like in C
Today I am going to introduce a new concept for Python developers: typeclasses.It is a concept behind our new dry-python library called classes.
Intellectually I understand why print "yo" was deprecated to be replaced by print("yo") but my brain really struggles to accept that it's different from return/raise. To this day.
Funny how these things get hard-coded in your fingers.
I mean I definitely get the reason, print is a function call to stdout, return does some magic thing. Lets just be glad we dont have to write end at the end of functions 😄
That's just syntax, I like ruby for it.
😄 also so so grateful for not living in paren hell.
Why can't we "multiply" functions to fit the formal notation like sets follow?
And sets don't have invert :/
I had to make an invert with a not switch added to the set to invert all Boolean results from it pain in the ||tooshy||. Why can't we have an inverted set class that does all that?
What's the weirdest string you can think if that still counts as an identifier?
what do you mean identifier?
https://paste.pythondiscord.com/ucinezizaj.py actual NxN support
although im still resolving where i give it a 4x4 but only give it one point and it fills in about half of it and then dies
now I'm wondering what it's thinking about
I'm making a program that basically works only as a result of cursed identifiers
yes that is an executable python script, yes those are identifiers
ew, mac
use some unicode identifier equivalents (similar appearance) of this
+-------------+-------------+-------------+-------------+
| 13 12 | 6 7 | 4 | 1 5 |
| | 12 1 | 16 6 | 7 3 |
| 7 | 15 4 | 13 12 3 | 14 11 |
| 15 9 1 4 | 3 | 14 11 | 2 12 |
+-------------+-------------+-------------+-------------+
| 4 12 | | 2 11 1 | 9 8 |
| 5 13 | 1 | 10 16 7 | 11 4 15 |
| | 4 11 | 9 8 | 6 10 |
| 9 7 8 | | 14 | 12 |
+-------------+-------------+-------------+-------------+
| 8 15 | 7 | 9 5 | 12 1 |
| 13 | 11 | | 15 5 |
| 16 3 | 12 9 | 8 | 11 |
| 12 6 14 | 3 | | 7 9 |
+-------------+-------------+-------------+-------------+
| 7 | | 11 2 | 3 16 |
| 14 13 5 | 11 3 2 | 15 | 10 8 |
| 6 2 | 14 15 | 13 | 11 |
| 10 12 | 16 1 9 | 3 14 6 | 15 2 |
+-------------+-------------+-------------+-------------+
as the identifiers and make the class solve the soduku
!e ```py
lol3 = "hello"
lol3 is an identifier
print("var5".isidentifier())
print("var*5".isidentifier())
@lime bane :white_check_mark: Your eval job has completed with return code 0.
001 | True
002 | False
that's what i mean by identifier
the reason i'm asking is because i use the isidentifier method on a user input and i want to know what's the worst thing they can get away with
aio:=__import__('asyncio', globals(), locals(), ['coroutine']).coroutine
``` This defines aio as the asyncio coroutine function, so that I can use it like this:
```py
aio(lambda foo: bar())
``` In this way, I can execute coroutines inside lambda without awaiting them, now if I declare a variable as well like this:
```py
aio(lambda foo: (a:="b"), bar(a))
``` I get bar was not awaited, that means if I declare a variable then it can't await the function that needs to be awaited, how do I execute coroutines then?
most unicode characters that people are "used in words", including all of CJK, a bunch of alternate scripts for ascii characters (like blackboard bold), and a whole lot of combining diacritics (zalgo)
also, the first character of identifiers had slightly different rules to continuing characters, but mostly that just means you can't start with a "number" character or a modifier character
!pep 3131
asyncio.coroutine makes use of generators, so you can use yield from expression
!D yield
7.7. The yield statement
yield_stmt ::= yield_expression
``` A [`yield`](https://docs.python.org/3/reference/simple_stmts.html#yield) statement is semantically equivalent to a [yield expression](https://docs.python.org/3/reference/expressions.html#yieldexpr). The yield statement can be used to omit the parentheses that would otherwise be required in the equivalent yield expression statement. For example, the yield statements
```py
yield <expr>
yield from <expr>
``` are equivalent to the yield expression statements...
you can have something like ᵃ𝗯c𝓯𝒅𝙜𝕤𝚍gd𝙫ₓ𝓂𝔪𝙯𝚖𝒶𝓳𝐚𝐢𝓯𝒽ₐ𝒂u𝙖j𝓾𝑙𝕦𝐬𝘱𝖚𝔲𝗉𝕚𝘶𝔭𝑖ᵘₚj
!e ```py
a = "ᵃ𝗯c𝓯𝒅𝙜𝕤𝚍gd𝙫ₓ𝓂𝔪𝙯𝚖𝒶𝓳𝐚𝐢𝓯𝒽ₐ𝒂u𝙖j𝓾𝑙𝕦𝐬𝘱𝖚𝔲𝗉𝕚𝘶𝔭𝑖ᵘₚ"
print(a.isidentifier())
print(a)
@lime bane :white_check_mark: Your eval job has completed with return code 0.
001 | True
002 | ᵃ𝗯c𝓯𝒅𝙜𝕤𝚍gd𝙫ₓ𝓂𝔪𝙯𝚖𝒶𝓳𝐚𝐢𝓯𝒽ₐ𝒂u𝙖j𝓾𝑙𝕦𝐬𝘱𝖚𝔲𝗉𝕚𝘶𝔭𝑖ᵘₚ
But the question is now, are they different identifiers? Or do they have an ascii equivalent?
identifiers are equivalent if they NFKC-normalize to the same string
!docs unicodedata.normalize
unicodedata.normalize(form, unistr)```
Return the normal form *form* for the Unicode string *unistr*. Valid values for *form* are ‘NFC’, ‘NFKC’, ‘NFD’, and ‘NFKD’.
The Unicode standard defines various normalization forms of a Unicode string, based on the definition of canonical equivalence and compatibility equivalence. In Unicode, several characters can be expressed in various way. For example, the character U+00C7 (LATIN CAPITAL LETTER C WITH CEDILLA) can also be expressed as the sequence U+0043 (LATIN CAPITAL LETTER C) U+0327 (COMBINING CEDILLA).
so there's no KFC form?
25x25 expert level with impunity
https://paste.pythondiscord.com/ejutegufor.py added 25x25 test, show in above screenshot
Ok there is alot going on there...
Lol the program is excited about it
https://paste.pythondiscord.com/uzowoxoteg.py
just quickly fixed the rollback reset after the DFS
well actually its not really a dfs
it tries to solve it each iteration
if there's a SolutionError, next.
If nothing is raised, go deeper.
if there's a Solved, use UberSolved to rewind all the way to the top
and resetting with the solution
next on the TODO is a puzzle generator
however it cannot discern 'unique' solution, it just grabs the first thing that works
local variable mess
actual fixed
How long did it take to run?
A few seconds, it had to make some educated guesses
For 25x25 one run of the reduce method takes a full second
For a 4x4 you can't really tell if it guessed or solved properly it does both almost instantly
3x3 will thonk a bit for a solve if it has to guess, but otherwise is almost instantaneous for 0 levels of hypothesis
Higher, I haven't tested yet
See if you can find a 36x36 anywhere
It would use 26 letters and 10 digits
It would be a pain in the ||tooshy!|| to solve
@alpine flower did you just change your name?
I'm looking at it and then it moves
:))
walrus face tat
def update_board(self):
x,y,n = self.xyn
a,b,c = self.chars['board']
blink = self.terminal.blink()
d = self.chars['numbers'][9](blink if self.running else 0)
e = f"{a}{a.join(d*x)}{a}"
f = f"\n{c}{c.join(b*x)}{c}\n"
o = chars['other']
if not self.running():
self.board = f"""\x1b[0m\x1b[s
\x1b[{33-(n>0)}m{n}\x1b[0m bombs :)
\x1b[0;30,47;m{c}{c.join(b*x)}{c}
{f.join(e*y)}
{c}{c.join(b*x)}{c}\x1b[0m\x1b[u\n\x1b[A"""
print('\x1b[A'*50,end=self.board)
else:
flags = 0
for j,i in itertools.product(range(x),range(y)):
flags += self.clicked[i][j] == 2
self.board = f"\x1b[s\n\x1b[0m\x1b[s{n-flags} bombs :)\n\x1b[0;30,47;m{c}{c.join(b*x)}{c}\n"
self.board+= f.join([a+a.join([self._get(i,j,blink)for i in range(x)])+a for j in range(y)])
self.board+= f"\n{c}{c.join(b*x)}{c}\n"
trying not to hard code the board...
hinting at some new double colon thing in strings in 3.10?
also pycharm hates this script but it runs perfectly
PyCharm tries to guess certain syntaxes in strings (regex, str.format, SQL, etc), so it might have guessed one of those but failed.
well now it's telling me quotation marks are bad characters in annotations
Ah, it's probably ignoring those, since type annotations use those to avoid forward references etc breaking stuff. You should be using typing.Annotated?
I have a different annotation style to most people
i don't use it for type hints
this is worse
Yeah PyCharm is trying to parse it as a type hint.
it parses the booleans fine but not the literals
this board generation string is now colourful!
def generate(self):
import random
x,y,n = self.xyn
self.bombs, self.numbers = ([[0]*x]*y,)*2
while n:
r0, r1 = random.randint(0,x-1),random.randint(0,y-1)
if not self.bombs[r0][r1]:
n -= 1
self.bombs[r0][r1] = 1
for i,j,k,l in itertools.product(range(x),range(y),range(-1,2),range(-1,2)):
if(m:=i+k)in range(x)and(n:=j+l)in range(y):
self.numbers[j][i]+=self.bombs[n][m]
I feel like this might be able to be optimised
@floral meteor are you writing an esoteric minesweeper?
yes
in the terminal
but now im having fun with ESC-[-SEQ
while True:
if msvcrt.kbhit():
char = msvcrt.getch().decode('ANSI')
else:char='\1'
if char!='\1':print(end=char)
it's still enter-key buffered
instead of printing enter, enter buffers the stdout
so i still got the problem of having to press enter
and i also got the problem of arrow keys using this accented `a with àKàHàMàP instead of ^[[A ^[[B ^[[C ^[[D
reminds me of when i wrote this
[(e:=enumerate),(s:=(exit('Invalid Size')if(int(i)if(i:=input('Board Size (Min 3): ')).isnumeric()else 0)<3else int(i))),(b:=[[dict(d=__import__('random').choice([0]*s+[1]*(s//3)),n=0)for()in[()]*s]for()in[()]*s]),[[[t.update(n=t['n']+b[i+x][j+y]['d'])for y in[-1,0,1]for x in[-1,0,1]if all(map(lambda v:v>=0and v<len(r),[i+x,j+y]))]for j,t in e(r)]for i,r in e(b)],(f:=lambda x,y,v:(t:=b[x][y]).update(d=t['d']^v))(0,0,8),[*iter(lambda h='\x1b[':all(all((t['d']&1and t['d']&2)or t['d']&4for t in r)for r in b)or[(p:=print)(h+'2J'),[p('',*[h+f'{7if t["d"]&8else 0}m{t["n"]if t["d"]&4else"F"if t["d"]&2else "#"}{h}0m'for t in r])for r in b],p(f'\n{h}7mMove (wasd), Flag (f) or Clear (c):{h}0m '),[*[(lambda t,c,n:lambda:[f(*c,8),f(p,q,8)]if(p:=c[0]+n[0])>=0and p<len(b[0])and(q:=c[1]+n[1])>=0and q<len(b[0])else 0)(*(g:=lambda b:sorted([[(t,(i,j))for j,t in e(r)if t['d']&8]for i,r in e(b)])[-1][0])(b),n)for n in zip([-1,0,1,0],[0,-1,0,1])],lambda:f(*g(b)[1],2),lambda:exit('You Lose')if(t:=g(b))[0]['d']&1else f(*t[1],4)if t[0]['n']else(r:=lambda i,j,l:[[[f(*c,4),r(*c,l+[c])if t['n']==0and c not in l else 0]if not(t:=b[i+x][j+y])['d']&4and not t['d']&1else 0]for y in[0,1,-1]for x in[0,1,-1]if all(map(lambda v:v>=0and v<len(b[0]),(c:=(i+x,j+y))))])(*t[1],[]),p]['wasdfc'.find(__import__('sys').stdin.read(1))]()][0],1)],exit('You win')]```
i did go the easy route and use wasd instead of arrow keys
thanks, thats what I was looking for!
So when I look really close at this text in a screenshot, it's a very colorful white
Even more evident here
If it's compression, wouldn't it look more pixellated, and less colourful
your monitor does not emit pure white light
hello RE my old friend, I've come to talk with you again,
because a pattern softly matching, somehow includes a bunch of bs.
that is matched although, I have excluded pattern [^</a>] with my brain.
still remains...
Source:
rel="nofollow ugc" tabindex="1">'Let Them Eat Cake' Biden's Policy Putting 16 Cents Back In Your Pocket, Gas Prices Up 42%</a> A tonne of other unnecessary bullshit
Code:
re.findall(pattern=str(tabindex="1">(.[0-9a-zA-Z_].*[^</a>*])))
Output:
'Let Them Eat Cake' Biden's Policy Putting 16 Cents Back In Your Pocket, Gas Prices Up 42%</a> A tonne of other unnecessary bullshit
[^blah] excludes the individual characters of blah, not the whole thing
That's okay, I may just be the worst possible programmer.
if you need actual help consider the help channels
I think more than anything I just needed the obvious pointed out.
Trying that now...
The problem with being a fucking idiot, is you're barely cognizant of it until it's strongly pointed out.
Then this is the channel where you would not be the worst programmer
But that's a screenshot not a photo
it's a mix of dct & chrominance subsampling
it's called sub pixel rendering
you can turn it off on win and linux
it's just more precise to color some part of the letter red than say 30% grey
hm right
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Hey guys, I tried to scrape the information using BeautifulSoup from stackoverflow and display the most interesting questions. I executed the entire program, no errors but when i execute it in the terminal, it get an empty list, no information. Can anyone please look at it and tell me what is the bug pleases😥
Sounds like your search terms are jank
Pycharm might be better, it would ghost out variables you don't use like item
So your function names are almost sentences
Otherwise I would recommend splitting that up into more functions and turning the...
a = []
for yay in a:
if b(a): ...
...structure into a generator expression
Wait hol up
@lapis laurel why are you using enumerate?
You don't use item, but you don't use index for anything other than getting items.
What you want to do instead is iterate for link, view in zip(links, views)
Then you can pack (link.getText(),link.get('href',None),view.select('.mini-counts'))
into a return from a function
Then your testing if len(...)
But anything with len that's already it's bool condition so you're wasting CPU cycles
@floral meteor I tried it out, but then i get this last bug, which i think is the main one. But i don't seem to get any reference to what the bug is. can you check it out please??
uh why did you .replace?
that's an extremely descriptive error there telling you that you probably shouldn't use a .replace there
i'll use the original and see if i can fix it up
uh
you didn't paste it :/
that looks like it'll fit
```py
if True:
print ("Hello World!")
```
will format pasted text like such:
if True:
print ("Hello World!")
do that i don't wanna manually type from image :/
import requests
from bs4 import BeautifulSoup as BS
from pprint import pprint
RES = requests.get('https://stackoverflow.com/')
CHICKEN_STEW = BS(RES.text, 'html.parser')
LINKS = CHICKEN_STEW.select('.summary')
VIEWS = CHICKEN_STEW.select('.views')
def create(*lv):
pack = [(
l.getText(),
l.get('href',None),
v.select('.mini-counts')
)for l,v in zip(*lv)]
func = lambda f:int(f[0].getText().replace('title',''))
target = [{
'Question':t,
'link':h,
'views':func(f)
}for t,h,f in pack if f and func(f)>15]
return sorted(target, key=lambda q:q['views'], reverse=True)
pprint(create(LINKS, VIEWS))
not fixed yet tho
@floral meteor i did as you said and removed replace, but now again, i get an empty list
@floral meteor here it is
@floral meteor I have something you might be interested in ;)
Do you want to embed inline ascii art into your scripts?
class MyImage(Bitmap):
攟丶丶丶攟丶丶攟攟攟丶丶攟
攟丶丶丶攟丶丶丶攟丶丶丶攟
攟攟攟攟攟丶丶丶攟丶丶丶攟
攟丶丶丶攟丶丶丶攟丶丶丶丶
攟丶丶丶攟丶丶攟攟攟丶丶攟
# MyImage is now a `PIL.Image.Image` object
MyImage.show()
also with color :>
Noice
So build_class gets inputted a function and a name so what you must do is read the functions code or free variables
Hol up
init_subclass
I feel like that's involved
Otherwise there would be namerror
I don't get that code at all
So next, debugging.
You pretty much insert print statements after variable declarations and modifications, as well as something along the lines of what you expect it to be
__prepare__ and __new__ are the only things required (in the metaclass)
right, so it will have a direction
Ah prepare I forgot about that one lol
It's on GitHub as well if you want to dig through the source
So how do you metaclass through inheritance?
metaclasses are inherited by subclasses
so class Sub(Base) has the same metaclass as Base
Yeah now that's cool
unfortunately there are not enough CJK characters to fit every RGB color, let alone such that each character actually looks like its color
lol
so it's a bit lossy but still overall really nice
Here's a round trip for every RGB color
You can tell the darker colors are less distinct
it's smoothie like the wind
I tried to show what the ascii art would've looked like
!e ```py
class Call(metaclass=lambda*a:type(*a)()):...
class cout(Call):lt=print
cout < "epic!"
however
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | TypeError: Call() takes no arguments
my text renderer doesn't have small enough fonts
Wat
This is as far as I could zoom out (the text is wrapping)
wow there is thousands and thousands
for this conversion
it took a couple minutes to process lol
you have a very featured monitor I suposed
So why does this not work?
The metaclass __new__ has to return a class for it to be inheritable
Not sure why it's messed up there
Consider debugging not on discord lol
!e ```py
class Call(metaclass=lambda*a:type(*a)()):
init = print
class cout(Call):lt=print
cout < "epic!"
@floral meteor :x: Your eval job has completed with return code 1.
001 |
002 | cout (<__main__.Call object at 0x7fa2d6f45f40>,) {'__module__': '__main__', '__qualname__': 'cout', '__lt__': <built-in function print>}
003 | Traceback (most recent call last):
004 | File "<string>", line 6, in <module>
005 | TypeError: '<' not supported between instances of 'Call' and 'str'
you trying to convert a python code to C++ syntax?
I already done that earlier
that's sneaky
It's a backwards class regime
like a stunt .py file?
.summary and .views are empty
@floral meteor I updated this again with the help of another friend, but the questions it displays are not on the first page of stackoverflow
import requests
from bs4 import BeautifulSoup
import pprint
res = requests.get('https://stackoverflow.com/questions')
print(res)
soup = BeautifulSoup(res.text, 'html.parser')
questions = soup.select('.summary')
views = soup.select('.views')
def sort_qs_by_views(question_list):
return sorted(question_list, key=lambda k: k['views'], reverse=True)
def create_custom_question_list(questions, views):
st_ov = []
for idx, item in enumerate(questions):
# getting rid of extra info in '.summary' that we don't need by selecting
# the ".question-hyperlink" (sub)class inside '.summary'
title = item.select_one(".question-hyperlink").getText()
# grabbing the links (which all start with: <a href="/questions/11227809/why-blah-blah?,
# so I added 'https://stackoverflow.com' for them to be interactive)
href = 'https://stackoverflow.com' + \
item.select_one(".question-hyperlink").get('href', None)
# '.views' looks like this (<div class="views" title="8 views">8 views</div>), so
# to strip it of everything but "X view(s)" we grab
# only the ['title'] attribute
view = views[idx].attrs['title']
if len(view):
# getting rid of the word "view(s)" so that only a number remains
points = view.replace("s", '').replace(" view", '')
if int(points) > 5:
st_ov.append(
{'title': title, 'link': href, 'views': int(points)})
return sort_qs_by_views(st_ov)
pprint.pprint(create_custom_question_list(questions, views))
all right you weirdos, i'm trying to wrap context managers around a function and call that function later
let's say i have this code:
a = 1
@contextmanager
def foo():
global a
a += 1
print("entered")
yield
a -= 1
print("exited")
def bar(f):
with foo():
yield lambda: f()
i'm trying to wrap as many layers around lambda: print(a) as i can, and then successfully exit all of them as well
so far i'm here:
>>> g = bar(lambda: print(a))
>>> g = bar(next(g))
entered
>>> g = bar(next(g))
entered
# ... some more times...
>>> next(g)()
7
>>> next(g)()
exited
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> a
6
i feel like i'm really close, but i'm missing exiting
maybe if i had an exits list of all the previous generators...?
uhh
what exactly you trying to do im trying to wrap my head around your goal
i.e. what's the expected output?
@lapis laurel the problem is you need headers with your requests to authenticate because all those fields you're searching for are only available when you're logged in
and in order to be logged in, you need to be sending authorisation tokens with each request
give this a look: https://api.stackexchange.com/docs
ok now this is just funny.
list index when setting an attribute.
!e
class ostream():
def __init__(self, val):
self.val = val
def __lshift__(self, txt):
print(txt, end="")
return ostream(txt)
def __repr__(self):
return ""
def __str__(self):
return ""
def __add__(self, other):
return self.val + other
class std:
class cout:
@staticmethod
def __lshift__(txt):
print(txt, end="")
return ostream(txt)
endl = "\n"
# TIME FOR SUM C++
std.cout() << "Hello, " << "world!" << std.endl;
@flat zodiac :white_check_mark: Your eval job has completed with return code 0.
Hello, world!
!e
class ostream():
def init(self, val):
self.val = val
def __lshift__(self, txt):
print(txt, end="")
return ostream(txt)
def __repr__(self):
return ""
def __str__(self):
return ""
def __add__(self, other):
return self.val + other
class std:
class cout:
@staticmethod
def lshift(txt):
print(txt, end="")
return ostream(txt)
endl = "\n"
TIME FOR SUM C++
std.cout() << "Hello, " << "world!" << std.endl;
!e
class ostream():
def init(self, val):
self.val = val
def __lshift__(self, txt):
print(txt, end="")
return ostream(txt)
def __repr__(self):
return ""
def __str__(self):
return ""
def __add__(self, other):
return self.val + other
class std:
class cout:
@staticmethod
def lshift(txt):
print(txt, end="")
return ostream(txt)
endl = "\n"
TIME FOR SUM C++
std.cout() << "Hello, " << "world!" << std.endl;
@north current :white_check_mark: Your eval job has completed with return code 0.
Hello, world!
i made it
@flat zodiac 👌
@flat zodiac 10/10
!e
class ostream():
def init(self, val):
self.val = val
def __lshift__(self, txt):
print(txt, end="")
return ostream(txt)
def __repr__(self):
return ""
def __str__(self):
return ""
def __add__(self, other):
return self.val + other
class std:
class cout:
@staticmethod
def lshift(txt):
print(txt, end="")
return ostream(txt)
endl = "\n"
TIME FOR SUM C++
std.cout() << "Hello, " << "world!" << std.endl;
@north current :white_check_mark: Your eval job has completed with return code 0.
Hello, world!
```py
code
!e ```py
metamaker = (lambda meta, cls: ( lambda: [ (dict_.pop(es, None) for es in dict_.get("slots", tuple())) if [None for [globals()["dict_"]] in [[dict(cls.dict)]]][0] is None else None, [None for [globals()["dict_"]["metaclass"]] in [[meta]]], [None for [globals()["dict"]["wrapped"]] in [[cls]]], meta(str(cls.name), tuple(cls.bases), dict), ][-1]))
printf = lambda format_string, *args: print(format_string,end="") if not args else print(format_string % args,end="")
main = metamaker(type("b", (type,), {"call": lambda self, : {None}}), type("", (object,), {}))()
int = metamaker(type("a", (type,), {"sub": lambda self2, : {None} if isinstance(, set) else [None for [globals()[.split("=")[0]]] in [[import('builtins').int(_.split("=")[1])]]][0]}), type("a", (object,), {}))()
void = None
return_0 = None
int-main(void)-{
printf("Hello, World!\n"),
int-"num1=2",
int-"num2=3",
printf("%d + %d = %d\n", num1, num2, num1+num2),
return_0
}```
@tribal moon :white_check_mark: Your eval job has completed with return code 0.
001 | Hello, World!
002 | 2 + 3 = 5
yay!
!code please put code in codeblocks
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
I once made both input and output and the initialization was 3 lines
If you're gonna one line, they look better without spaces:
- after commas and colons
- between letters and brackets
- between letters and other punctuation
- between punctuation
- around operators, especially assignment
i am BACK, sorry for the delay. In a spotty internet place
@floral meteor to answer your question, i guess i'm trying to programmatically apply contexts to a function?
i'm writing an adaptable contextual logger, which i am hoping will be able to have a list of adapters that will each apply its context to a function, then run the function after it's all buttoned up
eh, it's not much of a big priority, just tryna replicate that thing that I did
something like this:
contextuallogger = ContextualLogger(
[Adapter1(), Adapter2()]
)
contextuallogger.log("message", func)
# the above would produce something like this:
with adapter1.context:
with adapter2.context:
func()
... so i've got something actually working
i'll post the link to the change once i merge it, in case anyone wants to see
while 1:
if msvcrt.kbhit():
char = msvcrt.getch().decode('ANSI')
else:char='\1'
if char!='\1':
print(end=char)
if char=='\r':print()
then type Esc[32myeetEnter
then you can literally type any ANSI escape sequence.
But it's still enter buffered and prints '\r' on enter but not '\n'
hence the extra code to convert '\r' to '\n'
!e ```py
x, y = 5, 8
a, b = [[[(0x00for 0in(x,y))-15for __ in range(x)]for _ in range(y)]for ___ in range(2)]
print(a, b)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
"copy multiplication of lists", with some extra obfuscation for impact :)
heh
this should be blue screens:
golfing: that art of turning
if char=='w':
self.move(w=1)
if char=='a':
self.move(a=1)
if char=='s':
self.move(s=1)
if char=='d':
self.move(d=1)
into
if char in'wasd':self.move(**{char:1})
and then ```py
if char in'\t\b':
self.right_click(i, j)
if char in' \r':
self.select(i, j)
if char in'wasd':
self.move(**{char:1})
if char=='\x1b':
self.DIE(True)
if char in'à\0':
self.terminal.log('Please use wasd, space, or tab; or press ESC to quit')
self.update_board()
into
```py
{
1:lambda:0,
char in'\t\b':lambda:self.right_click(i,j),
char in' \r':lambda:self.select(i,j),
char in'wasd':lambda:self.move(**{char:1}),
char=='\x1b':lambda:self.DIE(True),
char in'à\0':lambda:self.terminal.log('Please use wasd, space, or tab; or press ESC to quit')
}[1]()or self.update_board()
5d now that sounds good already
I'm trying to craft extremely intricate tests on multidbs. it's fine.
yeah, might be 6D, but that's physics for you
Matplotlib can do higher dimensions?
I dunno what he's trying to do. I can keep up until 4, then I'm out
Your 2d screen can do higher dimensions?
it's "in" the computer
If it was continuous data I'd bugger it and not show it on screen until a specific point is asked for.
Otherwise, it can be easily displayed in 2d, any dimensions.
Although even number dimensions are easier in 2d and odd easier in 3d.
Just go for a "grid of grids of numbers or colors or brightness" approach
Although 6d is grid of grids of grids of data points
And I'm done lunch break cya tomorrow this is intriguing
he's done the 2+1D visualisation and he'll probably be breaking it in to 3+3D but this is just an aid to the theory for a research paper, would be nice to know if there's some better recommendations than matplotlib for the domain though
Well since you're asking in #esoteric-python the recommendation is use 6D rendering with raw terminal using ansi escape sequences for terminal control and unicode or ascii art for higher resolution
Also use 6d ray tracing with a light source coming from a certain direction for extra effect
But for actual, forget using the third dimension for visualisation it won't help much
Grid of grids of grids
I use grid of grids to make 4d minesweeper
You can potentially have as many dimensions as you like in minesweeper, but you'll need bigger screens and smaller mine panels
I'd need to know what's being visualised to come up with a way to visualise it else I can only guess.
Although cos there's 3 colour channels technically the data stored would be 5 dimensional
with a tetrachromatic color vision + monitor, you can add an extra dimension :)
Hello friends! Not sure if this is the place to put this, it's more of "Game Integration" but I'll give it a shot. I want to hook into a game called League of Legends, and ideally run 2 instanced on my pc. 1 being GUI, the other being CL. Basically I want to play 2 champions at once. Is this possible? Am I even in the right place?
That's not really related to Python
You'd be better off asking in an ot-channel or even better a LoL server
Not directly, but I want it to be coded in python. Everything I've seen is just "run 2 pc's at once, duh" type of deal
Well this isn't really the right server to be asking in
You'd be much better off finding a LoL server
You can always try asking in an ot-channel but not sure anyone will be able to help
Off-topic channels
There are three off-topic channels:
• #ot0-psvm’s-eternal-disapproval
• #ot1-perplexing-regexing
• #ot2-never-nester’s-nightmare
Their names change randomly every 24 hours, but you can always find them under the OFF-TOPIC/GENERAL category in the channel list.
Please read our off-topic etiquette before participating in conversations.
I guess a more specific question would be "What's the best way to run a GUI app in a CLI instance and be able to give input by hooking into the game"
Still not really relevant to this server
Certainly not this channel
I'm not trying to be argumentative, but I feel like if anything this would be the place to put it? "Esoteric: intended for or likely to be understood by only a small number of people with a specialized knowledge or interest"
I feel this would be one of those things understood by a select few and more specifically with the interest in the game aspect, but I'll go elsewhere
Read the topic
This is the kinda stuff that belongs here
It's mostly code-gore rather than the true dictionary definition of "esoteric"
Aaah, my mistake, I hadn't looked there
Things like implementing c++ syntax into python
I just googled "esoteric" and appended python to it
Yeah, nw
I posted it in the "game-dev" as well, although it also isn't exactly a 1:1 matchup. And I don't want to post in a help channel since it's just a thought experiment at this point and not a "I have X problem in Y code, can someone help"
Is here sb who wants to try this one:
you need to print following into the console:
name: Delfini,
hobby: guitare,
ID: 798556932151181363
```And the challange is, to make it as unreadable as possible, in as less lines as possible 😂
Olivia you were very nice too me, have an awesome time
I mean theres always exec(bytes('牰湩⡴渧浡㩥䐠汥楦楮尬桮扯祢›畧瑩牡ⱥ湜䑉›㤷㔸㘵㌹ㄲㄵ㠱㌱㌶⤧','u16')[2:])
but thats kind of cheating
I'm just over here needlessly contemplating that
#this:
y=[];y[:]=range(20)
#means the same as this:
x=list(range(20))```
but the first option is so much more esoteric and side effect prone. but the second one is shorter.
and `L=list` might be even shorter and more obfuscated, if you're calling it enough. It also has the advantage of being compatible with deeply nested function calls in single line, as it doesn't need the assignment operator, etc.
I "invented" a new way to do string literals hehe
class S():
def __init__(self,s=""):self.s=s
def __repr__(self): return self.s
def __getattr__(self,s):return self.__class__(self.s+" "+s if self.s else s)
s=S()
print(s.Hello.world.did.you.know.python.supports.unquoted.strings)
print(s.𝓮𝓿𝓮𝓷.𝓯𝓪𝓷𝓬𝔂.𝓸𝓷𝓮𝓼)
print(s.𝕨𝕙𝕪.𝕕𝕚𝕕.𝕥𝕙𝕖𝕪.𝕕𝕖𝕤𝕚𝕘𝕟.𝕥𝕙𝕖.𝕝𝕒𝕟𝕘𝕦𝕒𝕘𝕖.𝕝𝕚𝕜𝕖.𝕥𝕙𝕚𝕤)
(the weird unicode fonts get normalised back into standard characters)
Alright I'm gonna try to figure out metaclass inheritance
!e ```py
class A(metaclass=lambda*a:print(*a)or type(*a)()):
init = print
class B(A):
lt = print
try:B < 1
except:B() < 2
@floral meteor :x: Your eval job has completed with return code 1.
001 | A () {'__module__': '__main__', '__qualname__': 'A', '__init__': <built-in function print>}
002 |
003 | B (<__main__.A object at 0x7ff06c21be50>,) {'__module__': '__main__', '__qualname__': 'B', '__lt__': <built-in function print>}
004 | Traceback (most recent call last):
005 | File "<string>", line 5, in <module>
006 | TypeError: '<' not supported between instances of 'A' and 'int'
007 |
008 | During handling of the above exception, another exception occurred:
009 |
010 | Traceback (most recent call last):
011 | File "<string>", line 6, in <module>
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/hovamidawa.txt?noredirect
I figured it out
So B is an instance of A somehow.
There's nothing classy happening
And it doesn't bind methods
So how could I abuse this behaviour?
Ok this is harder than I thought it would be
!e ```py
f = lambda*á:type(*á)()
class A(metaclass=f):
new = lambda c:f(c)
class B(A):
getattr = lambda s,a:print(a,end=' ')or s
invert = lambda s:print('\b!')
~B.Hello.World
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | File "<string>", line 1, in <lambda>
004 | File "<string>", line 3, in <lambda>
005 | File "<string>", line 1, in <lambda>
006 | TypeError: type() takes 1 or 3 arguments
Wot
uh?
Are there any good "macro"-y libraries that can help me generate nice ASTs for some dynamic programming stuff? Thinking of equivalent to things like Rust macros or Template Haskell, basically trying to do stuff that would involve being very sensitive around string whitespace etc and building ASTs by hand is getting a bit painful
the python standard library just uses exec(some_template.format(stuff)) or fstrings
yeah, just that would be very tedious in my case (especially with indentation, etc...). I'll write out some helpers for my own needs
how come
__func_body = """\
def {name}{paramslist}:
if {obj} is None:
if not TurtleScreen._RUNNING:
TurtleScreen._RUNNING = True
raise Terminator
{obj} = {init}
try:
return {obj}.{name}{argslist}
except TK.TclError:
if not TurtleScreen._RUNNING:
TurtleScreen._RUNNING = True
raise Terminator
raise
"""
defstr = __func_body.format(obj=obj, init=init, name=methodname,
paramslist=pl1, argslist=pl2)
exec(defstr, globals())
```turtle does this and it seems no more tedious than any other approach I can think of
@lofty totem^
I'm basically trying to do a transpiler from a template thing into Python, so I'll end up with a good amount of embedded blocks, and there's like the tabs... well I'll think about this over dinner a bit
What is esoteric python?
weird stuff
like this sum function py [x for x in [0] for i in lst for x in [x+i]][-1]
Ah, that would indeed make things annoying
Yeah, you will need helper functions then
What's the template thing look like and what's an example of expected output?
I eat io for breakfast
alright i have my mobile office set up.
although some tosser nicked my number plates so its not mobile nummore
macro-y libraries, AST generation, dynamic programming, sensitive to string whitespace, automated
alright i'll see what i can do, but code density is proportional to coffee consumption, so you're likely to see a wide range of two different styles
Figure 1: I coded move at the start of the cup of coffee, and I coded start at the end of the cup of coffee
and for a bonus, in case I haven't told you yet, my favourite exit error code: ```nim
Process finished with exit code -1073741819 (0xC0000005)
okay why tf does this even...
assert len(iterable)==0
-->
() = iterable
alright, I bet y'all never seen center aligned code
!e now for an aussie classic ```py
@lambda c:c()
class bugger:
def setattr(self, *whatev):
pass
def getattr(self, *whatev):
return None
class important_stuff:
c = 10
def iter(self):
return self
def next(self):
if not self.c:raise StopIteration
self.c -= 1
print (self.c)
a = [0 for bugger.it in range(10)]
print(a)
b = [bugger.this for bugger.that in important_stuff()]
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
002 | 9
003 | 8
004 | 7
005 | 6
006 | 5
007 | 4
008 | 3
009 | 2
010 | 1
011 | 0
much more elegant than underscores
!e or a more official version:
@lambda c:c()
class bugger:
__setattr__, __getattribute__, __setitem__, __getitem__ = (lambda*a:None,)*4
__iter__ = lambda*a:iter(())
bugger.it = [bugger.this for bugger['that'] in bugger]
@floral meteor :warning: Your eval job has completed with return code 0.
[No output]
okay back to this, which code block is better?
eh i picked the second one
the method name generate makes a good title for this paragraph block
now I'm trying to figure out where in life I went wrong
and why pressing the s key goes left
okay now it works
nuuuuu
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
im doing something kind of weird idk if that'd count as esoteric python
C++ in python
cout in python
class cout:
def __init__(self):
pass
def __lshift__(self,value):
print(value)
cout = cout()
print("C++ in python")
cout << "Hello World";```
@plucky light :white_check_mark: Your eval job has completed with return code 0.
001 | C++ in python
002 | Hello World
class cin:
def __init__(self):
pass
def __rshift__(self,a):
global var
var = input()
cin = cin()
var = ""
print("C++ in python")
cin >> var;
print(var)
cin in python
thoughts?
the "var" is hardcoded
i am not sure of any other way of doing it
pass var as a string, and add it to the globals
hm but that wouldn't be a variable u are passing
if i can get the name of teh variable passed , i can use exec
!e
class CreateVar:
def __init__(self, varname, value):
globals()[varname] = value
CreateVar("a", 10)
print(a)
@flat zodiac :white_check_mark: Your eval job has completed with return code 0.
10
ah didn't know about this thanks
locals() wont work because it will go off-scope outside the class
speaking of scopes...
!e
print(globals())
print()
print(locals())
@flat zodiac :white_check_mark: Your eval job has completed with return code 0.
001 | {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}
002 |
003 | {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}
@flat zodiac why is this not working tho
dunno
!e
class cin:
def __init__(self):
pass
def __rshift__(self,var):
globals()[var] = "Helllo World"
cin = cin()
b = "asdasd"
print("C++ in python")
cin >> b;
print(b)
@flat zodiac :white_check_mark: Your eval job has completed with return code 0.
001 | C++ in python
002 | asdasd
ahhh
you also need to implement cout
hint: you need to create two classes for cout (for it to work with multiple variables)
decorator?
yeah, hang on
alright
!e
@lambda a:a()
class myclass:
def __init__(self):
print("a")
# myclass is now an instance
myclass.__init__()
@flat zodiac :white_check_mark: Your eval job has completed with return code 0.
001 | a
002 | a
well, decorators ARE functions
ig yes
you could...
!e
@lambda a: 929
class anotherclass:
def __init__(self):
print("init??")
print(bin(a)[2:])
!e
@lambda a: 929
class anotherclass:
def __init__(self):
print("init??")
print(bin(anotherclass)[2:])
@flat zodiac :white_check_mark: Your eval job has completed with return code 0.
1110100001
theeeere we go
oh wow
you can run a bin function on an int, which will return the binary representation of the number
!e
print(bin(16))
@flat zodiac :white_check_mark: Your eval job has completed with return code 0.
0b10000
!e
@lambda a: 929
class anotherclass:
def __init__(self):
print("init??")
print(type(anotherclass))```
@plucky light :white_check_mark: Your eval job has completed with return code 0.
<class 'int'>
ah wonderful
and the __init__ method doesnt work, because we never instantiated the class
basically the lambda gets the class, throws it away, and replaces it with a brand new number 929
!e
print(2e50)
@flat zodiac :white_check_mark: Your eval job has completed with return code 0.
2e+50
!e
lst = []
i = 0
while i < 100000:
lst.append(i)
i += 1
@flat zodiac :warning: Your eval job has completed with return code 0.
[No output]
wait
!e
lst = []
i = 0
while i < 100000000:
lst.append(i)
i += 1
print(len(lst), lst)
@flat zodiac :warning: Your eval job timed out or ran out of memory.
[No output]
lol
well done!
!e
class U(metaclass=map):
def __iter__(self):
yield from range(10)
print('the list is', list(U))
@proper vault :white_check_mark: Your eval job has completed with return code 0.
the list is []
interesting map doesn't check if its func is callable
it is impossible to check if an object is callable without trying to call it
Is checking hasattr of __call__ not enough?
!e
print(hasattr(lambda: 0, "__call__"))
@fathom echo :white_check_mark: Your eval job has completed with return code 0.
True
Don't have examples rn, but IIRC there were some cases where that didn't work
if it is a descriptor i dont think that works?
callable(fn)?
This answer seems relevant
https://stackoverflow.com/a/18704793
tl;dr only callable or direct ctypes access will work properly
callable returning True doesn't mean the object can actually be called, but it certainly cannot be called if callable returns False
C++ initializes with int var
Therefore, use that to modify globals
oh ok hm i will look into it later
(lambda:0).class
Oh I see
I used getattr in my solution
!e ```py
x = lambda:0
print(hasattr(x,'call')and hasattr(x.call,'call'))
for i in range(8):
x=x.call
print(x, id(x))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | True
002 | <method-wrapper '__call__' of function object at 0x7fc226fd9040> 140471854243552
003 | <method-wrapper '__call__' of method-wrapper object at 0x7fc226f91ee0> 140471854243360
004 | <method-wrapper '__call__' of method-wrapper object at 0x7fc226f91e20> 140471854243312
005 | <method-wrapper '__call__' of method-wrapper object at 0x7fc226f91df0> 140471854243264
006 | <method-wrapper '__call__' of method-wrapper object at 0x7fc226f91dc0> 140471854241104
007 | <method-wrapper '__call__' of method-wrapper object at 0x7fc226f91550> 140471854241056
008 | <method-wrapper '__call__' of method-wrapper object at 0x7fc226f91520> 140471854240960
009 | <method-wrapper '__call__' of method-wrapper object at 0x7fc226f914c0> 140471854240384
Uh
That is unexpected behavior
Does that go all the way down to id 0?
how much memory is each function take up with that one method?
The method wrappers are created on attribute access
weekly code golf competition starts at 1:00pm CDT tomorrow https://emkc.org/contests
python is the most hotly contested language usually
What is jelly? It looks esoteric
Jelly at the top there does that mean they allow esolangs? Or is that some sort of legit code for big brain programmers?
can't be any more big brain than APL
Or maybe chef...
Someone bake me a hello world soufflé
;)
Although naturally I end up writing up the interpreter myself, and even a code generator to actually code in it
So I guess I'll do that now.
After a play a few rounds of this terminal minesweeper I just made.
jelly is a golf lang written in python I think
you can see the supported langs by going to past due submission tab of any contest and looking at the drop down
other golf langs supported are golfscript, osabie, pyth, and a few others
im winning ^__^ the python champ hasn't competed yet tho
what are you winning in?
Alright imma suck down a 4-shot frappe and see if i can give you bit of competition
idk I've never done a brainfuck sol
or any brainfuck programs
you could join the emkc discord and ask
i'll probably win by being the only brainfuck solution
lol yep
XDDD
sometimes I do the esolangs nobody else does like pyth and golfscript
now i have to learn how to actual brainfuck
haha gl might be harder than beating lyndon at python >_>
I should have won last week but I forgot == short circuits
I won the week before that
i've been more into the theory and metacoding than coding in the brainfuck itself
lol you got rekt by lyndon
yeah they are pretty good at golf
sometimes I manage to beat thema gain when they inevitably get a smaller program
I can import sys to get argv right? or should i input?
you cna use input or open(0)
you can also print with input if it's a str
open(0) is a rly neat trick the ppl who knew about it before we did blew us out of the water that week
it used to be args only but it's stdin as well now
whole thing, like if the args were a text file with lines seperated by newlines
excellent
hey
heya
for anyone who wants to compete we're talking about this https://emkc.org/contests/43/password-policy
so can i ask questions here ?
heyayaya
only if it's about stuff in the topic
or esoteric
esoteric is okay
so i have to ask there
yeah discord.py stuff go in #discord-bots
if it's a general discussion provoking question
otherwise go to #❓|how-to-get-help
if you need help with specific code
unless you're like me and make bots look like they were coded in hellfire and brimstone
in which case here is okay for bots ;)
also, another hint, open(0) is also an iterator
like any multiline open
i've only been pythoning for 11 months
this is a good resource
k
okay i think i have a nice short sweet first line
nah ill change b to p
can you exit something other than an integer?
ive always exited integers
I don't think exit print works anymore
it used to but recently I've tried ti and it didn't work
lol code never rly works it just pretends for long enough to make you complacent
yea
and then you test it
and boom
error
is like
yeayea sure this code is perfect
you test the command
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "test" is not found
sigh....
but well
it works now
so im happy
ill probably get 1k more errors
!e ```py
a = [-2, -1, 0, 1, 2]
print(sum(c for c in a if c<0))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
-3
woo saved 5 bytes
still far from lyndon
doubt this strategy will work
but I did something pretty nea thaha I hope this works
!e ```py
print(*(ord(i)for i in'09AZaz'))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
48 57 65 90 97 122
fair enough i'll give this one a shot
now it's beautiful though I am sad that this strategy probably won't win cuz damn it's esoteric
you will see on wednesday haha
what I do is make a text doc with every test case
and iterate through them testing each one
to see which one it's failing on
here are all the test cases in order
LENGTH>100
EngineerMan is my favourite YouTuber, and therefore belongs in my very long password! Last I recalled he has >400k subscribers :)
UPPERCASE==LOWERCASE
Bones is my FAVOURITE h3r0
SPECIAL==0
Hello World!
LENGTH>8;SPECIAL>0;UPPERCASE<LOWERCASE
Hello World!
NUMERICAL==UPPERCASE
H3l10 WORLD!
LENGTH==4;UPPERCASE==1;LOWERCASE==1;NUMERICAL==1;SPECIAL==1
HexF
LENGTH==4;UPPERCASE==1;LOWERCASE==1;NUMERICAL==1;SPECIAL==1
Hi 5
LENGTH<500;LOWERCASE>7;NUMERICAL<3;UPPERCASE>7;SPECIAL<5
fraz and Gotoro are our newest community heros!
I just make the variables and then eval the conditions
yeah I am still doing that with mine
but
fancy lol
there are no longer hidden test cases so you can debug with the visible ones
oh
false and true need to be lowercase
they are
kk
i tried debugging i got oserror with open(0)
generator doesn't have a len
no it doesn't u gotta unpack that shizz
haha yeah I hate that
weirdly enough it doesn't even need to be parenthesized ont he right side of a for loop header
I should have won last week for figuring that out but I was dumb and forgot == short circuits
210 bytes
aha you can see me coming for ya on the leaderboard
like in Jaws
dadum
dadum
dadum dadum dadum
haha I was hoping for more competition
other than lyndon dominating
tho sometimes I beat them after they beat me
hey i can see lyndon and me at the same time without scrolling now
dadumdadumdadum
gl hehe
noice
I think I can shave a couple more bytes probably
gonna give this week to lyndon just cuz I like my sol so much
it's staying
193
aw i thought id try the utf-16 trick that made it go up to 300 lol
I decided to throw a funny
But the website crashed chrome
yeah it got switched from chars to bytes when someone did that
why does map not work with assignment unpacking?
it's very annoying
a,b,c,d = map(...)
Expected 4 arguments, got 0
I have reached the eye twitching stage of insanity
it does work but u can't assign it to two diff unpackings since it's exhausted
!e
*e, _ = map(str,'456')
print(e)
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
['4', '5']
!e
*e, _ =y,t,u= map(str,'456')
print(e)
@simple crystal :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: not enough values to unpack (expected 3, got 0)
it works if i use a star and a comma
but then it's the same size as my previous solution
haha I ran into the same problem
saved a byte
169 😉
beating lyndon is in sight now tho damn this program is concise
the length of the name of str.translate is bothering me
haha yep, I found a workaround but it is still too long to use
welcome to code golf where any method or function over 3 chars is like WHYYYY
pycharm decided to freeze. I can't even terminate it
alright i tried the opposite of Don't Repeat Yourself then eval("...".replace(...)) but that didn't work
I think i'll keep mine there cos len works for the wrong reason
It says my program doesn't pass the test cases but it does?
What format is the output supposed to be!
char=='à':lambda:self.move(**{{'K':'a','H':'w','M':'d','P':'s'}[msvcrt.getch().decode('ANSI')]:1}),
completely unrelated, terminal minesweeper now supports arrow keys
oh and has red numbers counting up
lol
I'm just refining the user experience for this game of minesweeper in the terminal
so, uh, how do I solve this? ;-;
There's no way I'm squeezing 14 more bytes out of this!
that's how i feel about a lot more bytes
12 more now
I think i'm staying at 187
saved a really cursed byte
lol
guaranteed first click has no bombs immediately next it or on it
i just noticed my watch reset and its been like that 7 hours
smh
gl i'll sleep on this challenge
@earnest wing gj you are doin really well
Thanks! I'll see if I can implement a couple ideas once I get back to my laptop
I gave a theoretical 7 bytes that depend on the semantics of python and a certain battery
I tied with lyndon
162 bytes
if their solution looks like mine I will be thoroughly impressed they got it so fast haha
I'm excited to see the sols on wednesday
tryin like hell to win but I think my sol is thoroughly golfed
okay this seems to be a personal cap I can't seem to progress
very fun challenge though I can't wait for the next
There's a mine directly above the 2 on the far right, and the three to the left of the top-left 1 are all clear. To the direct left of the bottom 2 is a mine.
Hol up I thought clearing the three next to the top left one was only known if that first move was a safe spot not a nuke
Ooh I see
So because of the 1 neighboring a two pattern placing the first nuke at above top right 2, the second nuke has two options both touching the one making those three safe, which leaves one option for the 1.
The journey is more important than the destination ;)
Alright I'm gonna implement an optional behavior where flagging a bomb removes it
But flagging a safe spot blows you up
IVXLCDM are all the Roman numerals right?
!e I just need to see... ```py
print(*map(ord,'IVXLCDM'))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
73 86 88 76 67 68 77
VIII
nah i was just cycling, it's hard to use pc while on bike
someone posted this for the golf challenge 🤔
the python one
and this is supposed to print hello world?
It's a 13th degree polynomial evaluated at x=0,1,2,...,13 and rounded to the nearest integer
or, no
slightly different
x=0,...,11
I wish I'd read more Orwell. Now I learn he was a Jelly programmer.
O_O
The guy was mad fucked up, but yeah his books were really really good.
What is 4D minesweeper
minesweeper in 4 dimensions
it makes 2 dimensional minesweeper look easy.
so the board would look something like ```
.... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....
.... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....
.... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....
.... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....
.... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....
.... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....
.... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....
.... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....
.... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....
.... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....
.... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....
.... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....
.... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....
.... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....
.... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....
.... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....
hang on that might be 5d
you get the idea. More than 2 dimensions of data gotta fit on the screen
so different sized partition lines
!e
for all people who dislike += mutating the list:
class _:
def __init__(self, iterable):
self.iterable = iterable
def __radd__(self, other):
return other + self.iterable
def __ror__(self, other):
return other | self.iterable
xs = [1, 2, 3]
ys = xs
xs += _([4, 5])
print(f"{xs=}")
print(f"{ys=}")
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 | xs=[1, 2, 3, 4, 5]
002 | ys=[1, 2, 3]
I have the exact same traceback for every error this thing raises ;)
I think this belongs in the poor coding practices channel ;)
!e ```py
def brainfuck(code,input=input):
from collections import defaultdict as d
from ctypes import py_object as j
hack=lambda v:j.from_address(v)
l=input==builtins.input
if not l:input=lambda i=1:input.pop(i-1)
a,o=d(int),''
i=p=t=0
gulag = [hack(id(IndexError)).value]
hack(id(builtins.IndexError)).value=StopIteration
for c in iter(lambda:code[p],None):
def __0(i,_):
a[i]+=1
a[i]%=256
return i,,
def __1(i,*):
a[i]-=1
a[i]%=256
return i,_,
def __2(i,o):
o+=chr(a[i])
return i,o,0
def __3(i,):
a[i]+=ord(input(1))%256
return i,*,
f = [__0,__1,
lambda i,_:(i+1,),
lambda i,*:(i-1,),
__2,__3,
lambda *:(,not a[i]),
lambda *:(_,-bool(a[i])),lambda:][chars.find(c)]
if t:
if c=='[':t+=1
if c==']':t-=1
else:
i,o,t = f(i,o)
p += 1 - 2*(t<0)
hack(id(IndexError)).value = gulag.pop(0)
return o,int(p!=len(code))
print(brainfuck('++++++++++[>+++>+++++++>++++++++>++++++++++>+++++++++++<<<<<-]>>++.-->>+.+++++++..-------->+This is a comment.-<<<<++.-->>+++++++.------->>+.+++.----<++++++++.--------.<<<+++.'))
@floral meteor :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
bruh
segfault
all i did was make for loop catch indexerror ;-;
I didn't get 139
I got -1073741819
I think that one's segfault on steroids or something
or maybe the windows version of segfault
!e maybe i need another coffee ```py
chars = '+-<>.,[]'
def brainfuck(code,input=input):
from collections import defaultdict as d
l=input==builtins.input
if not l:input=lambda i=1:input.pop(i-1)
a,o=d(int),''
i=p=t=0
for c in iter(lambda:code[p],''):
def __0(i,):
a[i]+=1
a[i]%=256
return i,,0
def __1(i,):
a[i]-=1
a[i]%=256
return i,,0
def __2(i,o):
o+=chr(a[i])
return i,o,0
def __3(i,):
a[i]+=ord(input(1))%256
return i,,0
f = [__0,__1,
lambda i,:(i+1,,0),
lambda i,:(i-1,,0),
__2,__3,
lambda i,o:(i,o,int(not a[i])),
lambda i,o:(i,o,---bool(a[i])),
lambda*:(*,0)][chars.find(c)]
if t:
t+=(c=='[')-(c==']')
else:
i,o,t=f(i,o)
p+=1-2*(t<0)
try:code[p]
except IndexError:break
return o,int(p!=len(code))
status = brainfuck('++++++++++[>+++>+++++++>++++++++>++++++++++>+++++++++++<<<<<-]>>++.-->>+.+++++++..-------->+This is a comment.-<<<<++.-->>+++++++.------->>+.+++.----<++++++++.--------.<<<+++.')
error = status[1] or print(status[0])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
ay, thats nice
does anyone have any guides for elegant python code? I've read a lot of it made by people who don't have style or don't make it aesthetically pleasing. is there a style guide or blog post that talks about this in detail? thanks!
Out of all channels 😆
@sick hound you had to ask in the channel dedicated to code gore and other questionable coding practices?
oh lol, didn't read the description
XD
!e ```py
print ("Hello, World")
@vast bough :white_check_mark: Your eval job has completed with return code 0.
Hello, World
!e
!eval [code]
Can also use: e
*Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code
block. Code can be re-evaluated by editing the original message within 10 seconds and
clicking the reaction that subsequently appears.
We've done our best to make this sandboxed, but do let us know if you manage to find an
issue with it!*
!e ```py
chars = '+-<>.,[]'
def brainfuck(code,input=input):
from collections import defaultdict as d
l=input==builtins.input
if not l:input=lambda i=1:input.pop(i-1)
a,o=d(int),''
i=p=t=0
for c in iter(lambda:code[p],''):
def __0(i,):
a[i]+=1
a[i]%=256
return i,,0
def __1(i,):
a[i]-=1
a[i]%=256
return i,,0
def __2(i,o):
o+=chr(a[i])
return i,o,0
def __3(i,):
a[i]+=ord(input(1))%256
return i,,0
f = [__0,__1,
lambda i,:(i+1,,0),
lambda i,:(i-1,,0),
__2,__3,
lambda i,o:(i,o,int(not a[i])),
lambda i,o:(i,o,---bool(a[i])),
lambda*:(*,0)][chars.find(c)]
if t:
t+=(c=='[')-(c==']')
else:
i,o,t=f(i,o)
p+=1-2*(t<0)
try:code[p]
except IndexError:break
return o,int(p!=len(code))
status = brainfuck('++++++++++[>+++>+++++++>++++++++>++++++++++>+++++++++++<<<<<-]>>++.-->>+.+++++++..-------->+This is a comment.-<<<<++.-->>+++++++.------->>+.+++.----<++++++++.--------.<<<+++.')
error = status[1] or print(status[0])
@vast bough :white_check_mark: Your eval job has completed with return code 0.
Hello World!
@earnest wing @floral meteor https://emkc.org/contests/43/password-policy sols are up
can't believe I didn't try re lol
i,m=input,map
l=''
for x in i():l+=x[:not'@'<x<'S']
WS,US,U,_,t,T=m(sum,m(m,[*vars(str).values()][52::2],[i()]*6))
S=T-t
i(f"{all(m(eval,l.split(';')))}".lower())
this is my sol, 162 bytes
endpoints = []
@endpoints.append
def users__Id(request, Id):
if request.method == 'POST':
return create_new_user(Id)
if request.method == 'GET':
return get_user(Id)
run(endpoints=endpoints)
```how does this make you feel?
like u dropped this ༼ つ ◕_◕ ༽つ)
thanks
Honestly, I think this is actually useful. AKA, if doesn't belong in this channel.
I mean,using prolog style variables in functions names is most certainly esoteric and not useful
ahh, map could've helped me
Shortening the variable names didn't work for me.
I kept this one cos it's misleading use of len
a,p=open(0) s=str *n,_=UPPERCASE,LOWERCASE,NUMERICAL,LENGTH=[sum(k(c)for c in p)for k in(s.isupper,s.islower,s.isdigit,len)] SPECIAL=_-sum(n) print(s(all(map(eval,a.split(';')))).lower())
Heh, I can't believe my answer was even half similar to Lyndon's
lyndon is the pro
they're always slacking though
sometimes I manage to beat them to optimal and they tie
cuz (if it isn't simple) they always wait till there are python solutions, beat them, then do ruby perl etc
I wish non re won but re is too powerful, I doubt 161 is optimal since lyndon only did that cuz I tied
haha yeah I wasn't very excited to use it so I didn't
it's sort of fun sometimes but I'm always left wishing it was more powerful
class ImmutableMetaClass(type):
"""Create an immutable class."""
def __setattr__(self, name, value):
message = f"{name} of {self} cannot be set."
raise AttributeError(message)
def __getattribute__(self, name):
if name == '__class__':
message = f"{name} of {self} is inaccessible."
raise AttributeError(message)
return super().__getattribute__(name)
class Immutable(metaclass=ImmutableMetaClass):
"""Create an immutable instance."""
__slots__ = ["one", "two", "three"]
def __init__(self, one, two, three):
super().__setattr__("one", one)
super().__setattr__("two", two)
super().__setattr__("three", three)
def __setattr__(self, name, value):
message = f"{name} of {self} cannot be set."
raise AttributeError(message)```
so let's say you have an instance of Immutable:
a = Immutable(1,2,3)
given access only to a, set a.one to 0 without rebinding the name a
idk how yet I'm messing with someone's attempt at an Immutable class and this is what I have so far
I was thinking without implementation dependent magic
since you can do absolutely anything with implementation dependent magic
could override ctypes as well though to avoid that
I was thinking rebinding super
idk if you can
It is a bit magic
oh that would work
...if they're in the same module
I'm thinking by accessing a only
not the module in which it's defined
well you can usually access the g/setattr function globals through stack frames but that's pretty lame
And stack frames from the exception raised by setattr etc
ah nice
so like ```py
a = some_module.Immutable(1, 2, 3)
try:
a.class.class
except AttributeError as b:
b.traceback.tb_next.tb_frame.f_locals['class'].getattribute = type.getattribute
a.class.class.setattr = type.setattr
a.class.setattr = object.setattr
a.one = 0
print(a.one)
Something like that yeah
why do i hate this code snippet
!e ```py
chars = '+-<>.,[]'
class BrainfuckError(SystemExit):...
def brainfuck(code,input=input):
from collections import defaultdict as d
l=input==builtins.input
if not l:input=lambda i=1:input.pop(i-1)
a,o=d(int),''
i=p=t=0
for c in iter(lambda:code[p],''):
def __0(i,):
a[i]+=1
a[i]%=256
return i,,0
def __1(i,):
a[i]-=1
a[i]%=256
return i,,0
def __2(i,o):
o+=chr(a[i])
return i,o,0
def __3(i,):
a[i]+=ord(input(1))%256
return i,,0
f = [__0,__1,
lambda i,:(i+1,,0),
lambda i,:(i-1,,0),
__2,__3,
lambda i,o:(i,o,int(not a[i])),
lambda i,o:(i,o,---bool(a[i])),
lambda*:(*,0)][chars.find(c)]
if t:
t+=(c=='[')-(c==']')
else:
i,o,t=f(i,o)
p+=1-2*(t<0)
try:code[p]
except IndexError:break
return o,int(p!=len(code))
status = brainfuck('++++++++++[>+++>++++>+++++>+++++++>+++++++++>++++++++++>+++++++++++>++++++++++++<<<<<<<<-]>>>>+++.<<<++.>>>>+++++++.>+++++++++.<<<<<.>>>>>>++++++++.<--------.>----.>+.<<<<<<<.>>>>>>----.<<.>>+++++++.<++.+.>-.>.<<<<<<<.>>+++++++++.<+.')
error = status[1] or print(status[0])
error and (()for()in()).throw(BrainfuckError,error)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
I am very naughty ;)
alright, cursed packaging; a function that can only be imported if something else is imported.
>>> from brainfuck import code
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'code' from 'brainfuck' (E:\__py__\__modules__\cursedutils\cursedutils\brainfuck\__init__.py)
>>> from brainfuck import generator, code
>>> code
<function code at 0x0000021B9C31F3A0>
>>>
I have a few ideas @simple crystal
In [2]: a=Immutable(1, 2, 3)
In [3]: super(Immutable, a).__setattr__('one', 4)
In [4]: a
Out[4]: <__main__.Immutable at 0x257d6444080>
In [5]: a.one
Out[5]: 4
In [8]: del type(a).__setattr__
In [9]: a.one = 56```
nice
Oh nice, shared memory:
print(f"{ma = }, {ma.tolist() = }")
print(f"{mb = }, {mb.tolist() = }")
mb[1]=7
print(f"{ma = }, {ma.tolist() = }")
print(f"{mb = }, {mb.tolist() = }")
out:
ma = <memory at 0x7f2d776fc1c0>, ma.tolist() = [1, 9]
mb = <memory at 0x7f2da005ae80>, mb.tolist() = [1, 9, 9, 1121]
ma = <memory at 0x7f2d776fc1c0>, ma.tolist() = [1, 7]
mb = <memory at 0x7f2da005ae80>, mb.tolist() = [1, 7, 9, 1121]
inspired by <#python-discussion message>
challenge: make this code print a 9 (and only a 9)
def print_nine():
print_nine()
print('9')
print_nine()
you can add any code before this, except a decorator to the print_nine function
the last line must be executed. for extra points the entirety of print_nine must also be executed.
print(9)
exit()
def print_nine():
print_nine()
print('9')
print_nine()
```:)
lol ok new rule, the last line must be executed
for extra points the entirety of print_nine must also be executed
!e
import sys
sys.setrecursionlimit(40)
sys.excepthook = lambda *a:print('9')
def print_nine():
print_nine()
print('9')
print_nine()
@proper vault :x: Your eval job has completed with return code 1.
9
I don't get bonus points
ok, now make it weirder 🙂
Can I add code after the print_nine function?
i thought setting sys.modules[name].class would work for lookups but alas, print_nine doesnt go to getattribute
so i have no clue how you can do this
i have one solution in mind
so it is doable, i think
wait let me actually check it works lmao
im no python wizard the excepthook and editing the module class were the two things that came to mind
ok, yes, it works
took a little bit of tweaking but there is at least one solution
for extra extra points: dont use excepthook
>>> def e():
... return e
...
>>> e()()()()()
<function e at 0x00000106ED27EF70>
e()()()()()()()()()()()()
def e(ee):
return e, ee
>>> def eee():
... for i in range(10):
... print("e(", end="")
... print("e", end="")
... for i in range(10):
... print(")", end="")
... print()
>>> eee()
e(e(e(e(e(e(e(e(e(e(e))))))))))
>>> e(e(e(e(e(e(e(e(e(e(e))))))))))
(<function e at 0x00000106ED31CDC0>, (<function e at 0x00000106ED31CDC0>, (<function e at 0x00000106ED31CDC0>, (<function e at 0x00000106ED31CDC0>, (<function e at 0x00000106ED31CDC0>, (<function e at 0x00000106ED31CDC0>, (<function e at 0x00000106ED31CDC0>, (<function e at 0x00000106ED31CDC0>, (<function e at 0x00000106ED31CDC0>, (<function e at 0x00000106ED31CDC0>, <function e at 0x00000106ED31CDC0>))))))))))
>>> def eeee(eee):
... for ee in range(eee):
... print("e(", end="")
... print("e", end="")
... for ee in range(eee):
... print(")", end="")
... print()
(sorry for spam)
>>> eeee(100)
e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
D:
SyntaxError: too many nested parentheses
bruh
I don't get syntax error :/
alright i have a weird issue with right aligning f-strings with escape sequences.
So I accounted for escape sequences in a three digit number, but then it counted over a thousand, and kept the same number of spaces making the string longer, rather than taking away spaces to preserve length
but i guess doing wierd things comes with weird issue
i can't spell wierd
so what are the 0xC000000X exit codes for?(
I am now officially an errorslinger
!e ```py
annotations=globals()
: +'+-<>'=",.[]";
://2 +1=(0x00for x in 100% yo_mamma is fat)
def code(
0:(str,"The code, preferably UTF-8")="",
1:(int,'architecture of target machine')=__
):
if not(_0):return''
if ord(max(_0))>1<<_1:raise RuntimeError(
"Cannot encode "+max(_0)+" into character size "+str(_1)
) ;-D
for _00 in['']:01: (list, "mem::code")=[ord()for _ in str(_0)]
_02:(list, "bf::mul-values")=[
_ for _ in range((max(01)+2)//10)if any([__//10== for __ in _01])
];_02+=(max(_01)//10 not in _02)[max(_01)//10]
00+='+'*10+'[>'+'>'.join(['+'for _ in _02])+'<'*len(_02)+'-]>'
_03:(int,"sys::pointer-shift state")=int()
_04:(list,'mem::turing-machine')=[0]*len(_02)
for _10 in _01:
_11:(tuple, ("chop off last digit","last digit"))=_10.divmod(10)
while _11[0]>_02[_03]:_03+=1;_00+='>';
while _11[0]<_02[_03]:_03-=1;_00+='<';
_12:(int,'cell_increment')= _11[1]-_04[_03]
_00+={1<0:'+',0<1:'-'}[12<0]*abs(12)+'.'
04[03]+=12
05:(str, 'conflict')=[:2],[2:4]
for _2 in range(2):
while _05[_2]in _00:_00=_00 .replace(_05[_2],'')
while _05[_2][::-1]in _00:_00=_00.replace(_05[_2][::-1],'')
return _00
print(code('Automatic brainfuck generation go brrrr.'))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
++++++++++[>+++>++++>++++++>+++++++++>++++++++++>+++++++++++<<<<<<-]>>>+++++.>>>+++++++.-.-----.<+++++++++.<+++++++.>>+++++.<----.<++.<<<++.>>>-.>>--.<<-.>.>----.<---.>+++++++.<<++.>+++++.<<<<.>>>>----.--.>-------.<.>++++.<<--.>>++.<++++.>-----.-.<<<<<.>>>>--.>+.<<<<<.>>>+.>>+++....<<<<++++++.
That's how I use annotations. type hints are overrated
atomic brainfuck generation