#esoteric-python
1 messages ยท Page 52 of 1
me when fractional indices:
my pc taken away for 2 months :(
anyways hiatus until i get it back
esolang has prefix operators and weird token behavior
standalone digit is label, digit in a perceived operand context is a number
183 # labels/numbers 1, 8, 3
'183 # number 183
_183 # label 183, only valid outside of a perceived operand context
abc # names a, b, c
_abc # name abc
ye
So you can't pass a label as an operand and have it look up the thing it points to?
nop
i originally intended it to be a stack based language where unpack and goto would be able to manipulate operations but the parsing part became harder as a result
i'll rework it when i get my pc back ;`;
Are you on iOS or Android (or hypothetically other) in the meantime?
i kinda dislike postfix notation tho, but anyways earlier example ends up like this ```py
'1'2+'4'7 .1.2+
Which? Both? I was gonna suggest a coding environment
my working code is on the pc, so..
Aah. I was gonna say that e.g. https://omz-software.com/pythonista/ exists
Maybe Pydroid 3 is the coolest one for Android? Not sure. (Or QPython it looks like)
So I was poking at this new programming languageโs closed sourced compiler and managed to get Cython function bugs out of it trying to run Pythonโs pandas library on it. How does that work 
You would either file a bug report to cython or pandas if relevant, it's not related to esoteric python
new programming language's closed source compiler, not cython nor pandas
Well, I have no idea what that talking about or mean so I skipped it
But I only know that this is unrelated to here
i mean it's not completely unrelated
8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
Sorry to the mods, cause itโs off topic. But I see youโre using obsidian and have python code inside it. What plugin are you using to do that?
๐ code in place?
I was a section leader last year
Have you tried asking in the discussion forums?
okkkkkkkkkkkkkkkkkkkkkkkkkkkkkk yeyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
i completed that codeeeeeeeeeeeeeeeeeeeeeeeeee
by myselffffffffffffffffffffffffffffff
๐ญ
thank you , you all for not helping me so i can use my brain
wait really no way
yeah because the rule I made must be followed
in case you don't know #esoteric-python message
Aghh, it's taking me too much time. They use some sort of code sanitization before passing the code to pyoide. Maybe it's possible to do stuff with it, but it's going to be an interesting challenge. If anyone up to the challenge, the main logic seems to be in static/js/ide/utils/karelCompiler/karel/KarelVM.js (after decoding with source maps - browses do that automatically). Oh and the link to the website is ofc https://codeinplace.stanford.edu/public/ide/a/housekarel (registration required?!)
hii
humm right i am trying to learn coding that why i joined this server
this channel is specially for writing esoteric code you should checkout #python-discussion and #1035199133436354600
!e
import sys
import traceback
def trace(exc_type, exc_val, exc_trace):
if issubclass(exc_type, NameError):
exc_trace.tb_frame.f_globals[str(exc_val).split("'")[1]] = str(exc_val).split("'")[1]
while True:
try:
exec(exc_trace.tb_frame.f_code)
break
except NameError as e:
exc_trace.tb_frame.f_globals[str(e).split("'")[1]] = str(e).split("'")[1]
continue
sys.excepthook = trace
print(Hello, World)
:x: Your 3.12 eval job has completed with return code 1.
Hello World
How can i make this not exit with 1?
Hmm. It seems to me that.. When you call exec(exc_trace.tb_frame.f_code), you're re-running things from the frame where the exception occurred... but f_code is the whole function, not just the line the caused the error, right? Maybe that's fine but even then I guess the CPython interpreter state still thinks there's an unresolved exception, and is heading toward exiting?
!e
import sys
import traceback
def trace(exc_type, exc_val, exc_trace):
if issubclass(exc_type, NameError):
exc_trace.tb_frame.f_globals[str(exc_val).split("'")[1]] = str(exc_val).split("'")[1]
while True:
try:
exec(exc_trace.tb_frame.f_code)
break
except NameError as e:
exc_trace.tb_frame.f_globals[str(e).split("'")[1]] = str(e).split("'")[1]
continue
sys.excepthook = trace
print(Hello, World)
# but this still runs:
print(Hello, Again)
:x: Your 3.12 eval job has completed with return code 1.
001 | Hello World
002 | Hello World
003 | Hello Again
I take it eval(your_var_name, frame.f_globals, frame.f_locals) isn't enough for what you want?
Hmm yeah that's interesting that it is proceeding, I guess that part of my model of it is wrong.
Maybe you just need to return False after breaking to let the default handler take over? Hmm.
Sorry, I'm not sure. Interesting code though!
No, doesn't work
Yeah, i am planning on allowing english spelled numbers like thirteen -> 13
I've never thought to implement a DSL based on NameError. Clever.
I think you should just sys.exit(0) at the end of trace inside the if, since because the script runs the entire code again, once the code runs sucessfully to completion it should normally exit with code 0, you just have to do it yourself to interrupt python's default behavior after the excepthook.
Another thought, I think I remember seeing the person that made the goto in python use trace to resume execution at a specific point, so you might be able to do something like that to prevent code from running twice. It wouldn't be foolproof since you could have very nested statements, but it would at least work in the simple case of one set of errors per line.
I'm not familiar enough with traces and that, so I changed it to read the file, and rewrite it using ast.NodeTransformers instead. It even works with pypy
# fix.py
from ast import *
import sys
import inspect
if sys.implementation.name == "pypy":
pypy = True
else:
pypy = False
class NodeVisitor(NodeTransformer):
def visit_Name(self, node):
return Call(
func=Name(id="__best_var", ctx=Load()),
args=[
Constant(value=node.id),
Call(func=Name(id="locals", ctx=Load()), keywords=[], args=[]),
Call(func=Name(id="globals", ctx=Load()), keywords=[], args=[]),
(
(
Attribute(
value=Name(id="__builtins__", ctx=Load()),
attr="__dict__",
ctx=Load(),
)
)
if pypy
else (Name(id="__builtins__", ctx=Load()))
),
],
keywords=[],
)
def visit_Import(self, node):
if len(node.names) == 1 and node.names[0].name == "fix":
return parse(
r"""
if 1:
def ___best_var(var, *scopes):
for scope in scopes:
if var in scope:
return scope[var]
return var
globals()['__best_var'] = ___best_var
"""
).body[0]
return node
frame = inspect.currentframe()
while frame:
last_working = frame
frame = frame.f_back
frame = last_working
source_file = frame.f_globals["__file__"]
with open(source_file, "r") as f:
source = f.read()
new_tree = fix_missing_locations(NodeVisitor().visit(parse(source)))
# print(dump(new_tree, indent=2))
# print("==========")
# print(unparse(new_tree))
compiled = compile(new_tree, "", "exec")
exec(compiled)
sys.exit(0)
# main.py
import fix
print(Hello, World)
Tomorrow i'll add it so that spelled out english numbers become integers
but does it work with the REPL
no, but I'm sure it's possible to inject it into the REPL.
I added support for numbers: https://codeberg.org/assembly/python-dsl
well as long as there's another way other than using __file__..
Its actually very easy using code library
import code
import sys
from fixlib import fixed_parser
class CustomREPL(code.InteractiveConsole):
def __init__(self, *args, **kwargs):
super().__init__()
import numbers as __number_converter
def ___best_var(var, *scopes):
for scope in scopes:
if var in scope:
return scope[var]
try:
return __number_converter.english_to_int(var)
except:
return var
self.locals["__best_var"] = ___best_var
def runsource(self, source, filename="<input>", symbol="single"):
"""Override the runsource method to use the custom execute function."""
try:
code = self.compile(source, filename, symbol)
except (OverflowError, SyntaxError, ValueError):
# Case 1
self.showsyntaxerror(filename, source=source)
return False
if code is None:
# Case 2
return True
code = compile(
fixed_parser(source, parsemode=symbol, import_rewrite=False),
filename,
symbol,
)
# Case 3
self.runcode(code)
return False
CustomREPL().interact(
f'Python {sys.version.split()[0]} [Fixed]\nType "help", "copyright", "credits" or "license" for more information.'
)
Python 3.13.2 [Fixed]
Type "help", "copyright", "credits" or "license" for more information.
>>> print(Hello, python, discord, one, two, three, four_hundred_million_seventy_nine_thousand)
Hello python discord 1 2 3 400079000
>>>
ohh.
so just secretly open a new REPL when the module is imported, i see..
read the channel description. This falls under obfuscated -- very esoteric Python
very quickly changed stances :p
we need a cobra-accelerated version of Python for this ecosystem
that would be awesome. A framework for Python with a cobra holy smokes 
https://chilaxan.github.io/python/2023/12/01/symbolic-numbers-in-python-part-1.html I did something similar a while back
A while ago I wanted to see if I could add symbolic numbers to Python. This would mean that something like one would equal 1 and two_hundred_and_five would equal 205.
Never did get around to part 2 tho lol
The secret to getting it to work everywhere was to hot swap the globals dict type to a custom subclass with that missing dunder implemented
That's an interesting approach
https://paste.pythondiscord.com/IDYA FizzBuzz with just dynamic dispatch.
I think i figured it out. You can just replace the globals using c_void_p
!e
from ctypes import c_void_p
import random
class BuiltinDict(dict):
# We need to save all builtin and global variables used as default parameters
# otherwise this function will get called again trying to access that name
def __getitem__(
self,
key,
globals=globals(),
builtins=__builtins__,
hasattr=hasattr,
getattr=getattr,
random=random,
):
if key in globals:
return globals[key]
elif hasattr(builtins, key):
return getattr(builtins, key)
if key == "pie":
return "๐"
elif key == "pi":
return 3 + random.random()
return key
c_void_p.from_address(id(globals()) + 8).value = id(BuiltinDict)
print(Hello, World, pie, pi)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello World ๐ 3.438299635356297
you can use __missing__ instead of __getitem__ to avoid having to check if key in self and key in __builtins__.__dict__
For the highest reolution i got (75kร150k) it was probably around like 32 gb for rgb
optimize it to take half of it
use pallette to make it colorful
I did. 75k pixels height was top half of thr image
150k length
What in God's good name is this code from the IntelliJ repo?
def temp(filepath):
a = 1
with open(filepath) as f:
l = <caret>f.readlines()
for line in l:
a = 1
Is that <caret> literal, or is that trying to say the line is: l = ^f.readlines()?
My guess is that's how their test harness decides where to put the editor's cursor during setup, and it's stripped out?
Looking at the testSrc directory, that does seem to be the case
I'm using pyinstaller to bundle my core app into an exe. The app is modular and I'm bundling my modules as .pyd files.
The core doesn't know anything about the modules at compile time, but sometimes the modules have dependencies that the core doesn't... these need to be installed at runtime (app restart allowed).
Can someone suggest a way to do this? I'm currently trying to do pip and pip._internal etc as hidden imports for the pyinstaller to I might be able to call pip at runtime, but that seems like a dead end right now.
I hope that's esoteric/code gore enough for this channel :>
Sadly uv doesn't offer a Python API yet, or else that would be my preferred trick.
you think another package manager might work if they had a python api?
Yeah, maybe pyenv offers that?
Edit: I guess not at first glance... hmm.
I probably could include pip, or uv for that matter, with the project (e.g. through the installer). But I'm not sure how I would include the installed libraries with my project.
i miss my pc rn and i can't finish my wip esolang
so here's a fizzbuzz program in said esolang ```py
1a:100>?f01@:3%!?(!"Fizz"$<)1@:5%!?(1|"Buzz"$<)?(:$<)1+af
I've recently been in the mood of writing python like rust, so could I get an opinion on this "procedural macro"? https://paste.pythondiscord.com/AJ4Q it's for automatically adding the default list constructors to a dataclass
you can compare ASTs by ==?
https://paste.pythondiscord.com/ONLA alternative version that doesn't compare asts by == since that stopped working, and makes the type checker happy by being less magic (using field: list[x] = [] instead of just field: list[x])
I think pattern matching can be used to do what you are doing with three ifs
I'm very unfamiliar with using match, could you show me?
you can match a class using case class_name(), and match a class with a certain attribute x as case class_name(x=...) (... must also be a valid match pattern)
there's a full tutorial in PEP 636 but that's the gist of what you'd need here
Iโve read the pep for match, but since Iโve never actually played around with them Iโm still not certain exactly how to write them.
!pep 636
for example if you wanted to match a list identifier node, you'd use the pattern Name(id="list")
iirc the other attributes not mentioned in the pattern will be ignored, so you won't need to check for them
!e ```py
from ast import *
x = parse('abc')
match x.body[0]:
case Expr(value=Name(id="abc")):
print("matched!")
:white_check_mark: Your 3.12 eval job has completed with return code 0.
matched!
!e ```py
from ast import *
x = parse('x: list[Any] = []')
match x.body[0]:
case AnnAssign(
annotation=Subscript(
value=Name(id="list"),
),
value=List(),
):
print("matched!")
:white_check_mark: Your 3.12 eval job has completed with return code 0.
matched!
Is there a postfix way to convert generator to list?
e.g. something like range(5) -> list
if that makes sense
it's just would be easier to type when debugging sometimes
instead of going back and wrapping the generator with list
The best I've found for now is this
from pipe import Pipe
print(range(5) | Pipe(list))
why though?
a few move-across-word keybinds and you can easily wrap it in a call or that other syntax
you could also make a shorthand like that | Pipe() thingy
for example, > _(list) where ```py
class _:
def init(self, f):
self.f = f
def lt(self, o):
return self.f(o)
just feels more natural.
E.g. typing range + list is
- Type
range(5) ctrl <-x 2 to get beforer- type
list( ctrl ->x3 to get after)- type
)
versus 1. type range(5) and 2. type | Pipe(list)
Yeah, looks good too. It seems the only solution is to have a special object with one of the operators overridden
there's always the option of overriding the names too
but i'm not sure if that'd fare well with linters or whatever they're called
overriding the names?
like assigning a different class to list
oh, that would be too esoteric ๐
wanna take a guess at where you are right now
not reallyy-
i still haven't told you to overwrite the built-in class slot ^_^
doing that would be annoying probaby because there are lots of different options
list, tuple, secret third option, set, dictionary, etc.
overriding them all is annoying
its sad that you cant override the abc to make stuff work tbh
!e ```py
from fishhook import hook
@hook(type)
def lt(self, other):
return self(other)
print(range(5) > list)
print(range(5) > set)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | [0, 1, 2, 3, 4]
002 | {0, 1, 2, 3, 4}
well.
something along the lines of range(5) > []
which is cute syntax, i think
although
type hooking allows for silliness
although chaining is a bit meh....
| can be overridden but it must be checked for type/generic unions
that could be done anyway perhaps
using | as ยฐ
1 > (float | str)
ooh-
may as well do functions too at that point
!e ```py
from fishhook import hook
@hook(type)
def lt(self, other):
return self(other)
@hook(type(int | str))
def lt(self, other):
for typ in self.args:
other = typ(other)
return other
print(range(5) > list)
print(1 > complex | str)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | [0, 1, 2, 3, 4]
002 | (1+0j)
we might have to override piping anyway
__args__ doesnt actually return the args but rather the unique args
(int | str | int).args โฆ (int, str)
kinda messed up if you ask me
oh well
^
bitwise XOR is the second lowest operand-preserving non-chaining binary operator precedence after bitwise OR
{{
print('{}โ{}โ{}\nโโโโผโโโโผโโโ\n{}โ{}โ{}\nโโโโผโโโโผโโโ\n{}โ{}โ{}'
.format(*[' ' if i == '1' else ' X ' if i == '5' else ' O ' for i in str(B)])
) for _ in range(5)
if (B := B + 4 * 10 ** abs(9-int(input())))
and (t := [2.71828 ** (
sum(w[i][j] * list(map(int,str(B)))[j] for j in range(9)) + b[i]
) for i in range(9)])
and (B := B + 8 * 10 ** t.index(max(t, key = lambda x: x / sum(t))))
} for B, w, b in [(
111111111,
[
[0.5324228, 0.76355624, 1.0098922, 1.0587181, 0.47961304, 0.8581823, 0.045538172, 1.0410924, -1.579585],
[0.4228034, 0.9537834, 0.9404552, 1.0115612, 0.5452481, 0.8414384, 0.0972775, -1.0017858, 0.40512067],
[0.7085032, 0.955647, 1.0234874, 1.03152, 0.36106178, 0.82706773, -1.0083874, 0.76845086, 0.19899876],
[0.46637133, 0.65566856, 1.0476296, 1.3649647, 0.5284521, -1.0649983, 0.18261205, 0.78231066, 0.3543514],
[0.6555538, 0.993636, 1.0712171, 1.2289686, -1.1268336, 0.7060021, 0.121178925, 0.5562301, 0.011001009],
[0.6181679, 0.48797947, 1.063911, -0.8666658, 0.55554706, 0.98548925, 0.23587868, 0.90056294, 0.30139807],
[0.7447117, 0.6618681, -0.7941452, 1.040301, 0.39376765, 0.8027111, 0.14813231, 0.800058, 0.38237593],
[0.6764701, -1.1199214, 1.1118764, 0.79409623, 0.48408085, 0.83786356, 0.18026906, 1.0840094, 0.28564036],
[-0.9352118, 0.70592344, 1.1290987, 1.057092, 0.47734314, 0.8022352, 0.11734288, 0.7755984, 0.34827393],
],
[-0.27312347, -0.35538667, -0.7696111, -0.9394737, 0.61957735, -0.09319963, 0.28401002, 0.48452064, 0.626548],
)]}
hihi
this seems like the right channel for this ive been working on-
the above code doesnt run because the walrus operator cant be used with B and i wanna know if theres an easy workaround without stepping out of the comprehension
dont expect too much from it tho since ive only been able to get the cost down to 0.8~
Can't you just use a different variable for assignment than for iteration?
Pseudocode:
[(B := iterated, [B := B * 2 for _ in range(iterated + 1)][-1])[1] for iterated in range(10)]
oo- yep, i didnt know you could set a variable in a tuple like that. thought the operator was exclusive to conditionals. tyvm
:= explain me this
It's the I mean it, officer operator
Officer ๐ฎ operator
Lets you do x = y in a place where by default the language wants to protect you
๐ n yeah n further more
Tons more here https://peps.python.org/pep-0572/
I mean, it sorta closes a loophole that might have been irritating, but I can't say I've seen it much in action yet either
while chunk := file.read(8192):
process(chunk)
is sorta the most legit example on that page to my eye
I don't 100% get why we didn't just make chunk = ... into an expression vs. a statement and move on, but oh well
if name = "me":
...
Among other reasons, because of this footgun.
Yeah. That works in Ruby, which is fun.. I appreciate the guardrail in Python I suppose.
But yeah that's why I called it the I mean it operator
I do get it's just surface level but not deep understanding
How I can implement in my day to day code
Is it really necessary
There are some funny edges to it, to my eye.. for example:
class Example:
[(j := i) for i in range(5)] # INVALID
Ya
Feels like I understand
I see more examples
I get more confused
Like that if else block with walrus operator
It's ez to read what the code does
My biggest complaint is that it doesn't support inline type annotations.
I found it handy
So I guess I prefer to avoid using this where I can
Ya bro
We should complain about it n ask from it dev team to add type annotations
It will provide safety
but I guess it's nice to be able to say this:
if env_base := os.environ.get("PYTHONUSERBASE", None):
return env_base
``` but the type thing, yeah, that irks me.
๐
My mind clogged
(parentheses optional in comprehension syntax)
Yeah but I guess the main point is that it's invalid because it's trying to create a class variable and this stuff won't let you
usually i'd just do a non-assigning annotation before the line
Is there any python library just for one liner.? Pre written snipets
Some of these examples I'm just not down with:
while total != (total := total + term):
term *= mx2 / (i*(i+1))
i += 2
return total
Like.. please spend another line to make this less nested? I dunno, maybe just me.
As I hurt my wrist flicking in pc game ๐ฎ I can't type properly
I am using voice to text ๐คง
Should I read this code from top to bottom or bottom to top?
tbf, that code is technically a syntaxerror
I guess inside out.. the middle is the "thing we're doing a lot", figure that out, and then go back and read the "termination condition" at the top
Really? It's from the PEP
doesn't the pep indent the return
What that mx2 n how I variable working in middle lol?
I guess I need to be so high to understand this
it should also be noted, however, the context of the example:
The
whiletest there is too subtle, crucially relying on strict left-to-right evaluation in a non-short-circuiting or method-chaining context. My brain isnโt wired that way.But cases like that were rare.
Maybe time to go docs or get back to reading pep8 guidelines again
As I didn't touched it for long I feel so backlog
Agree
We so use to simplicity that we getting stuck
I GUESS what's going on here is that this is part of calculating a cosine using its taylor-series approximation?
in which case it's kinda missing a 'precision' param
lol yeah I just pasted it into Claude and asked it to reconstruct the full function, and it agrees
The PEP implementation would run into you hit floating-point precision limits, which might be more ocean boiling than you wanted
Hmm I just tried writing this the way I'd prefer and I have to admit it's quite a bit longer.
to be fair, the author of the appendix doesn't like this example either
This is my best take so far.. way open to suggestions though
def cos_approximation(x, precision=1e-10):
neg_x_squared = -x**2
total = term = 1.0
term_index = 2
while True:
old_total = total
term *= neg_x_squared / (term_index * (term_index + 1))
total += term
term_index += 2
if abs(term) < precision or old_total == total:
return total
(sorry, kinda the opposite of esoteric)
but this is what I'd do instead of walrus-ing it like that example.. and yeah good point that the author calls it out as too-terse.
There's probably some nardog way to do that as a single comprehension but I guess I'm not there yet
TIL augmented assignment + unpacking don't work together
a, b = 0, 0
def test() -> tuple[int, int]:
return 5, 5
# Pyright:
# Expression with type "tuple[Unknown, Unknown, int, int]" cannot be assigned to target tuple
# Type "tuple[Unknown, Unknown, int, int]" is incompatible with target tuple
# Tuple size mismatch; expected 2 but received 4
# SyntaxError: 'tuple' is an illegal expression for augmented assignment
a, b += test()
ok more esolang rambling. ```py
def maxsumb(xs):
it = iter(xs)
r = a = next(it, 0)
b = -1e3082
for v in it:
r += v
a = min(a, r)
b = max(b, r - a)
return 0 if b == -1e3082 else b
print(maxsumb([-4, 1, 3, 5, 1, -10, -100, 7, 1]))
esolang equiv:
($@x21'308*-$a$b0'x$=(-+:'a>?$a:-'a+:'b>?$b?)?;'b:22@,=??0)$`maxsumb
?; #"non-obligatory stack pop"
`maxsumb@((4-1351'10-'100-71))$<
link to python code simulation #bot-commands message
that reminds me of false
import discord.ext.commands as c,discord as d,tokens as t
b=c.Bot((),intents=d.Intents.all())
@b.tree.command()
async def s(i,a:int):
async for(m)in(i.channel.history(limit=a)):
await(m.delete())
@b.event
async def on_ready():await(b.tree.sync())
b.run(t.tokens["testbotpy"])
``` how shorten?
!e
code
!e ```py
def foo(): {
print("Hello world")
}
foo()```
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello world
Wait till you find out about this other one
!e
def my_func():print(1);print(2);print(3);
my_func()
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 1
002 | 2
003 | 3
Super tricky puzzle:
i=1000;exec(__________________*_)
In the code, each underscore can be replaced with any byte. Can you fill it in such that the code prints only the even numbers between 999 and 1? (998, 996, ..., 6, 4, 2)
Unclear questions: 999 is not an even number
oops, edited
Just to be sure, we only get one byte after the *?
How many underscore there for the long one
18 it looks like
"print(i);i-=1;" *i
Being silly rn because it didn't specify to only print every even number between 999 and 1
So technically this did print every even number between 999 and 1, just also all the odd number as well
And also 1000
did the spec change because it does specify that...
Yes unless I'm blind
What is the seperator between the number, or just ""
newline
Does anyone know if it's possible to raise objects that do not derive from 'BaseException', without using a wrapper? (cpython)
if its type has the exception class flag set, it can raise
!e ```py
import ctypes as ct
class A: ...
ct.c_ulong.from_address(id(A)+16+8*19).value |= 2**30
print(A.flags)
raise A
:x: Your 3.12 eval job has completed with return code 1.
001 | 1073763864
002 | TypeError: print_exception(): Exception expected for value, type found
003 |
004 | The above exception was the direct cause of the following exception:
005 |
006 | Traceback (most recent call last):
007 | File "/home/main.py", line 5, in <module>
008 | raise A
009 | A: <__main__.A object at 0x7f7dea2ffaa0>
thanks
!e
import ctypes as ct
ct.c_ulong.from_address(id(str)+168).value |= 1<<30
try:
raise "test"
except:
print("caught")
:warning: Your 3.12 eval job has completed with return code 139 (SIGSEGV).
[No output]
unfortunately, raised exceptions need proper metadata, so you'd have to use a BaseException subclass anyhow. ^.^
ok, thank you anyways. Guess i will have to do ast rewriting after all.
looks like someone's making a nuking bot (and trying to hide it), unless i'm just being too pessimistic
not sure if that's allowed here
its not, i just have a bot to purge a select amount of messages in a channel because its the easiest way to do so
if it was a nuking bot, it wouldnt ask for the amount of messages, it would trigger automatically, and would destroy all channels
what???
set()
yeah, it was just strange that you want to obfuscate a discord bot
that's all
its something i wont change, so i decided to make it horribly unreadable :3
Obfuscate a Discord bot
yeah if the CIA wanted to 
We could probably build one in the Python community to match or best any government tech I reckon. If we really wanted to tbh 
what
why are you using type hints here
you're in the channel specifically for weird things like that
answer pls
_<
Stealth tech. Is kind of what I meant. Sorry. I wouldnโt be surprised if some from the community work in government or building cutting edge tech that isnโt known in the mainstream or open source
relevant at runtime for the library
??????
yeah seems totally fair to me
You are getting sleepy Olivia. Veryy sleepy - bro it is 3am here 
what are you
Donโt poke about the obfuscated discord bot Olivia, Tristian will jump out from the shadows
Iโm a Pythonista
forced by d.py
:3
Can you not just use purge or something like that?
!d discord.TextChannel.purge
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have [`manage_messages`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_messages) to delete messages even if they are your own. Having [`read_message_history`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.read_message_history) is also needed to retrieve message history...
huh interesting api design
this is nonsense
Proprietary technology really has brainwashed programmers. Any real builder of proprietary software working at any company knows what real โnonsenseโ looks like.
markov chain check?
can we replace chatgpt with this guy
Yeah it's cool, I appreciate systems that work with runtime type annotations while also allowing static typing to be valid
Iโm not sure if that is a compliment or Iโm getting fried ๐
where the heck is esoteric stuff in this convo
here's an infinite echo program in my esolang ```py
f"> "$!<$>$<\f
esoteric like asking if the Python standard library has a library for ABI programming 
link to runtime of lang
runtime?
well you said its in "your" esolang if its a lang it must have a runtime
it's unimplemented bcause they took my pc away โโฆโ
or a place where it could run
so the link is in future
it has a partially running prefix-based implementation on my local pc though ^-^
but that's old so i'll change it when i get my pc back in 2 months
There's both a stable and unstable C api for the runtime if that's what you're asking!
Hmm we can get more esoteric. ABI vs API 
f # label
"> " # string
$!< # print(..., end="")
$> # input()
$< # print(...)
\f # goto `f`
that's fun
Thatโs looks more like on the api side of python ๐
can you access cmdline args?
$|
now make it look like assembly and you get Pyssembly
i knew i just didnt use it for some reason

leap year from input.... ```py
$>:4%?n:'25%?y'400%?ny"yes"\fn"no"f$<
$>:4%?n:'25%!1,'400%!=?("yes"\f)n"no"f$<
!e
# simple python operator tutorial
# created by bulmenisaurus. part of the timed programming session. time spent coding: 437 seconds (~7 minutes).
a=b=1
a=โ=b # -> true
a!=b # -> false
# integer division (repeating operator means integer result)
print(a // b) # -> 1
# ** means integer multiplication
a, b = 10, 5
print(a *โ* b) # -> 50
# same with modulo (python uses %)
print(a %โ% b) # -> 0
# like other c like lanaguages, python has -- and ++
print(+โ+a) # -> 11
a--โ
print(a) # -> 10
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 1
002 | 50
003 | 0
004 | 11
005 | 10
yeah!
its actually a really neat idea
lkfdjdsklf
i kind of wanna steal it
languages dont have to have an implementation
looks correct
right, I was wrong at that time
Lmao
is there any case when python would optimize the local name away during compilation?
!e
import dis
def test():
x = 2
y = x + 2
return y
dis.dis(test)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 2 0 RESUME 0
002 |
003 | 3 2 LOAD_CONST 1 (2)
004 | 4 STORE_FAST 0 (x)
005 |
006 | 4 6 LOAD_FAST 0 (x)
007 | 8 LOAD_CONST 1 (2)
008 | 10 BINARY_OP 0 (+)
009 | 14 STORE_FAST 1 (y)
010 |
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/RI45OXGY75DBOMADV27ZZIDHWI
E.g. optimize out x in a case like this
I was just watching talk and got an impression that compiler does it, but I've never the case when it actually would work.
Maybe this part of the talk was just a way to introduce constants folding, when a = 25 + 19 would actually be optimized to a = 44, idk
A bit dangerous optimising bytecode - it changes the side-effects (but with this measure any bytecode optimisation would be dangerous). Maybe it could...
I just don't see why it wouldn't be possible to optimize those variables that juse use literals
not in current cpython
it might jit to be more optimised at runtime but it wont ever elide x entirely, i think
because its hard to know whether x will be used later in some mysterious way
!e py def checkNumber(digit=15): even = True number = 0 while number < digit: number += 1 even = not even print(f"Number: {number}, Even: {even}") checkNumber()
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | Number: 1, Even: False
002 | Number: 2, Even: True
003 | Number: 3, Even: False
004 | Number: 4, Even: True
005 | Number: 5, Even: False
006 | Number: 6, Even: True
007 | Number: 7, Even: False
008 | Number: 8, Even: True
009 | Number: 9, Even: False
010 | Number: 10, Even: True
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/SMU2CPOH6CEWPQYIH5WHTA6DWI
e.g. ```py
def f():
x = 2
y = x + 2
print(y, locals()["x"])
you cant optimise x out here, because its still needed later
inspect.getframeinfo(frame, context=1)```
Get information about a frame or traceback object. A [`Traceback`](https://docs.python.org/3/library/inspect.html#inspect.Traceback) object is returned.
Changed in version 3.11: A [`Traceback`](https://docs.python.org/3/library/inspect.html#inspect.Traceback) object is returned instead of a named tuple.
really what this means is that you can only perform this optimisations in trivial cases
and at that point its not really worth the time taken while implementing and the maintenance burden and what not
!e
import inspect
frame_log =[]
def f():
x = 2
y = x*2
frame_log.append(inspect.currentframe())
f()
print(frame_log[0].f_locals["x"])
You never know when it's still needed :)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
2
!e
import inspect
frame_log =[]
def not_suspicious_func():
frame_log.append(inspect.currentframe().f_back)
def f():
x = 2
y = x*2
not_suspicious_func() # Nothing would went wrong right?
f()
print(frame_log[0].f_locals["x"])
Even better
:white_check_mark: Your 3.12 eval job has completed with return code 0.
2
couldn't it optimizepy def f(): x = 2 y = x * 2 return ytopy def f(): x = 2 y = 4 return ythen? That would get rid of the multiplication of two constants but keep all the names
in this specific case, yes that would be feasible
but you run into this
in more complicated cases you can run into things like closures or some such
I suppose it wouldn't make a difference in most cases since the compiler doesn't have much to reason with
yeah
also it leads to like 0 actual performance boost when profiling
!e ```py
import dis
def test():
x = 2
y = x + 2
return y
dis.dis(test)
:white_check_mark: Your 3.13 eval job has completed with return code 0.
001 | 2 RESUME 0
002 |
003 | 3 LOAD_CONST 1 (2)
004 | STORE_FAST 0 (x)
005 |
006 | 4 LOAD_FAST 0 (x)
007 | LOAD_CONST 1 (2)
008 | BINARY_OP 0 (+)
009 | STORE_FAST 1 (y)
010 |
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/URVX2IIML3QJM4G3DAKCCFAVRM
there is LOAD_FAST_LOAD_FAST though
which i think is cute
!e ```py
import dis
def f():
x = 1
x + x
dis.dis(f)
:white_check_mark: Your 3.13 eval job has completed with return code 0.
001 | 2 RESUME 0
002 |
003 | 3 LOAD_CONST 1 (1)
004 | STORE_FAST 0 (x)
005 |
006 | 4 LOAD_FAST_LOAD_FAST 0 (x, x)
007 | BINARY_OP 0 (+)
008 | POP_TOP
009 | RETURN_CONST 0 (None)
!e [i for i in [(x:=3)]] what cruelty thine inflict upon me, python!
:x: Your 3.13 eval job has completed with return code 1.
001 | File [35m"/home/main.py"[0m, line [35m1[0m
002 | [i for i in [([1;31mx:=3[0m)]]
003 | [1;31m^^^^[0m
004 | [1;35mSyntaxError[0m: [35massignment expression cannot be used in a comprehension iterable expression[0m
@shut zealot that's why ucd has the dunder import, but not sys, btw
also import unicodedata as ucd is a federal law
Huh I'm a little surprised that doesn't work, interesting
!e (@versed eagle too) No, nothing is sacred :) ```py
from fishhook import hook, orig
@hook(int)
def mul(self, other):
return orig(self, other) + 1
def f():
x = 2
y = x * 2
return y
print(f())
:white_check_mark: Your 3.12 eval job has completed with return code 0.
5
in this case it would actually be free to optimise because fishhook relies on implementation details
but yes, it is possible to alter things in such a way that the program would no longer have the expected result were the optimisation applied
a more agnostic (but still implementation detail dependent) way to do this would be with tracing functions
I wonder if it would be possible to do something like using inspect/traceback to schedule code to run at a specific line number.
Since there was that goto implementation posted here a while back
one would either have to alter the running code object or use a tracing function for that
it seems the only possible "mysterious" way to access a local is locals(), everything else involves explicit LOAD_CONST, so it is possible to recognize when variable can be optimized away in the most cases
vars()
eval("x")
inspect.currentframe().f_locals / inspect.currentframe().f_back.f_locals for non-local action
Those are even harder to imagine being actually used
pretty much, if you allow any expression or statement that isnt setting x or y in these specific ways then your optimisation is invalid
I thought f-strings are using vars too but they seem to access consts directly
!e
def test(): x = 25; print(f'x = {x}')
import dis
dis.dis(test)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 1 0 RESUME 0
002 | 2 LOAD_CONST 1 (25)
003 | 4 STORE_FAST 0 (x)
004 | 6 LOAD_GLOBAL 1 (NULL + print)
005 | 16 LOAD_CONST 2 ('x = ')
006 | 18 LOAD_FAST 0 (x)
007 | 20 FORMAT_VALUE 0
008 | 22 BUILD_STRING 2
009 | 24 CALL 1
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/T6JHUN3IPSV35W3WL22NV26YCA
It was a very questionable choice, but I do have production code that uses inspect.currentframe().f_back.f_locals for rust-macro-like ergonomics.
(The corruption of spending too much time in eso-py)
their likelihood of use doesnt really matter, unless you're proposing to change python's semantics so that they arent valid anymore
Yeah, such optimizations would definitely need some form of contract with programmer that they're aware those optimizations come at the cost of dynamic locals access.
oh i see
you want to optimise a subset of python, rather than python itself
i would recommend checking out RPython
I'm not familiar with them, but I'd think the compile-to-c flavors of python like Cython or Nukita have some sort of restriction like that
i dont know about Nukita, but Cython also changes the syntax and adds extra sorts of things
RPython is a strict subset of python
are those 3 cython nuitka and rpython are basically separate languages with their own compilers?
I was thinking more of something like what numba does, some kind of @optimize decorator that would recompile the byte code
!e ```py
from fishhook import hook
@hook(int)
def mul(a, b): return 17
a, b = 2, 2
print(a * b)
print(2 * 2)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 17
002 | 4
(there's also dynamic locals storage but meh.)
!e
import inspect
def not_suspicious_func():
inspect.currentframe().f_back.f_locals["x"] = 0
def f():
x = 2
not_suspicious_func() # Nothing would went wrong right?
y = x*2
f()
:warning: Your 3.12 eval job has completed with return code 0.
[No output]
i'm seeing less sys._getframe() and more inspect.currentframe()
is = equivalent to .__set__() ?
I want to use in pytorch as it is not allowing me to use two = operaters in one line.
when assigning to an instance attribute, it calls it
but it doesn't mean the attribute gets assigned when calling .__set__(), so it's not necessarily equivalent
:incoming_envelope: :ok_hand: applied timeout to @gilded fiber until <t:1745331387:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
have you seen this?
!e
def test():
try:
return 42
finally:
return "Unexpected"
print(test())
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Unexpected
I didn't know that there is a such esoteric feature in python
!pep 765
yeah, that's how I've learned this was a thing
It's not even discarding the full return statement, it just not returning the value
!e
def x():
print('hey')
return 32
def test():
try:
return x()
finally:
return 23
print(test())
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | hey
002 | 23
Yep
Because it got the value
And
Hey time to return ->
Oh wait I need to do finally first, I cannot just leave that
Done finally
Oh such a shame I already returned, guess I cannot return again now
Imagine that it's something like:
On return:
set $return_value to return value!
raise ItsTimeToReturnIGuessException (cached by default on function call)
Therefore:
try:
return stuff
finally: # Runs after any interrupts leaving the try cause, so exceptions, ItsTimeToReturnIGuessException and just_leaving_the_scope_dont_mind_me_exception
return sneaky # we'll catch "the exception" and set the SPECIAL VARIABLE OF RETURN to ``sneaky``
!e py import os for i in range(10000000): os.mkdir(str(i))
!e py import os for i in range(10000000): os.mkdir(str(i))
:warning: Your 3.12 eval job timed out or ran out of memory.
[No output]
and who now can say that there are no goto statements in python ๐
i'm going down the pympler rabbit hole, measuring the size of all my Python objects. something i haven't figured out yet is measuring the memory overhead of loading a module.. pympler's output is strange when pointed at a module
!e
a = {"a": 25, "b": 42}
lst = [a]
b = {"b": 42, "a": 25}
print(b in lst)
a = [1, 2, 3]
lst = [a]
b = [1, 2, 3]
print(b in lst)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | True
002 | True
omg, I didn't know contains is using == to figure the matching object, I thought it would be using is
!e
code
!e note that is and == is the same for most mutable objects, except lists and dicts, sets and anything else that has custom equality checking implemented ```py
def find_using_is(arr, el):
for idx, i in enumerate(arr):
if i is el:
return idx
arr = [-4, 77, 8394]
print(find_using_is(arr, -4))
print(find_using_is(arr, 77))
print(find_using_is(arr, 8394))```
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
ok this was unexpected to me, my python 3.12.7 returns none for the third one
yeah, that's probably what gave that impression that in, .remove, .index and .count (maybe something else?) is using is instead of ==
Now I can only hope I haven't introduced some weird bug anywhere because of this assumption
!e ```py
def find_using_is(arr, el):
for idx, i in enumerate(arr):
if i is el:
return idx
arr = [-4, 77, 8394]
print(find_using_is(arr, -4))
print(find_using_is(arr, 77))
exec('print(find_using_is(arr, 8394))')
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 0
002 | 1
003 | None
if you use the same int literal in a compilation unit multiple time, it'll only get created once
it's classic literals ids thing
!e
a = (1,2,3)
b = (1,2,3)
print(a is b)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
True
yeah in idle you execute it line by line instead of all at once
!e ```py
def find_using_is(arr, el):
for idx, i in enumerate(arr):
if i is el:
return idx
arr = [-4, 77, 8398]
print(find_using_is(arr, -4))
print(find_using_is(arr, 77))
print(find_using_is(arr, eval('8398')))
print(find_using_is(arr, arr[2]))```
btw anything else is using == this way besides those lists operations?
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 0
002 | 1
003 | None
004 | 2
do you mean list.__eq__ or the .__eq__ of the list's elements?
I mean ".__eq__ of the list's elements"
!e ```py
class x:
eq = lambda a, b: print("done") or a is b
l = [x(), x()]
m = l.copy()
n = [x(), x()]
print("m:")
l == m
print("n:")
l == n
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | m:
002 | n:
003 | done
list.__eq__() does both is and ==, btw
when does it use is?
probably a shortcut to avoid checking elements of itself
before it uses ==
it first checks a is b, and if that is False, it does a == b
this causes it to be wrong with NaN
it would make sense if it checked len too (after ensuring the other is a list too)
oh, I see, makes sense
!e ```py
class x:
eq = lambda a, b: print("done") or a is b
l = [x(), x()]
n = [x()]
l == n
:warning: Your 3.12 eval job has completed with return code 0.
[No output]
in this case it checks the is of the elements, because id(l) != id(m), right?
mmhm.
gotcha
!e
class x:
__eq__ = lambda a, b: print("done") or a is b
l = [x(), x()]
n = [x()]
print(l == n)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
False
!e py from math import nan a = eval('[nan]') b = [eval('nan')] print(a == a, a == b, a[0] == b[0], a[0] is b[0])
:white_check_mark: Your 3.12 eval job has completed with return code 0.
True True False True
how is the second one True tho?
sometimes I feel like this channel is some kind of Python related jazz club
both reference the same nan
so, you know.. is equality
oh right it's the same nan ๐คฆโโ๏ธ
i mean- it's like speakeasies, maybe
weird activity going on and concealed from the public.. sorta :3c
!e ```py
t=b"5966235733 12250270781 225129188 1169776007 7209451424 12849676943"
from hashlib import md5
exec(b'print('+b'\n'.join(md5(c).digest() for c in t.split())+b'\n)')
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello!
This is a stupid way to store data
Hello, backdoor!
is there a sneaky way to print something without calling print or builtins? like print(x) but in 5 characters?
open(1,'w').write(...) I guess but that's not a lot shorter
ye... it gets sent to eval() must be 5 characters exactly. x holds my valuable goodies.. this is for a CTF i shouldnt even be asking here but this is where i come when i need esoteric python knowledge
It's certainly got me curious; languages like Ruby and Perl have super-terse ways to access STDOUT but I can't really think of one in Python?
Does it need to print only x?
ya... i think so or trick into dumping contents of the variable
It's probably going to be ||{}[x]||
Yeah, that's why I'm asking
hmm that doesn't seem to get executed
tricky challenge thanks for your help! im thinking there is a way to crash the program and spit out the contents in an error message but their error handling is good so i dunno. will post the challenge here after the CTF and see what ya'll think
Does it have to be stdout? Or any?
!e
import this
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | The Zen of Python, by Tim Peters
002 |
003 | Beautiful is better than ugly.
004 | Explicit is better than implicit.
005 | Simple is better than complex.
006 | Complex is better than complicated.
007 | Flat is better than nested.
008 | Sparse is better than dense.
009 | Readability counts.
010 | Special cases aren't special enough to break the rules.
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/3FJ23ANHL2E67OQUB734IG4BYU
import __hello__ doesn't want to work ;-;
a related puzzle with a silly solution: what is the shortest python code that prints a pangram, i.e. the output has every letter a-z at least once (case insensitive)
Does it require any specific running environment?
not that I know of
vars() in repl
w=[];w[0]#jvq
Because you didn't require me a specific environment
ah, I see what you mean now. I meant running the file directly as opposed to the repl, and output to stdout
!e
print(vars())
:white_check_mark: Your 3.12 eval job has completed with return code 0.
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fef7d488dd0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/main.py', '__cached__': None}
Hmm do you have a specified filename?
it should work regardless of filename
Ok
no stderr? ๐ข
!e
print(globals())
:white_check_mark: Your 3.12 eval job has completed with return code 0.
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fb58cdd8dd0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/main.py', '__cached__': None}
I'm pretty sure the stdout solution beats any stderr abusing one, but you can try ๐
!e print(dir())
:white_check_mark: Your 3.12 eval job has completed with return code 0.
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
I can do 10 with stderr but I get the feeling that yours is going to be shorter ```
esmecat@papaya:~$ python3 -c "[]['zvqj']"
<string>:1: SyntaxWarning: list indices must be integers or slices, not str; perhaps you missed a comma?
Traceback (most recent call last):
File "<string>", line 1, in <module>
[]['zvqj']
~~^^^^^^^^
TypeError: list indices must be integers or slices, not str
ya i have no idea how to do this...
Click here to see this code in our pastebin.
This is not support channel, please go to #1035199133436354600 or #python-discussion
If you are not sure about the channel topic, read it
i know its not support i just thought this qualified as esoteric thought i'd share sorry to break your rules ๐ฆ
len=0 your code just break and exit :)
Only take 2 input where first is that and second whatever
Assuming I remember exec at the right scope
try: exec(guess) is a very strange way to do target == guess. You also introduce such false positives as "print", "input", "super", "bytes", "float", "round", and "slice" not to mention the one mentioned above
I think it meant for eval code execution
ya your code gets executed and if you get all green it ran without error if not then all red.
so you need to somehow compare individual indexes of the f string maybe hell i dunno
if you're looking to do something nasty then perhaps you could try golfing the guess result rules. As your code is I don't think it quite has the same behaviour has wordle (which I assume is what you're trying to emulate)
ya its evaldle! i didnt write it, part of a CTF competition, python jail challenge.
So what is the challenge?
ah that makes more sense
well you connect to the server, and somehow need to get the contents of f which is flag.txt on the server's system.
flag for mat usualy like pwnctf{l337FLAGTIMEWOOT}
you should try some its a lot of fun. much fun. such challenge
I searched subset of function that is <= 3 char
But only thing I find helpful is combining int and min
Where you can take a min of the string, and integer it
Which gives you less constraints
If you can replace it to len
But only if you can combine it
so basically you need to leak the flag, but you can only output information via erroring/not erroring?
Well, you have multiple round of exec
So you might able to inject stuff
I figured out how to create arbitrary length string now
But storing eval/exec require 6
a=exec
For example
I think someone already mentioned a way to do this
Who
If I can have exec where the function name is <2character, I can run arbitrary code
if you have multiple runs, you can maybe binary search it one character at a time
like
k='a'
j=k>f
1/j
``` could tell you if codepoint of the first character is greater or less than `'a'`
and then once you get the first character just make k longer
What the binary search for
Oh f is already the string?
I thought it was the file handle the whole time lmao
you are on the right track, im waiting for a writeup. systematically comparing each item against an alphabet seems to be the only way
maybe using eval you get to modify the program somehow
idk if it was mentioned alreafy
check out my similar writeup
it's in croatian so pls translate it
eval takes expressions, not statements
but things such as [a:=3] and setattr(a,1,2) are expressions
it's exec, not eval
this makes sense
.
Unless you can modify len to something usable first, you only get 5 char each time
Best bet is convert len to eval
a=eval
len=a
But require min 6 currently
!e
f="secret" # outside eval
k=int
k(f)#
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 4, in <module>
003 | k(f)#
004 | ^^^^
005 | ValueError: invalid literal for int() with base 10: 'secret'
Would this work?
Or have to not error
Oh wait nvm I forgot the except
Thinking how to cause a warning
syntaxwarning
is probably the easiest
or deprecation warning but those are unlikely to print anything useful i think
Syntax cannot print something useful
i mean unless there's some other 1-char function in the environment you can hook len into your best bet is getting 1 bit at a time
You can use 3 char
k=abc
len=k
But I checked but nothing seems work
Top 10 bugs I don't wanna meet in production code
!e
def run(gen):
next(gen)
def main():
x = 42
gen = (i for i in range(20) if i >=15 and (x:=i))
run(gen)
print(x)
if __name__ == "__main__":
main()
:white_check_mark: Your 3.12 eval job has completed with return code 0.
15
*features
yeah, it's not very welcomed both as a feature and as a bug it might become ๐
It's probably working in similar way to closures from nonlocal
yeah? what's unexpected about this?
closure captures x as an assignment target, you invoke the generator which invokes the closure to get a value, the first one being 15 since i >= 15 is true and x := 15 -> 15 is also true
side effect is assignment to x
this, isnt a bug,,,
i mean, it should be defined in the assignment expressions PEP so it's definitely not a bug
more about it here: https://peps.python.org/pep-0572/#scope-of-the-target
I mean it is explainable, it's just very weird when some function very far away can change local variable in another function.
I meant not that this particular code has a bug, but that it could easily introduce one
well no, it's static scoping
!e ```py
def a(it):
x = 36
print('a', x)
print(next(it))
print('a', x)
def b():
x = 42
print('b', x)
a((x := i for i in range(5)))
print('b', x)
b()
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | b 42
002 | a 36
003 | 0
004 | a 36
005 | b 0
it can't change anything "very far away" no more than a normal closure function
That's understandable that it cannot change a scope, I was more worried that it may unexpectedly change x in b.
But yes, it's the same thing as with nonlocal closures.
!e ```py
import math as math;
class console:
def init(self):
pass;
def log(x):
print(x);
text = list("i am not sorry");
if True: console.log(str("".join(text)));
:white_check_mark: Your 3.12 eval job has completed with return code 0.
i am not sorry
this is the worst piece of code i have ever written in my life
what. why would you make "i am not sorry" a list???
hi
to give the letters a bit more room to breathe :)
why not
!e ```py
console = type("console",(),{"log":print});
text = [...,"okay"],;
if [] == []: console.log("%s"*~-len(text)%text[()==():]);
:white_check_mark: Your 3.12 eval job has completed with return code 0.
okay
The init is not necessary
it is, because it's important that every class has a pass;
Hi there! I don't know if this is the perfect place to ask this question (I'm new here).
In my python programming class we noticed that the first 128 integers seem to be preloaded by the python interpreter. That is, despite the fact that integers are immutable, new variable declarations seem to point to the same place in memory. If I declare two large integer variables x,y to the same number, the statement 'x ==y' is true but the statement 'x is y' is false. This isn't true for these special lower integers. 'x is y' evaluates to true!
Does anyone know why this is happens? Is it an intentional optimization, because low integer numbers are used frequently?
It's an optimisation, yes
it's an implementation detail for the main python implementation, yes
basically, every integer in range(-5, 257) (-5 to 256 inclusive) is preloaded
if it's <= -6 or >= 257, the integer is not preloaded
it makes them happy
Idk what channel to ask this in so: is these 2 things equal in what they do, cuz someone on a dif server told me to use match/case instead of the severe If spam
Equal in that there's a SyntaxError in both.
But generally speaking, you can replace simple if-elif-elif-... chains with match-case, but match-case is more than just that, it matches patterns.
(and regular if is better for complex conditions, I'd say)
(Also at the risk of stating the obvious, your if code checks every case top to bottom, and the match code stops when it finds the first match.)
(using elif would prevent it)
So match/case is the same as If-Elif-Elif-... and both would stop at the first match, whats wrong with it? Im making a BF interpreter with some additions (0123 for example)
The argument you see here a lot is that it's for 'pattern matching' not 'multi-if'.. but I don't personally find it so objectionable.
So it can be used for both but If/Elif can be used for more complicated conditions, so for an equality check its fine to just do match/case?
Yeah; here's the original writeup on what it is 'for', but it will work fine in this situation too https://peps.python.org/pep-0636/
e.g.
match command.split():
case ["go", ("north" | "south" | "east" | "west") as direction]:
current_room = current_room.neighbor(direction)
``` is kind of the motivating story
But they show an example of HTTP status codes, and I personally think it's fine to use there too
Other people feel differently and like to use if/elif whenever they aren't using the 'full' features of match/case.
Im using it I guess, it looks neater
Are you actually trying to make a brainfuck interpreter
Unless Iโm using features from match-case that if-elif-else donโt offer, I always use if-elif-else, since to me a slightly more noisy condition statement is well worth one less level of indentation.
!e
class Thing:
order = 0
@classmethod
def __lt__(cls, other: type) -> bool:
if not issubclass(other, Thing):
return NotImplemented
return cls.order < other.order
class BigThing(Thing):
order = 1
class LittleThing(Thing):
order = -1
print(BigThing < LittleThing)
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 16, in <module>
003 | print(BigThing < LittleThing)
004 | ^^^^^^^^^^^^^^^^^^^^^^
005 | TypeError: '<' not supported between instances of 'type' and 'type'
is there a way around this?
you need a metaclass
!e
class Thing(type):
order = 0
@classmethod
def __lt__(cls, other: type) -> bool:
if not issubclass(type(other), Thing):
return NotImplemented
return cls.order < other.order
class BigThing(metaclass=Thing):
order = 1
class LittleThing(metaclass=Thing):
order = -1
print(BigThing < LittleThing)```
:white_check_mark: Your 3.12 eval job has completed with return code 0.
False
The class of a class. Class definitions create a class name, a class dictionary, and a list of base classes. The metaclass is responsible for taking those three arguments and creating the class. Most object oriented programming languages provide a default implementation. What makes Python special is that it is possible to create custom metaclasses. Most users never need this tool, but when the need arises, metaclasses can provide powerful, elegant solutions. They have been used for logging attribute access, adding thread-safety, tracking object creation, implementing singletons, and many other tasks.
More information can be found in Metaclasses.
oh nice
Why is __lt__ a classmethod there? I'm kind of surprised that works...
!e
class Thing(type):
order = 0
def __lt__(cls, other: type) -> bool:
if not issubclass(type(other), Thing):
return NotImplemented
return cls.order < other.order
class BigThing(metaclass=Thing):
order = 1
class LittleThing(metaclass=Thing):
order = -1
print(BigThing < LittleThing)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
False
it seems to not matter in this situation?
i am perplexed.
!e
class Thing(type):
order = 0
def __lt__(cls, other):
if not isinstance(other, Thing): return NotImplemented
print(cls.order)
return cls.order < other.order
class BigThing(metaclass=Thing): order = 1
class LittleThing(metaclass=Thing): order = -1
print(BigThing < LittleThing)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 1
002 | False
!e ```py
class Thing(type):
order = 0
@classmethod
def lt(cls, other):
if not isinstance(other, Thing): return NotImplemented
print(cls.order)
return cls.order < other.order
class BigThing(metaclass=Thing): order = 1
class LittleThing(metaclass=Thing): order = -1
print(BigThing < LittleThing)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 0
002 | False
it's a coincidental matter :p
the use of @classmethod uses Thing.order, which is 0
the not-use would utilize BigThing.order, which is 1
coincidentally, both values are not less than the value of LittleThing.order
(1 < -1 => False, 0 < -1 => False)
python assignments are truly confounding-
instead of following the unwritten(?) rule of closest first, it executes in first-written first order
@spam
@ham
def eggs(): ...
# eggs => ham => spam
-~x
# x => ~ => -
a = b = 42
# 42 -> a -> b
binary operators would be a better analogue, in particular comparison chains
but it's goofy yea
a, b = a[b] = {}, ()
evaluation jumping from right to left to middle, you can't even conceptualize the assignments as parallel
ne foda
ayo, another three letter username spotted in the wild
NE1 IN?
every three letter username on this discord probably reads this channel
https://github.com/ani-2008/MindFuck
Hey guys, I built an interpreter for a language like BrainF*ck named MindF^ck. ig I can post it here, I will welcome your feedback
main.py line 42
if memory_pointer < 30000:```
https://github.com/ani-2008/MindFuck/blob/main/main.py#L46
sys.stdin.read(1) would provide a much better user experience
main.py line 46
get_in = input()```
!e
import sys
import ctypes as ct
import string
Py_TPFLAG_HAVE_GC = 1 << 14
NULL = 0
__used_list__ = set()
if sys.platform.startswith("linux"):
libc = ct.CDLL("libc.so.6") # Linux
elif sys.platform.startswith("win"):
libc = ct.CDLL("msvcrt.dll") # Windows
else:
raise OSError("Could not find clib!")
class AllocationError(MemoryError): ...
class FreeError(MemoryError): ...
class DoubleFreeError(FreeError): ...
malloc = libc.malloc
malloc.argtypes = [ct.c_size_t]
malloc.restype = ct.c_void_p
free = libc.free
free.argtypes = [ct.c_void_p]
memcpy = libc.memcpy
# dest src n
memcpy.argtypes = [ct.c_void_p, ct.c_void_p, ct.c_size_t]
def malloc_obj(obj) -> ct.c_size_t:
addr = malloc(size := sys.getsizeof(obj))
if addr == NULL:
raise AllocationError(f"Failed to allocate object of size {size}!")
memcpy(addr, id(obj), size)
new_obj = ct.cast(addr, ct.py_object).value
# We should un-set Py_TPFLAG_HAVE_GC to prevent the object from being
# garbage collected but there does not seem to be a consistent,
# cross-platform way to find the offset of the tp_flags member on a
# PyTypeObject, so we 'manually' increment the refcount by adding
# the new object to a global set to prevent Python from trying to
# free it
global __used_list__
__used_list__.add(new_obj)
return new_obj
def free_obj(obj):
# We let Python free the object lazily as explicitly freeing it would cause
# a double free at the end of the program when Python tries to free
# all leftover objects.
# This should also prevent use-after-free since Python will keep the object
# until it is sure that there are NO references to it anymore
try:
global __used_list__
__used_list__.remove(obj)
except:
raise DoubleFreeError("tried to free object that was never allocated")
my_string = malloc_obj("Hello")
print(my_string)
free_obj(my_string)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello
huh..?
oh..
oh..
umu.
!e ```py
import sys
import ctypes as ct
import string
NULL = 0
used_list = set()
if sys.platform.startswith("linux"): libc = ct.CDLL("libc.so.6")
elif sys.platform.startswith("win"): libc = ct.CDLL("msvcrt.dll")
else: raise OSError("Could not find clib!")
class AllocationError(MemoryError): ...
class FreeError(MemoryError): ...
class DoubleFreeError(FreeError): ...
malloc = libc.malloc
malloc.argtypes = [ct.c_size_t]
malloc.restype = ct.c_void_p
free = libc.free
free.argtypes = [ct.c_void_p]
memcpy = libc.memcpy
dest src n
memcpy.argtypes = [ct.c_void_p, ct.c_void_p, ct.c_size_t]
def copy_obj[T](obj: T) -> T:
addr = malloc(size := sys.getsizeof(obj))
if addr == NULL:
raise AllocationError(f"Failed to allocate object of size {size}!")
memcpy(addr, id(obj), size)
ct.c_ssize_t.from_address(addr).value = 1
new_obj = ct.cast(addr, ct.py_object).value
global used_list
used_list.add(new_obj)
return new_obj
def free_obj(obj):
try:
global used_list
used_list.remove(obj)
except KeyError:
raise DoubleFreeError("tried to free object that was never allocated")
one = 1
other = 1
obj = copy_obj(one)
print(one, obj)
print(one is other, one is obj)
free_obj(obj)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 1 1
002 | True False
hehe. non-cached 1
Ig it should be like if memory_pointer <= 29999:
thanks forgot about this I have updated
What if I take macOS?
Also I don't think adding/remove from list require global
makes it clearer, idk. i just repurposed a function from the original :^
Oh well
I recently came across something really baffling, I guess python normalizes line endings before running?
I would imagine the lexer replaces the platform-specific line endings with a universal representation?
Oh, in a string like that though? Weird.
!e ```py
print(f"\n={ord("\n")} \r={ord("\r")}")
exec("print(ord('''\r'''))")
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | \n=10 \r=13
002 | 10
I wonder if you ran this on an old Mac with native \r lien ends it would give 13, or if itโs always 10
I guess Iโd hope it would always be 10, since otherwise it could/should fail on a system with \r\n as the native
!e exec("print(ord('''\r\n'''))")
:white_check_mark: Your 3.12 eval job has completed with return code 0.
10
Thatโs also slightly cursed, what looks like a multi char ord ends up working
yeah it is a bit silly but overall a good design choice probably

!e```py
import ast
from linecache import*
import sys as s
from traceback import*
s.excepthook=lambda t,v,tb:getattr(builtins,(c:=ast.parse(getline((e:=extract_tb(tb)[-1]).filename,e.lineno)).body[0].value).args[0].value)(c.func.id)if issubclass(t,NameError)else s.excepthook(t,v,tb)
Hello_world("print")
:x: Your 3.12 eval job has completed with return code 1.
Hello_world
black formatting my spaghetti
try
I wonder what it will do to my 16k char hello world
let me try
lol
fun fact, python has a built-in formatter
!e ```py
from ast import unparse, parse
print(unparse(parse(r'''
console = type("console",(),{"log":print});
text = [...,"okay"],;
if [] == []: console.log("%s"*~-len(text)%text[()==():]);
''')))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | console = type('console', (), {'log': print})
002 | text = (*[..., *'okay'],)
003 | if [] == []:
004 | console.log('%s' * ~-len(text) % text[() == ():])
not that it does a good job, but it expands code, at least
that's fun!
niiice
back in the dayโข๏ธ (about 7 years ago) i made a 400MB tic-tac-toe script that would get a segfault on anything less than 64GB of RAM. unfortunately i don't have that script on hand but i can try to recreate it
I would like to see that
(I got 16GB of ram)
hehe i'll work on it tonight then!
i remember how i made it, just gotta do it again
so true 
print(bytes((sum(range((-~True + True) * ~True * ~True)) + sum(range(~True * ~True)), sum(range(-~True * (~True * ~True -~True + True))) - (-~True + True) * ~True, sum(range((~True) ** (-~True) ** (-~True))) - (-~True + True) * -~True, sum(range(True - True, sum(range(-~True * -~True + True + -~True * -~True)) - sum(range(True - ~True)) - True, -~True * -~True + True)) + sum(range(-~True * -~True + True)) + sum(range(True - ~True)) - True, sum(range(-~True * -~True + True + -~True * -~True)) - sum(range(True - ~True)) - True, (sum(range(-~True * -~True + True + -~True * -~True)) - sum(range(True - ~True)) - True) * -~ True + ~True * ~True, sum(range((-~True * -~True + True + -~True * -~True) * -~True - True)) - sum(range(-~True * -~True + True + -~True * -~True)) + True, sum(range((-~True - ~True) * -~True, sum(range(True - ~True, sum(range(~True * ~True)) + True)))) - sum(range((-~True - ~True) * -~True + True, (-~True - ~True) * -~True - ~True)) - True, sum(range(sum(range(~True * ~True)) + True, sum(range(~True * ~True - ~True)) - ~True)) - ~True, sum(range(-~True * -~True + True + -~True * -~True)) - sum(range(True - ~True)) - True, sum(range((~True) ** (-~True) ** -~True + ~True)) + ~True, sum(range(~True * ~True + True, (~True) ** (-~True) ** -~True)) + True)).decode('utf' + str((-~True) ** (True - ~True))))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Haru Desu Yo
gotta make sure it's pep8-compliant then you'll be good to go
got back home from work and recreated the tic-tac-toe script. this is how much memory it uses to run
3.3 million lines of code (excluding blank lines) and they're all PEP8 compliant!
Please react with โ
to upload your file(s) to our paste bin, which is more accessible for some users.
i'm not entirely sure the paste bin would appreciate it
but thank you
for anybody curious of how i generated it: https://gist.github.com/skrungly/0c33c46a0dc041617ed3d60484e8dcd8
Click here to see this code in our pastebin.
Bro.
๐ there's GOTTA be a better way
what do you mean? this way is perfect
Do chess next.
defining a function, within a function; while recursing with a loop 
the gist contains an updated version where the recursive function is external
because i realised that was a bit unnecessary
i don't even want to think about the disk space that would require
kinda reminds me of this https://andreasjhkarlsson.github.io//jekyll/update/2023/12/27/4-billion-if-statements.html
I recently stumbled upon this screenshot while researching social media on the train. Of course, it was followed by a cascade of spiteful comments, criticizing this fresh programmerโs attempt to solve a classical problem in computer science. The modulus operation.
oh yeah! that's a fun one
i feel like that one is simpler.. but 330GB is insane
the tic-tac-toe script is only a mere 180MB
Reminds me of my solution to AoC day 5 generation code and resulting regex
This was only for part 1, basically finding numbers around asterisks in 2D and multiplying them, made 33k chars long by fixed width look back
*misremembered the day, it was actually day 3 https://adventofcode.com/2023/day/3
the deep protocols
word soup
Time cube moment
sub-Planck is funny
peaked to 11gb when compiling to bytecode
yep! mine was the same.
it's not as bad as the original one i made a few years back, but i don't even know if that one worked properly
so at least this one worksโข๏ธ
:incoming_envelope: :ok_hand: applied timeout to @brisk zenith until <t:1746881262:f> (10 minutes) (reason: newlines spam - sent 106 newlines).
The <@&831776746206265384> have been alerted for review.
oops
been a while
anyways, let me try that again
(actually, i will do it in a bit)
something doesn't quite add up with the tictactoe generator script. apparently there are meant to be 255,168 possible games of tictactoe, but i tried modifying the script to count the games and it comes out with 256,104 (so a discrepancy of 936). i have no idea why though
rip
easily done, i'm just a bit stupid
so it's generating 936 unused code paths? disappointingly inefficient, literally unusable
also: ship it
haha exactly
this is the script i used to count it (without generating the actual code)
search it up
btw, did you know that the outcome of tic-tac-toe is already decided by the 2nd turn! /assuming each player plays perfectly.
by the 3rd turn, (only) if player 1 misses the move; player 2 could actually win.
otherwise it's always a draw for p2 .
or an immediate loss, if p2 didn't counter correctly in the 2nd turn.
there aren't that many moves since the board could be rotated in any way...
outcome of ttt is decided at 0 turn (= before the game), assuming each player plays perfectly

same applies for pretty much every other deterministic 2-player game: chess, checkers, go, ...
@errant crescent here, your turn: ```
O | . | .
. | . | .
. | . | X
sort of... problem with ttt is that there are that many moves to the entire game.
it's pretty simple when you look at all of them.
unlike chess which has so many possibilities and moves, which allows for more diverse strategies; and a lot misses.
making the "perfect" move in these games is relatively controversial.
it's a draw. iirc.
O | . | X
. | . | .
. | . | X
```&
```fix
O | . | .
. | X | .
. | . | X
```&
```fix
O | . | .
. | . | X
. | . | X
there are that many moves
so many possibilities and moves
this does not matter
number of games is finite, so there exist a perfect strategy for both players
making the "perfect" move in these games is relatively controversial
not at all
hard to compute? yes, for now
it is
O | . | X
. | . | O
. | . | X
O | . | X
. | X | O
. | . | X
O | . | X
. | X | O
O | . | X
O | . | X
X | X | O
O | . | X
no way to win => draw
You can use symmetry to dramatically reduce this number
Mega Man and other NES games without PRNG are also "deterministically winnable" state machines
ofc you can rotate & flip however much u need; however the strat remains.
now imma delete that comment, since there are 400k members in this server.
huh, that's interesting
try it out yourself. your in for a fun ride.
if each player plays perfectly, its a deterministic game
if you vary the first N moves and then assume optimal play from there, it will also be deterministic based on the starting varied state
this is because ttt is a fully solved game
yes. however since ttt is symmetric, with at most 4 moves per player - before a winner can be decided โ you can determine the win/loss really quickly.
although your statment is correct. the least amount of turns before an outcome can be determined, in this game, is only 2. (one turn for each player).
what you are saying is nonsense
there is a game prefix of 6 moves, after which either player can win
per player
its useful to distinguish between ply and turns here probably
the least amount of turns before an outcome can be determined, in this game, is only 2. (one turn for each player)
this is wrong though: if you assume perfect play, the outcome is decided from the beginning, before any moves at all happen
the only way that you will need moves to determine the outcome is if you assume unoptimal play
which is always a draw by player 2.
though I'd want to give player 1 the possibility of doubt; for when player 2 plays.
because only then, will you, in real life, be able to determine the outcome.
with the right "counter" (2nd move), even if player 1 plays after this perfectly, there's no way to win.
this tbh. (*for the first 2 moves)
This entire discussion reminds me of this video https://youtu.be/QNFQvX-MQgI?si=6GQne9wVRB1inrhL
When it comes right down to it, there just aren't that many ways a game of Tic-Tac-Toe can go down. Join me as we investigate what it means for things to be different, with digressions into music, coding and math.
If you enjoyed this video and want some behind the scenes content, I hope you'll consider supporting me on Patreon: https://www.pat...
and then people like to do bizarre analysis of such simple game
i remember seeing somewhere "if one player plays optimally and the other plays random moves, what's the expected win-draw ratio"
the simplicity makes it possible to do such analysis
its not possible to do this with chess, for example
It is possible, just not with our compute- but there's no reason it couldn't be done. Chess is enumerable- just a very large search space (as an aside; checkers is solved). The DL techniques for chess attempt to estimate the win prob for every move- so you could use that as a reasonable heuristic; assuming DL has reached a level pretty close to perfect play
it is possible, just not with our compute
so its not possible
chess is solvable
but chess isnt solved
I think that's just a limit on your imagination.
They are problems that are provably unsolvable, or require more information than the universe can hold. Chess isn't one of them. I'd bet humans will solve chess at some point
My fav thing solved is Pokemon Platinum: https://youtu.be/jNMWkD5VsZ8
Scripted in Lua not python- but still fun
After getting only a 99.8% chance of success in FireRed, I'm back in Platinum, with several billions of simulations to reclaim those pesky fractions of a percent.
โ ๏ธWARNING: There are several points in the video where sped-up footage creates a strobe effect that may affect viewers sensitive to flashing lights. This occurs most prominently...
did you read what i said
.
.
I was responding to "it's not possible"
chess isnt solved โ it is not possible for us to determine the outcome of a game given an arbitrary starting state and assuming optimal play
my imagination is limited because i stated a fact about our current knowledge of the game?
or do you dispute this
it's not possible *now
yes, that is what i said
it seems like you agree with me, so im not really sure why you tried to start an argument
so i think i will just stop engaging with this conversation now
That was a fun video, though the method they used looked very over complicated to me. Since battles last a different amount of time, that means they make a different number of RNG calls, so I didnโt see why they couldnโt just keep repeating battles until all the seeds converge to the same seed. There might be some cycles, but going full armchair mode I donโt see why there wouldnโt be some consistent short sequence of inputs you could repeat until all the seeds converge, then just tas the game normally
Hmm, it might be a "they'll converge past the heat death of the universe" problem- but also if PRNG only kicks in at battles and encounters- then you are limited by HP and moves. There might not be a super reliable way of syncing them all
Super cool, 10^47 bits is definitely approaching "utilizing an entire star system"- which might not be the best use of resources.
also this reminds me of one of the first programs i posted in here about 7 years ago, which obfuscated strings using True and bit shifts: ```py
bytes([(True ^ True << True ^ True << (True << True) ^ True << (True << (True << True)) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True ^ True << (True ^ True << True) ^ True << (True << (True << True)) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << (True ^ True << (True << True))), (True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True ^ True << (True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << (True << True) ^ True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << (True << True) ^ True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True ^ True << True ^ True << (True << True) ^ True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << (True ^ True << (True << True))), (True << (True << True) ^ True << (True << (True << True)) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True ^ True << (True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << True ^ True << (True << (True << True)) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True ^ True << (True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True)))]).decode()
'why hello there'
there might be cycles
this is the problem
every seed will be in some cycle, and not all of them will be the same cycle
it is indeed harder than the armchair would make you think
to converge every single seed together you need a method that is able to distinguish between arbitrary seeds without direct feedback!
and your only observable change is the outcome of certain random events

Hey everyone, I was doing some code golfing challenges earlier today and came across the following challenge:
Given some user input of integers separated by spaces, check if the list of integers is a valid Fibonacci sequence
IF the sequence is correct: print out "fib"
IF the sequence is incorrect: print out the first instance of an erroneous value
Example inputs and outputs:
"0 1 1 2 3 5 8" # fib
"2 4 6 10 16" # fib
"1 2 3 4 5" # 4
"0 1 1 2 3 21 24 45" # 21
Here is some sample code that provides a solution:
# User inputs a list of numbers as a string, e.g. "1 2 8 3 19 101"
num_list = input().split()
num_list = [int(x) for x in num_list]
# Take out the two starting integers to start the sequence with
a, b, *num_list = num_list
for i in num_list:
# If the next integer i is correct
if a + b == i:
a = b
b = i
else:
# If it is ever not correct, print the erroneous value and exit
print(i)
exit()
# If the loop succeeded in it's entirety, print "fib"
print("fib")
And here is my current shortest amount of characters I've gotten (the site I was on interpreted input() instead of print() as valid solutions)
I=input;a,b,*z=[*map(int,I().split())]
for x in z:
if a+b!=x:I(x);exit
a,b=b,x
I("fib")
I was wondering if anyone could beat my record of 93 bytes here, since I've gotten a bit obsessed with this specific challenge
website?
It was one of the many challenges on Clash of Code: https://www.codingame.com/multiplayer/clashofcode
Unfortunately as far as I know the database of those puzzles may be private
l=input;a,b,*x=map(int,l().split())
for p in x:a+b!=p>l(p);a=b;b=p
l("fib")
``` ?
basically a shrunk down version, so..
yup that'll do it
i need to get back to codingame when i get my pc back =^^=
How exactly does that a+b!=p>l(p) work? I've never seen > like that before
do you know how a < b < c works in python?
I've not seen it anytime recently so if I did I forgot ๐
it's like a < b and b < c
so by extension, a+b != p > l(p) becomes a+b != p and p > l(p)
ohhh that's so good ๐ญ , and to check it runs the code
the last part (p > l(p)) works no matter which comparison operator is used though
Oh and since it waits when you use input you don't need exit either ofc
genius stuff
I wonder if that would've worked on codingame ๐ค
Or if it would complain about timeouts
It probably would work
(...it errors when stdin is exhausted, soo)
(it should work for isolated test cases in theory)
Yeahh, I already abused that fact myself a little bit
codingame is fun, especially when you get a golf challenge
Is there a way to check if loop iterated at least once without early continue but without setting some variable on every iteration (or checking it)?
did_iterate = False
for i in range(100):
if i < 50:
continue
did_iterate = True
print(did_iterate)
you can check the iterable's truthiness in some cases
in the others, just set a variable
I understand, I thought maybe there is some hack to avoid doing it more than once
lua for comparison ```lua
i=io.read
a=i'*n'b=i'*n'o=print
for p in i,'*n'do t=a+b==p or-o(p)a=b b=p end
o'fib'
for i in [1, 2]:
if i == 2: break
else:
if "i" in locals():
print("ited")
I've managed to create something that prints to console if iterated at least once without breaking out of the loop even once (not only in first iteration, but also second, third, etc), but I don't think that's what you asked for exactly, right?
Also continue skips only one iteration, you meant break?
Also, I'm guessing that you are asking this because you want to optimise your code. If so, it's not worth it.
Good thinking ```py
foo = bar = object()
for foo in some_iterable:
...
did_iterate = foo is not bar
some_iterable = [foo, foo]
Alternatively if you are going to use i in a range:
i=0
for i in range(1):
...
print(i!=0)
``` seems to work for me as well
Ye, but it doesn't catch aborting with break (for whatever that's needed).
Just don't any lines between foo = ... and for foo in ....
this specific snippet always prints false
Yes, if you would increase it to range 100 for example it would post true though, this was just an example range, (though it has been pointed out it doesn't account for breaks already so oh well)
without evaluating, what is the output? ```py
*a, = a[:3] = "kl", *"mn" "x".join("abc"),
print(len(a))
I can't comprehend *a, = a[:3]
it's two separate unrelated assignments, the first one unpacks an iterable into a list (UNPACK opcode but it's all packed back into a single assignment target)
and since they go from left to right, it makes a
the next one a[:3] = modifies the first three elements of the newly created list a
remark: ```py
a = b.c = d[e] = f = g
equivalent to
tmp = g
a = tmp
b.c = tmp
d[e] = tmp
f = tmp``` (not entirely sure on this one so please correct me)
Was asking completely out of curiosity (it seems there could be a way to do something once when you actually need it just once, instead of repeating it again and again, though maybe it's not possible in Python), I know that those kind of micro optimizations are never worth it.
I really meant continue, but checking locals to see if iterator ever had an output is a cool idea, I like it
16?
or 17...
1(kl) + 9(a mnx b mnx c) = 10 items get assigned to a
then first 3 are replaced with 10 = +7 more items
10+7=17
that's how I understand it
btw I didn't know "a" "b".join was syntactically valid
yup
it's sort of a problem with implicit concatenation
it behaves the same as a higher precedence +
is it ||17||?
oh people already posted the answer
i just had to scroll down lol
yay i was right though
||```py
*a, = a[:3] = "kl", *"mn" "x".join("abc"),
*a, = a[:3] = ("kl", "a", "m", "n", "x", "b", "m", "n", "x", "c")
a = ["kl", "a", "m", "n", "x", "b", "m", "n", "x", "c"]; a[:3] = ["kl", "a", "m", "n", "x", "b", "m", "n", "x", "c"]
a = ["kl", "a", "m", "n", "x", "b", "m", "n", "x", "c", "n", "x", "b", "m", "n", "x", "c"]
print(len(a))
is it cheating that i evaluated it by hand
if taken literally, the "without evaluating" would say yes and then murder me 1000 times
by hand is fine
aaaaaaaaaaaaaaaaaaaaaaaaand my adhd came again:
import pyautogui as p
from bs4 import BeautifulSoup, Tag
def element_to_dict(element):
if not isinstance(element, Tag):
return str(element).strip()
children = [element_to_dict(child) for child in element.children if str(child).strip()]
return {"tag": element.name, "attributes": dict(element.attrs), "children": children}
response = requests.get(url)
asdf = BeautifulSoup(str(BeautifulSoup(response.text, "html.parser").find("div", id="products-found")), "html.parser").find_all("div", class_="product")
p.write(element_to_dict(asdf[0])["children"][0]["children"][1]["children"][1]["children"][0]["attributes"]["data-micro-price"].split(".")[0])
i usually write worse code than this
element_to_dict=f=lambda e:isinstance(e,Tag)and{'tag':e.name,'attributes':{**e.attrs},'children':[f(x)for y in e.children if(x:=f'{y}'.strip())]}or e
``` non-obligatory golf
thank you
can you direcrly replace the element to dict in p.write()?
i only use it once so idfc about how golfed it is
c=lambda t,i=0:[x for x in t.children if str(x).strip()][i]
p.write(c(c(c(c(asdf[0]),1),1)).attrs["data-micro-price"].split('.')[0])
``` ?
Alternative golf/better way of doing it: xpath with lxml (super untested, you probably need to do one more step of conversion on the result of the xpath) ```py
import lxml
p.write(lxml.etree.HTML(str(BeautifulSoup(response.text,"lxml"))).xpath("//div[@id='products-found']//div[@class='product']//@data-micro-price"))
Yeah xpath/selector-query seems like a way better approach for this example
The Frick is this
Well, imma take it
xpath is a way of querying for elements in xml-like datastructures. // means "any child of", and when it is first implicitly means any child of the root. div means a <div> element. [] lets you specify more specific criteria of an element. @<thing> gets the value of the property of <thing> on the element, and = is comparison,. Putting this all together, //div[@class='product'] means "a div that is a child of the root element with the class product". I then chain this one more time, except the second // means any elements that are children of the first element. The ending //@data-micro-price gets the value of the data-micro-price tag from any elements that are children of the matching divs of the matching divs.
Depending on how the website looks/what data you want, it might even be golfable to just .xpath("//@data-micro-price").
I am more comfortable with xpaths, which is why I used lxml, but Defiler also mentioned selector-query, which is built into bs4 and lets you use css selector queries, which act similar to xpath expressions.
xpaths are also cooler
Bro made an entire essay on this ๐ญ
The main reason I like them more than css selectors is that they are much easier to test, since almost all browsers support the $x("xpath") syntax for quickly running an xpath expression on the website
Yep. One small detail I wasn't perfectly clear on, but // means any child, recursively (where as / is a strict one level deep child)
what is estoeric python?
I think the answer will be along the lines of: "If you need to ask, then you are in the wrong place."
It's python taken to the extreme.
import ast
from linecache import*
import sys as s
from traceback import*
s.excepthook=lambda t,v,tb:getattr(__builtins__,(c:=ast.parse(getline((e:=extract_tb(tb)[-1]).filename,e.lineno)).body[0].value).args[0].value)(c.func.id)if issubclass(t,NameError)else s.__excepthook__(t,v,tb)
Hello_world("print") # print('Hello_world')
```guess this snippet will be enough to answer that
This hurts to try and read
it's pretty average, so
Yeah I'm kinda new to python so this is to be expected
dw, this channel is abnormal
so don't expect to encounter something like the above in functional projects
Someone get the SCP foundation lmao
_ โโ
[โ|||โโโโโโโ]โโโโโโโโโโโโโโโโ
__โโโ
โโโโโโโโโโ
โโโ
Iโโโโโโโโโโโโโโโโโโโโโ]
โฅโโฒโโฒโโฒโโฒโโฒโโฒโโฒโโค
Artillery lol, I should make a bash script that prints that out
It's basically: how does this one line of code even work
then you shouldn't come to this channel
its full of nightmares
average? its easy
Welp, I won't
Elitism in esoteric python :(
let them ast cake
~1+2
(P:=print,R:=range,G:="\033[32m",RE:="\033[31m",B:="\033[34m",W:="\033[0m",BW:="\033[1;37m",DG:="\033[90m",M:=["#########","#.......#","#.Z.....#","#.......#","#########"],w:=[[1,1],1,[[2,2]]],PC:=['^','>','v','<'],D:={0:[-1,0],1:[0,1],2:[1,0],3:[0,-1]},r:=lambda:[P(f"\n\n{G}=== ZOMBIE HUNTER ==={W}\n"),[P("".join(f"{B}{PC[w[1]]}{W}"if[y,x]==w[0]else f"{RE}Z{W}"if[y,x]in w[2]else f"{BW}#{W}"if M[y][x]=='#'else f"{DG}.{W}"for x in R(len(M[0]))))for y in R(len(M))]],[(r(),P("\nControls: WASD to move, F for melee attack, G for ranged attack"),c:=input("\nEnter command: ").lower(),w.__setitem__(0,[w[0][0]+D[w[1]][0],w[0][1]+D[w[1]][1]])if c=='w'and M[w[0][0]+D[w[1]][0]][w[0][1]+D[w[1]][1]]!='#'else w.__setitem__(0,[w[0][0]+D[(w[1]+2)%4][0],w[0][1]+D[(w[1]+2)%4][1]])if c=='s'and M[w[0][0]+D[(w[1]+2)%4][0]][w[0][1]+D[(w[1]+2)%4][1]]!='#'else w.__setitem__(1,(w[1]-1)%4)if c=='a'else w.__setitem__(1,(w[1]+1)%4)if c=='d'else(h:=[w[0][0]+D[w[1]][0],w[0][1]+D[w[1]][1]]in w[2],P("\nMelee "+f"{G}hit!{W}"if h else f"{RE}miss...{W}"),w[2].remove([w[0][0]+D[w[1]][0],w[0][1]+D[w[1]][1]])if h else None,(P(f"\n{G}You win! Killed the zombie with melee attack!{W}"),exit())if not w[2]else None)if c=='f'else(h:=next((t for i in R(1,6)for t in[[w[0][0]+D[w[1]][0]*i,w[0][1]+D[w[1]][1]*i]]if t in w[2]),None),P("\nRanged "+f"{G}hit!{W}"if h else f"{RE}miss...{W}"),w[2].remove(h)if h else None,(P(f"\n{G}You win! Killed the zombie with ranged attack!{W}"),exit())if not w[2]else None)if c=='g'else None)for _ in iter(int,1)])
Lambda functions are good for beginners to learn imo
Love this script so much. The fact it runs too is amazing
Wtf
This is what I imagine Cython being
you don't need to come here to learn about lambda
and vice versa
I think it's a good challenge if you are learning
nice-ified https://paste.pythondiscord.com/XBQA
ugh i had to do this on mobile for 2 hours... whatever.
LMAO hell yea
link to code in this channel #esoteric-python message
it's changed a bit from that form but same thing anyways.
I recently got hooked by a Truttle1 video on the slashes (///) esolang, so I tried to golf an interpreter (279 chars with \n line ends): ```py
def slashes(s):
m=r="";t=0
while(s:=list(s)):
if(c:=s.pop(0))=="/":
if(t:=t+1)==3:
while(s:="".join(s))and m in s:s=s.replace(m,r,1)
r=m="";t=0
continue
if c=="\":
if s:(c:=s.pop(0))
else:break
(m:=m+c)if t==1 else(r:=r+c)if t==2 else print(c,end="")
shortened a bit ```py
def slashes(s):
m=r="";t=0;g=1
while s:
c,*s=s
if"/"g==c:
t+=1
if t>2:
while m in(s:="".join(s))>"":s=s.replace(m,r,1)
r=m="";t=0
elif g:="\"g!=c:m+=t%2c;r+=t//2c;t<1==print(end=c)
shortened a bit more ```py
def slashes(s):
m=r="";t=0;g=1
while s:
c,*s=s;t+="/"g==c
if t>2:
while m in(s:="".join(s))>"":s=s.replace(m,r,1)
r=m="";t=0
elif g:="\"g!=c:m+=t%2c;r+=t//2c;t<1==print(end=c)
This version looks to have broke somewhere ```pycon
def slashes(s):
... m=r="";t=0;g=1
... while s:
... c,*s=s;t+="/"g==c
... if t>2:
... while m in(s:="".join(s))>"":s=s.replace(m,r,1)
... r=m="";t=0
... elif g:="\"g!=c:m+=t%2c;r+=t//2c;t<1==print(end=c)
... slashes("/a/b/a")
... print()
...
a
(Should output `b`)
fixed ```py
def slashes(s):
m=r="";t=0;g=1
while s:
c,s=s;t+="/"==gc
if t>2:
while m in(s:="".join(s))>"":s=s.replace(m,r,1)
r=m="";t=0
elif g:="\"!=gc!="/":m+=t%2c;r+=t//2*c;t<1==print(end=c)
Your memorization of operator precedence is crazy, I think I see how you turned the ternaries into </== but wow
i spent most of my 4 years of python experience in esopy/golfing so..
not fixed actually there might be something wrong
I think the golf/my original implementation/the implementation I referenced on the wiki has a bug, since if I'm reading the rules right I think /\a/b/a should also output b, not a
no wait they do work, I'm just stupid/tired and forgot the r-string
fixed 2? ```py
def slashes(s):
m=r="";t=0;g=1
while s:
c,s=s;z="/"==gc;t+=z;g="\"!=gc
if t>2:
while m in(s:="".join(s))>"":s=s.replace(m,r,1)
r=m="";t=0
elif z<g:m+=t%2c;r+=t//2*c;t<1==print(end=c)
ya i think it's fixed now
I think I get it, the \ is handled by the z<g being false, right?
yup
