#esoteric-python
1 messages · Page 46 of 1
!e
class Thing:
def __init__(self, msg):
self.msg = msg
def __getattr__(self, attr):
def fakemethod(self=self):
print(self.msg)
return fakemethod
obj = Thing("foo bar bat")
obj.fakemethod()
:white_check_mark: Your 3.12 eval job has completed with return code 0.
foo bar bat
!e But this is cheating. The proper way would be:
from types import MethodType
class Thing:
def __init__(self, msg):
self.msg = msg
def __getattr__(self, attr):
def method(self):
print(self.msg)
return MethodType(method, self)
obj = Thing("foo")
print(obj.fake)
obj.fake()
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | <bound method Thing.__getattr__.<locals>.method of <__main__.Thing object at 0x7f991daebda0>>
002 | foo
Weird question...
I want to call a class method that I have in several classes, inside a function that can take an object of any of these classes. How can I determine which class to call the method from?
Simplified example:
class Person:
def get_from_file(self, name, age, home):
...
class Student(Person):
def get_from_file(self, name, age, home, year, house):
...
class Teacher(Person):
def get_from_file(self, name, age, home, subject):
...
class House:
def get_from_file(self, name, founder, animal, values):
...
def genericLoader(file_name, delimiter, **kwargs):
...
my_object = <CORRECT CLASS NAME>.get_from_file(kwargs)
...`
Is there a way to determine it, or do I just if elif elif else?
classmethods can be called from instances
if thats what you mean
No, I mean something that I can replace <CORRECT CLASS NAME> with
you said your function had an object of the correct type already
so just obj.class_method()
Ahh ok, I missunderstood what you meant first. That works, thanks
not esoteric enough
Yeah, I just didn't consider that I could do it from the object name, I thought I needed to get the class name from it somehow
I'd imagine it's pretty terrible at guessing what any golfed code over 500b does unless that code provides easy context for it (like the strings "rock", "paper", and "scissors" being in the code)
and beyond that easy to trick by including fake contextual clues like those mentioned above
I wonder if anyone fine-tuned a model to specifically output golfed code
probably not, I'd imagine if you could get some pretty strong outputs from it if you treated it like an RAG with COT
except instead of actually needing retrieval based augmentation you feed the same "this is how you turn a for loop into a comprehension or get the same result using map blah blah" into the input every time
no need for fine tuning really
https://chatgpt.com/share/41097106-7115-420b-bc72-bf0ed215100f surprisingly, it got my iopcc 2023 submission partly correct
it couldnt tell me exactly what pattern was being drawn but it got the gist of it
surprising
Not so surprising; the code imports trig functions, prints with ANSI escapes, and contains a short sleep inside a forever loop
I am going to build youtube channel claimer. Old youtube channels, I am gonna claim the ownership. It is kind of automation project by python programming. If someone is expert in automation, let's connect!
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
call cls.mro()
it returns an ordered list in which the order of the resolution of methods is specified
iirc phyton uses the c3 algo??
idk
but the rule of thumb is:
- 1: The method in the class itself
- 2: The method in the parent class in order of inheritance
Would you say, it's usage is mostly... esoteric? 
I did this long time ago, printing false for true and such stuff, I don't really remember the code
Have I done anything wrong here that I get no output?```py
from ctypes import py_object
py_object.from_address(id(True) + 8).value = False
print(f"True: {True}")
here you're setting the type of True to be False
type of True is supposed to be bool, not an instance of bool, so this would break
id(x) + 8 would be x's type on 64-bit systems
so id(True) + 8 would mean changing the True object's type instead of its value
I have a code from some years ago, which is unreadable to me but still works
It does the same thing but I can't figure it out
Here's the code(requires internet to run)```py
_ = import('ctypes').py_object.from_address
__ = import(''.join([chr(int(i)) for i in '114 101 113 117 101 115 116 115'.split()])).get
class TheStart(metaclass=type(
'',
(type,),
{
'prepare': lambda *a: type(
'',
(dict,),
{
'missing': lambda *a: getattr(builtins, a[1], 1),
'contains': lambda *a: bool('')
}
)()
}
)): (globals().setitem('hack', lambda x, y: setattr((id(x)+8), "value", type('', (), {'str': lambda _: y})))); globals().setitem('d', lambda _: ''.join([chr(int(i)) for i in _.split()]))
hack(True, __(d('104 116 116 112 115 58 47 47 119 119 119 46 101 105 103 104 116 98 97 108 108 97 112 105 46 99 111 109 47 97 112 105')).text[12:-3])
class Love(TheStart):
print(Destiny is us)#?
"requires internet to run"?
why do you need requests...
wtf is https://www.eightballapi.com/api
I'll check that out, thanks
the classmethod is available on the object itself, there's no need for mro :p
it doesnt
!e ```py
import ctypes
setattr(ctypes.py_object.from_address(id(True)+8), "value", type('', (), {'str': lambda _: "hello, world"}))
print(True)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
hello, world
instead of setting the object's type to False, you're setting the object's type to a different type, with an overloaded string representation
says in the name
for no reason ever I'm going to make it a single line
I never checked this channel, what is the point of it?
The description doesn't give that much info
Lambdas aren't esoteric or something
scroll up a bit you'll start seeing weird codes, that's esoteric
Well code that is hard to read or just "weird" isn't necessarily esoteric.
I know about esoteric languages a lot, and python, well, isn't one, so I can't understand the meaning of this channel, unless its just for "weird code", but then again: why use an already reserved word for something unrelated.
It shouldn't have been named this way
Yo didn't expect you here, deleted
Oh hi
Helping people in #1035199133436354600 since yesterday, feels good to help others considering it isn't hard at all
lul
!e
from itertools import permutations
def calc(n):
def f(x):
return x**2 - 4*x + 4
return f(n) // 2
def obscure(n):
return calc(n) - sum(map(lambda x: x**2, range(n)))
def mystify(data):
return [hex(x) for x in data]
class Enigma:
def __init__(self, seed):
self.seed = seed
self.data = mystify([self.seed] * 5)
def process(self):
perm = permutations(range(5))
result = [0]
for p in perm:
temp = self.seed
for idx in p:
temp = obscure(temp) + idx
result.append(temp)
return result
def __str__(self):
return str(self.data)
e = Enigma(42)
print(e.process())
:warning: Your 3.12 eval job timed out or ran out of memory.
[No output]
!e
from functools import reduce
import itertools as it
def f(a, b):
return reduce(lambda x, y: x ^ y, map(ord, b), a)
def g(x):
return ''.join(chr(c) for c in it.accumulate(x, lambda a, b: a + b))
def h(s):
return [ord(c) for c in s]
def i():
return list(it.chain.from_iterable(map(lambda c: [c] * 3, [i for i in range(10)])))
a = f(0, 'This is an example!')
b = h(''.join(chr(i) for i in i()))
c = g([c - a for c in b])
print(c)
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 18, in <module>
003 | c = g([c - a for c in b])
004 | ^^^^^^^^^^^^^^^^^^^^^
005 | File "/home/main.py", line 8, in g
006 | return ''.join(chr(c) for c in it.accumulate(x, lambda a, b: a + b))
007 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
008 | File "/home/main.py", line 8, in <genexpr>
009 | return ''.join(chr(c) for c in it.accumulate(x, lambda a, b: a + b))
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/DNOHOPXLBYT5XYUJPAU23XW25Y
!e
def Ω(𝛿):
return 𝛿 * (𝛿 - 1) // 2
def Ψ(Φ):
return [(λ := λ + 1) for λ in range(Φ)]
def Δ(Ξ):
return {ξ: ξ * ξ for ξ in Ξ}
def Σ():
∆ = 42
Γ = Ω(∆)
δ = Ψ(Γ)
φ = Δ(δ)
return φ[Γ % len φ]
print(Σ())
:x: Your 3.12 eval job has completed with return code 1.
001 | File "/home/main.py", line 11
002 | ∆ = 42
003 | ^
004 | SyntaxError: invalid character '∆' (U+2206)
not esoteric
also you forgot parenthesis for len
- go join the esolangs server then!
- read the channel description! and there is esoteric python here, you just have to find it :P
chilaxan and cereal both have made cool things
death.py but i think they changed names now
and they haven't been active recently
and l3viathan
lots of people make cool things here
yeah
oh hi olivia!
hi kotnen!
she makes cool stuff too!
🐦
anyway, as to your point about this not being esoteric, my dictionary gives the following definitions for ``esoteric'':
Intended for or likely to be understood by only a small number of people with a specialized knowledge or interest, or an enlightened inner circle.
Having to do with concepts that are highly theoretical and without obvious practical application; often with mystical or religious connotations.
i think the stuff here generally meets both of those definitions
and more generally, who's to say what's esoteric and what isn't?
l3viathan said this once and i think its a really nice way of putting it
ok ill step off my soapbox now!
aside from the dictionary
"esoteric" in the context of esolangs is not a magic word reserved to esolangs
the same meaning can be derived from esoteric application of practical languages
silly little challenge: write a program that will determine if a given number is odd, like the following:
print(int(input()) % 2 == 1)
the catch is your code can only use the characters a-z and parentheses
Hmm.. no comma, no spaces?
yep
Do you have a solution? Because I don't see how you could do that without at least .
i do
Ok, then let me think :)
no eval or exec either
||print(bool(int(next(iter(reversed(bin(int(input()))))))))||
that was quick!
shorter than my solution too, I did print(next(reversed(bin(int(input()))))in(str(int(not(())))))
Oh, right, I don't need the iter(); print(bool(int(next(reversed(bin(int(input()))))))) then
not(()) can be simplified to not()
>>> input = lambda: 42
>>> ~() // input // str // reversed // next // ord // bin // reversed // next // int
0
>>> input = lambda: 69
>>> ~() // input // str // reversed // next // ord // bin // reversed // next // int
1
>>> input = lambda: 42
>>> int(next(reversed(bin(ord(next(reversed(str(input()))))))))
0
>>> input = lambda: 69
>>> int(next(reversed(bin(ord(next(reversed(str(input()))))))))
1
ok, that is a lot longer than your solution
what the hell did i just wrote
why does input() returns an int, and why do i convert it to a string...
for some reason i have a function called rocket_stages available in my repl... ```py
rocket_stages?
Help on function rocket_stages in module sc:
rocket_stages(ssto_payload_ratio: 'float', payload_mass: 'float' = 1, n_stages: 'int' = 2, k: 'int' = 3) -> 'list[float]'
inspect.getsource(rocket_stages) // print
def rocket_stages(
ssto_payload_ratio: float,
payload_mass: float = 1,
n_stages: int = 2,
k: int = 3,
) -> list[float]:
# >>> rocket_stages(0.02, n_stages=5, payload_mass=1000, k=0)
# [27_134, 12_408, 5_674, 2_595, 1_186, 1_000]
# >>> [(x[:i+1]//sum, x[i:] // sum * 1.5 // 400,)for i in range(len(x))]
# [(num of engines, mass including this stage), ...]
q = ssto_payload_ratio
res = [q ** ((i - 1) / n_stages) - q ** (i / n_stages) for i in range(1, n_stages + 1)]
total = payload_mass / (1 - sum(res))
res = [total * x for x in res]
res = [round(x, k) if k else int(x) for x in res]
res += [payload_mass]
return res
huh
That sounds like advent of code leftovers
new challenge in a similar style: write some code that determines if an integer >=2 is composite, using only letters a-z and parentheses.
What composite mean(?
non-prime natural number
“composed” of multiplications by prime numbers
Thx
spaces allowed?
no
lack of comma is killing me lol
no divmod nor pow
im assuming no exec/eval, right
yea the commas are hard
yep
am I supposed to create a function? or am I allowed to hardcode the number?
write a full program with print to output and input for input
must we be 100% accurate?
yes
I can only get it with spaces oof
I got it with no spaces and a single ":" might be getting somewhere
no symbols is a bit hard T-T
square brackets allowed?
nope
making sure exec and eval are banned right?
as a hint, this is the exact test my solution uses for determining if a number is composite: ||n is composite if and only if there are integers a, b greater than one such that a*b=n (basically the most naive algorithm)||
solution ||print(any((sum((c)for(z)in(range(b)))in((a)for(z)in(range(not()))))for(a)in((int(input()))for(z)in(range(not())))for(b)in(range(a))for(c)in(range(a))))||
And there limit on how many time I can request I put?
you can do it with just 1
very impressive, you did it shorter than I did :) but the same basic idea
Oh, there are hint
Let me try this
i think you can make it slightly simpler by ||replacing the first in((a)for(z)in(...)) with just is(a) edit: actually maybe not since is might not work with integers not in the integer cache||
Thinking how to get -1
if you want to decrease a positive integer by one I think the simplest way is max(range(n))
I was on track of thinking a*b-n=0 but you need -n part
a*b = n is simpler to implement
But you cannot have ==?
you can use in
Hmm right
||```py
print(next(int(not(not()))in((x*y-n)for(x)in(range(n))if(x)and(next(reversed(range(x))))for(y)in(range(n))if(y)and(next(reversed(range(y)))))for(n)in(int(input()),)))
illegal chars used: *-, (each only once)
print(next((n)in((x*y)for(x)in(range(n))if(x)and(next(reversed(range(x))))for(y)in(range(n))if(y)and(next(reversed(range(y)))))for(n)in(int(input()),)))
illegal chars used: *,
print(next((n)in((len(list(()for(i)in(range(x))for(j)in(range(y)))))for(x)in(range(n))if(x)and(next(reversed(range(x))))for(y)in(range(n))if(y)and(next(reversed(range(y)))))for(n)in(int(input()),)))
illegal chars used: ,
||you're on the right track, there are ways to get rid of each of those illegal chracters||
||
y = 5
input = lambda*_: y
print(not(any(list(sum((a)for(c)in(range(b)))in(input(),input())for(a)in(range(input()))for(b)in(range(input()))))))
Require multiple use of input
||
Oh oops
The comma
And I thought better way now
Wait no it doesn't
Got it
||
y = 11
input = lambda*_: y
print(not(any(list(sum((a)for(c)in(range(b)))in(input()for(z)in(range(not())))for(a)in(range(input()))for(b)in(range(input()))))))
||
Oops, forgot spoiler, did now
now can you figure out how to do it without repeating input? 😉
does this count? ||```py
print(
int(input())
in (
sum((x)for(i)in(range(y)))
for (x) in (range(500))
if (x) and (next(reversed(range(x))))
for (y) in (range(500))
if (y) and (next(reversed(range(y))))
)
)
interesting idea
side note, i wonder if it is possible to make an infinite iterator
then we would have an infinite range with something like (next(iter(a))for(a)in(enumerate(infiterator)))
>>> max('ab', 'b')
'b'
>>> max('ab')
'b'
that's specifically why I chose it
is there a way to pass two arguments to a function?
||iter(list,callable) is an infinite iterator||
seems very unlikely
unrelated to this specific challenge, but you can absolutely exec arbitrary code under this ruleset
by using exec?
Is it turing complete? 😄
x - 1 == next(reversed(range(x))) # for x >= 1
x - 1 == max(range(x)) # for x >= 1
x * y == sum((x)for(i)in(range(y))) # for y >= 0
x > 0 == bool(range(x))
[x,y] == list((y)if(bool(range(i)))else(x)for(i)in(range(len(str(())))))
x + y == sum([x,y])
2 == len(str(()))
1 == int(not())
0 == int()
18 == hash(id) // abs // hex // len
65 == hash(id) // abs // bin // len
``` that is a list of simple operations i figured out how to do
idk how to do `-x`, it can be done as `(-1) * x`, but it requires `-1`
after that `x - y` can be done as `x + (-y)`
||exec(bytes(iterable)), where iterable is constructed like ((c1)if(i==0)else(c2)if(i==1)else(...)for(i)in(range(N)), x==y is constructed like (x)in((y)for(z)in(range(not()))) and arbitrary integers c1, c2, ... & Nare constructed any way you like (for example starting with a number like len(str(object)) and either decrementing it using max(range(n)) or increasing it a lot using sum(range(n)) )||
idk why i figured out how to make [x,y] but not [x] 🤦♂️
for negatives you could do int(b"-10"), where you constuct the bytestring as olivia describes using a bunch of ifs
so it is turing complete if we use exec/eval
without using those, it is much harder. For example I think it is impossible to make a program that just prints TrueFalse
chr(n) gives you arbitrary character
is it possible to perform string concatenation somehow?
i have tried, but it also seems unlikely
if we could get the values of a dictionary we could iterate over vars(str) to find str.join but there seems to be no way to do that either
(type)(int)(list)(str)(dict)
``` this is valid code 😄
>>> [next(reversed(kv)) for kv in vars(str).items() if ord(next(iter(next(iter(kv))))) == ord('j')]
[str.join]
``` uses `.items`
next(iter(next(iter(kv))))
cursed
I don't think you could call it if you did
Love the activity here today, very esoteric stuff 😄
Well, not esoteric
But you know
Weird 😄
I guess then we would need bytes.decode, not str.join
because we know how to make arbitrary bytestrings, but can't turn them back into strings
why not? (str.join)(['a', 'b'])
doesn't work for me
nah
oh, right
i forgot it needs second arg :)
list((3)for(o)in(range(not())))
This can probably be shorter
list((3)for(o)in(str(int()))) is the shortest I know of
Ah, right
Hi
that's useful
||```py
print(any(sum((a)for(z)in(range(b)))in((I)for(i)in(chr(not())))for(I)in(int(input())for(i)in(chr(not())))for(a)in(range(I))for(b)in(range(I))))
shortest code competition..?
this is a prime determiner
Oh, so I don't have to invert it? Whatever
143 -> 123 ||```py
print(any((I)in(sum((a)for(z)in(bytes(b)))for(b)in(range(I)))for(I)in(int(input())for(i)in(chr(not())))for(a)in(range(I))))
What da hell is that
we were trying to write a prime checker in python but all of our keyboards broke simultaneously, allowing us to only type lowercase letters and parentheses into the python interpreter
composite checker*
is it possible to check if number is perfect?
In number theory, a perfect number is a positive integer that is equal to the sum of its positive proper divisors, that is, divisors excluding the number itself. For instance, 6 has proper divisors 1, 2 and 3, and 1 + 2 + 3 = 6, so 6 is a perfect number. The next perfect number is 28, since 1 + 2 + 4 + 7 + 14 = 28.
The sum of proper divisors of ...
I think it is pretty straightforward
same difference isnt it
Probably possible.
(...)and(not((n)in(range(2))))
for whatever condition checking you've got going on
I wanted to operator chain like .... in [N] not in range(2) but you can't do not in without spaces :(
omg you can do for i in something by using parans
how to + 1?
I got lost in the sauce
got 178, works fine for all i think
sum([x,1])
too long
then I don't know
eh anyway
||```py
print(not(any(sum((a)for(a)in(range(I))if(I)in(sum((a)for(z)in(bytes(b)))for(b)in(range(I)))or(a)and(not(max(range(a)))))in(range(I))for(I)in(int(input())for(i)in(chr(not()))))))
am I right that you can replace bytes with range ?
!e
print(not(any(sum((a)for(a)in(range(I))if(I)in(sum((a)for(z)in(bytes(b)))for(b)in(range(I)))or(a)and(not(max(range(a)))))in(range(I))for(I)in(int(input())for(i)in(chr(not()))))))
:x: Your 3.12 eval job has completed with return code 1.
:warning: Note: input is not supported by the bot :warning:
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | print(not(any(sum((a)for(a)in(range(I))if(I)in(sum((a)for(z)in(bytes(b)))for(b)in(range(I)))or(a)and(not(max(range(a)))))in(range(I))for(I)in(int(input())for(i)in(chr(not()))))))
004 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
005 | File "/home/main.py", line 1, in <genexpr>
006 | print(not(any(sum((a)for(a)in(range(I))if(I)in(sum((a)for(z)in(bytes(b)))for(b)in(range(I)))or(a)and(not(max(range(a)))))in(range(I))for(I)in(int(input())for(i)in(chr(not()))))))
007 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
008 | File "/home/main.py", line 1, in <genexpr>
009 | print(not(any(sum((a)for(a)in(range(I))if(I)i
... (truncated - too long, too many lines)
Full output: https://paste.pythondiscord.com/OCPV4ZS253UACIJGABBWKNEHVI
i got -1
end of file
yup :p
negating the any is very smart
hm
I tried checking if sum(...) == n - 1
it would be fun to write a converter between some python expressions and this maybe
oh that's smart-
not arbitrary python expressions, but a large subset of the builtin functions could be done mechanically i think
new project idea!
it might be expensive in terms of both code size and runtime performance
oh it doesn't work T^T
print(any(
(N-1) in # N is equal to ...
[sum(a for a in range(N) if N in (a*b for b in range(N)))] # the sum of its divisors
and not(N in range(2))
for N in [int(input())]
))
``` works for me
which is the deobfuscated version of my solution
yep
but it would be fun!
not completely correct, for example it says 12 is perfect
seems like you don't take into account abundant numbers
my 201:
||py print(any(max(range(N))in(sum((a)for(a)in(range(N))if(N)in(sum((a)for(e)in(range(b)))for(b)in(range(N))))for(d)in(dir()))and(not((N)in(range(len(str(()))))))for(N)in(int(input())for(f)in(str(int())))))||
183 fixed ||```py
print(any(sum((a)for(a)in(range(I))if(I)in(sum((a)for(z)in(bytes(b)))for(b)in(range(I)))or(a)and(not(max(range(a)))))in((I)for(z)in(dir()))for(I)in(int(input())for(i)in(chr(not())))))
174 by ||golfing the 1 check
print(any(sum((a)for(a)in(range(I))if(I)in(sum((a)for(z)in(bytes(b)))for(b)in(range(I)))or(a)is(int(not())))in((I)for(z)in(dir()))for(I)in(int(input())for(i)in(chr(not())))))
```||
using only characters a-z and parens to code
using parens instead of spaces is kinda cancer to read lol
chr(not()) evaluates to '\x01' yeah?
isn't that shorter
oh
yea that's the... entire restriction
what's the goal?
swag
mind to elaborate?
there were two prompts, one to create a program that determines whether a number is divisible by 2 and another for whether it's non-prime
(also the perfect number prompt)
are capitals allowed?
But why?
no
I don't think there are any valid use case for this: What you can achieve with or with capital is like the same if I'm not wrong
you can use the True and False types
not(()) and not(not(()))
not() and bool()
Fair, didn't know not() work with no args
something funny i just realised
print(list(str(a)for(a)in(str(input()))))
it's not a function, it's a prefix operator so it's actually already getting an argument
Oh, I thought they exist as both form
(Which would be weird but I never have a thought about it previously
im testing out the code and it kinda breaks at high values 😔
3455 returns True
t=n=10**999;exec("n=n//2+t*t//n;"*99);print(f"1.{n-t}")
sqrt(2) to 1k digits
55b so far
There are, using dir you can generate any string that is a valid identifier, but you can’t use capitals which is annoying
result = (lambda _, __, ___, ____, _____, ______, _______, ________:
getattr(
__import__(True.__class__.__name__[_] + [].__class__.__name__[__]),
().__class__.__eq__.__class__.__name__[:__] +
().__iter__().__class__.__name__[_____:________]
)(
(lambda _, __, ___: _(_, __, ___))(
lambda _, __, ___:
bytes([___ % __]) + _(_, __, ___ // __) if ___ else
(lambda: _).func_code.co_lnotab,
_ << ________,
(((_____ << ____) + _) << ((___ << _____) - ___)) + (((((___ << __)
- _) << ___) + _) << ((_____ << ____) + (_ << _))) + (((_______ <<
__) - _) << (((((_ << ___) + _)) << ___) + (_ << _))) + (((_______
<< ___) + _) << ((_ << ______) + _)) + (((_______ << ____) - _) <<
((_______ << ___))) + (((_ << ____) - _) << ((((___ << __) + _) <<
__) - _)) - (_______ << ((((___ << __) - _) << __) + _)) + (_______
<< (((((_ << ___) + _)) << __))) - ((((((_ << ___) + _)) << __) +
_) << ((((___ << __) + _) << _))) + (((_______ << __) - _) <<
(((((_ << ___) + _)) << _))) + (((___ << ___) + _) << ((_____ <<
_))) + (_____ << ______) + (_ << ___)
)
)
)(
*(
[len] +
[ord] +
[sum] +
[int] +
list(range(7))
)
)
decode this without running it, i dare ypu
!e
result = (lambda _, __, ___, ____, _____, ______, _______, ________:
getattr(
__import__(True.__class__.__name__[_] + [].__class__.__name__[__]),
().__class__.__eq__.__class__.__name__[:__] +
().__iter__().__class__.__name__[_____:________]
)(
(lambda _, __, ___: _(_, __, ___))(
lambda _, __, ___:
bytes([___ % __]) + _(_, __, ___ // __) if ___ else
(lambda: _).func_code.co_lnotab,
_ << ________,
(((_____ << ____) + _) << ((___ << _____) - ___)) + (((((___ << __)
- _) << ___) + _) << ((_____ << ____) + (_ << _))) + (((_______ <<
__) - _) << (((((_ << ___) + _)) << ___) + (_ << _))) + (((_______
<< ___) + _) << ((_ << ______) + _)) + (((_______ << ____) - _) <<
((_______ << ___))) + (((_ << ____) - _) << ((((___ << __) + _) <<
__) - _)) - (_______ << ((((___ << __) - _) << __) + _)) + (_______
<< (((((_ << ___) + _)) << __))) - ((((((_ << ___) + _)) << __) +
_) << ((((___ << __) + _) << _))) + (((_______ << __) - _) <<
(((((_ << ___) + _)) << _))) + (((___ << ___) + _) << ((_____ <<
_))) + (_____ << ______) + (_ << ___)
)
)
)(
*(
[len] +
[ord] +
[sum] +
[int] +
list(range(7))
)
)
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | result = (lambda _, __, ___, ____, _____, ______, _______, ________:
004 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
005 | TypeError: <lambda>() takes 8 positional arguments but 11 were given
yeah its not like it can be ran anyways
!hell
it also does (lambda: _).func_code.co_lnotab which just doesnt make sense? maybe this branch was never supposed to be taken i guess
and it does True.__class__.__name__[_] which even if it was called with the right amount of args would try to index a string with.. len? yeah im not sure how this was even supposed to work
Bet
After deobguscationg lua scripts i trained my brain
Make a weird function that checks if all ints in a list are ones
def allOnes(_n:list[int])->bool:return(all(u==1 for u in _n))
Brainrot but
How i think
It have intto string convertion
And it uses that shit long bit operations
To get string
And then idk
allOnes=lambda n:set(n)=={1}
def allOnes(n: list[int]) -> False:
if not isinstance(n, list):
return False
a = 0
for item in n:
if item == 1:
a += 1
return a == len(n)
Real sigmas do this^
!e
import re
allOnes=lambda n:bool(re.fullmatch(' '.join('1'*len(n)),' '.join(map(repr,n))))
assert allOnes([])
assert allOnes([1])
assert allOnes([1, 1])
assert not allOnes([1, 2, 1])
:warning: Your 3.12 eval job has completed with return code 0.
[No output]
!e
allOnes=(lambda f:lambda*p:(q:=[f(*p)],sum(iter(lambda:(q.__setitem__(0,f(*q[0][1])),0)[1]if(q[0][0])else(1),1)))[0][0][1])(lambda n,i=0:((0,False)if(n[i]!=1)else(1,(n,i+1)))if(i<len(n))else(0,True))
assert allOnes([])
assert allOnes([1])
assert allOnes([1, 1])
assert not allOnes([1, 2, 1])
:warning: Your 3.12 eval job has completed with return code 0.
[No output]
allOnes={1}.issuperset
so [] doesnt pass "all elements are ones"? sad empty list
Right. <= then.
yes, it should
it's a composite checker, not a prime checker
(well technically it's an inverted prime checker)
ohh, i thought it was a (divisible by two) checker lmao
which is a composite checker!
definitionally
LC?
!e ```py
from typing import Callable, Iterable
def equal_to[T](v: T) -> Callable[[T], bool]:
def _is_equal(x: T) -> bool:
return x == v
return _is_equal
def all_is[T](f: Callable[[T], bool]) -> Callable[[Iterable[T]], bool]:
def _all_check_is(it: Iterable[T]) -> bool:
return all(map(f, it))
return _all_check_is
allOnes = all_is(equal_to(1))
assert allOnes([])
assert allOnes([1])
assert allOnes([1, 1])
assert not allOnes([1, 2, 1])
print("passed")
:white_check_mark: Your 3.12 eval job has completed with return code 0.
passed
@overload
def allOnes(xs: list[Literal[1]]) -> Literal[True]:
...
@overload
def allOnes(xs: list[int]) -> bool:
...
now make it in python4
allOnes = all(map(($==1), $)) or something
mhh.
$ and $n are already reserved syntaxes for "templates"
where y |> (x |> f($, $1)) is basically equivalent to f(x, y)
and $ == $0
but this is the same thing except without the pipes, its just not applied yet
yea but it's ambiguous to figure out which refers to which if both are used
..how about something like a prefix &
all ∘ map (==1)
map(1 .__eq__, xs) |> all?
oh yea no argument names-
function composition is still unimplemented too, hmm
plus that weird bug with templates that i haven't fixed yet T^T
god i have so much i wanna do..
what
leetcode
You can can do this?
Need to learn more on how typestub give better understand to type checker on what your code do
i think it's more of a ```py
from typing import Literal, Protocol, overload
class HasEqT:
@overload
def eq(self, __x: Literal[1]) -> bool:
...
@overload
def eq(self, __x: T) -> bool:
...
@overload
def allOnes(xs: list[Literal[1]]) -> Literal[True]:
...
@overload
def allOnes(xs: list[HasEq[int]]) -> bool:
...
but i don't know how typing works soo 🤷♂️
this example is impractical, but yeah, overloads and literal types exist (only for, well, literals, not for custom classes, and not for.. floats, for some reason)
Everytime I've used overloads I've ended up refactoring the code later
every time i've used typing in python i've ended up switching to a different language
-# /hj
Well, at least I got a practical use case (because my friend does something stupid that accept a item and list of item, and conditionally return an item and list of item (not literal part but overload)
i.e.
A -> B
list[A] -> list[B]
So now whenever I feel like I need them that's just a signal to take a step back
defining a constraint on eq rhs type is bad, you can compare different (even incompatible) types, its supposed to be __eq__(self, :object) -> bool: in general (otherwise your thing is no longer an object)
i dont think there's a good way to express the thing here
Those should probably be two functions
yea that's what i was aiming for
but i don't know how typing works soo
if you want eq(1) -> bool and eq(object) -> bool its just eq(object) -> bool (since 1 is an object) which is just object's __eq__
so like just list[object]
iirc, __eq__ must accept object, so HasEq is always satisfied
class HasEq[T](Protocol):
@overload
def __eq__(self, __x: Literal[1]) -> bool:
...
@overload
def __eq__(self, __x: object) -> bool | NotImplementedType:
...
``` ?
notimplemented is not needed in types (you can always use a NotImplemented), so you're once again back to just object.__eq__
yea but how would i annotate __eq__ for Literal[1] with a strictly bool output
eq with anything is already supposed to be a bool
eh, numpy
numpy is weird indeed
!d object.eq
object.__eq__(self, other)``````py
object.__ne__(self, other)``````py
object.__gt__(self, other)```
These are the so\-called “rich comparison” methods. The correspondence between operator symbols and method names is as follows: `x<y` calls `x.__lt__(y)`, `x<=y` calls `x.__le__(y)`, `x==y` calls `x.__eq__(y)`, `x!=y` calls `x.__ne__(y)`, `x>y` calls `x.__gt__(y)`, and `x>=y` calls `x.__ge__(y)`.
A rich comparison method may return the singleton [`NotImplemented`](https://docs.python.org/3/library/constants.html#NotImplemented) if it does not implement the operation for a given pair of arguments. By convention, `False` and `True` are returned for a successful comparison. However, these methods can return any value, so if the comparison operator is used in a Boolean context (e.g., in the condition of an `if` statement), Python will call [`bool()`](https://docs.python.org/3/library/functions.html#bool) on the value to determine if the result is true or false.
after spending some time going down the typing rabbit hole i have finally convinced myself to stop
Yes exactly
# coding: hoopy
from hoopy.prelude import (<$>), ($)
allOnes = \x -> all $ ((==) 1) <$> x
ooh codecs cool
its so sad that they are.. not supported by any static analysis tools, so using them in real code is practically impossible
!e
def all_ones(ones) -> 1 or not 1:
try:
return not 1 / ~-ones[not 1]
except ZeroDivisionError:
return all_ones(ones[1:])
except IndexError:
return not not 1
except:
return not 1
print(all_ones([]))
print(all_ones([1]))
print(all_ones([1, 1, 1]))
print(all_ones([1, 1 + 1, 1]))
print(all_ones([1, 1, "1"]))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | True
002 | True
003 | True
004 | False
005 | False
every time ive used typing in python it's been to abuse python
can we create non-alphanumeric python3 code?
Depends what you mean by that. Code that doesn't match [a-zA-Z0-9] anywhere: yes. Code that contains only whitespace and punctuation: not really, nothing that does anything interesting. (Not counting the usual loopholes like codecs etc.)
what does codec mean? why not counting them?
You can register a custom codec (with regular code), and then import "Python code" that looks pretty much like anything you want, by adding a special # codec: my-weird-codec comment in the first line.
Right, so that wouldn't work anyways
!e
def allOnes(n:list[int]) -> bool:
if len(n)==0: return False
for i in n:
try:
1/i
except ZeroDivisionError:
return False #
return sum(n)==len(n)
print(allOnes([]))
print(allOnes([1]))
print(allOnes([1, 1, 1]))
print(allOnes([1, 1 + 1, 1]))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | False
002 | True
003 | True
004 | False
!e
def allOnes(n:list[int]) -> bool:
if len(n)==0: return False
for i in n:
try:
1/i
except ZeroDivisionError:
return False #
return sum(n)==len(n)
print(allOnes([3, 3, -3]))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
True

if the length is zero, all elements are equal to one
I know?
yes, and im saying that this specific part is incorrect
Here, this
i didnt mean to ping you with the first reply, sorry
it wasnt directed at you
Aight, no worries
!e
result = chr(
int(
ord(NameError.__class__.__eq__.__name__[len([].__class__.__name__)])
+ len(True.__class__.__name__) * (len(True.__class__.__name__) + len(None.__class__.__name__)) // len(None.__class__.__name__)
+ (len(True.__class__.__name__) - len(NameError.__class__.__name__))
+ len(True.__class__.__name__) + len(None.__class__.__name__) - (len(print.__class__.__eq__.__name__) - len(object.__class__.__name__))
)
) + chr(
int(
ord(NameError.__class__.__eq__.__name__[len([].__class__.__name__)])
+ len(True.__class__.__name__) // len(None.__class__.__name__) * len(None.__class__.__name__)
+ (len(True.__class__.__name__) - len(NameError.__class__.__name__))
+ (len(True.__class__.__name__) - (len(None.__class__.__name__) - (len(True.__class__.__name__) + len(None.__class__.__name__))))
+ len(True.__class__.__name__) + len(None.__class__.__name__)
)
)
print('Result: ', result)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Result: os
!e
print((lambda _, __, ___, ____: getattr(__import__(_(
____(
__(NameError.__class__.__eq__.__name__[___([].__class__.__name__)])
+ ___(True.__class__.__name__) * (___(True.__class__.__name__) + ___(None.__class__.__name__)) // ___(None.__class__.__name__)
+ (___(True.__class__.__name__) - ___(NameError.__class__.__name__))
+ ___(True.__class__.__name__) + ___(None.__class__.__name__) - (___(print.__class__.__eq__.__name__) - ___(object.__class__.__name__))
)
) + _(
____(
__(NameError.__class__.__eq__.__name__[___([].__class__.__name__)])
+ ___(True.__class__.__name__) // ___(None.__class__.__name__) * ___(None.__class__.__name__)
+ (___(True.__class__.__name__) - ___(NameError.__class__.__name__))
+ (___(True.__class__.__name__) - (___(None.__class__.__name__) - (___(True.__class__.__name__) + ___(None.__class__.__name__))))
+ ___(True.__class__.__name__) + ___(None.__class__.__name__)
)
)), 'name'))(*([chr]+[ord]+[len]+[int])))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
posix
From my look it surely have some bit manipulation, so maybe it was some string decoder, who knowns
Can you not match [a-zA-Z0-9] at all?
For the least, is it possible to print the input by that?
Yeah, you can use letters that are equivalent
So some sort of unicode that is like p and function as a p?
!e
𝚒𝚖𝚙𝚘𝚛𝚝 𝚛𝚊𝚗𝚍𝚘𝚖
𝚙𝚛𝚒𝚗𝚝(𝚛𝚊𝚗𝚍𝚘𝚖.𝚛𝚊𝚗𝚍𝚘𝚖())
:x: Your 3.12 eval job has completed with return code 1.
001 | File "/home/main.py", line 1
002 | 𝚒𝚖𝚙𝚘𝚛𝚝 𝚛𝚊𝚗𝚍𝚘𝚖
003 | ^^^^^^
004 | SyntaxError: invalid syntax
huh, wait a sec
My method of finding these is flawed..
Ah, no, it works. Just not with keywords.
!e
import 𝚛𝚊𝚗𝚍𝚘𝚖
𝚙𝚛𝚒𝚗𝚝(𝚛𝚊𝚗𝚍𝚘𝚖.𝚛𝚊𝚗𝚍𝚘𝚖())
:white_check_mark: Your 3.12 eval job has completed with return code 0.
0.6324942822469275
But you can call eval(), er.. I mean 𝚎𝚟𝚊𝚕 of course, so you can still do anything
Ah
Well
As much as I could compress, I have a converter which make any code -> only used 5 alphanumeric character including unicode substitute
Which obviously use eval/exec
>>> print.__self__
builtins
``` a quick way to get `builtins` module
(`__builtins__` is not very reliable, sometimes it is a module, sometimes - a dict)
lol
Does anybody know the exact difference between type(x) and x.__class__?
Is this summary by chatgpt correct? https://chatgpt.com/share/18cca388-5f72-4d42-8427-6cf62670acad
type(x) returns a real type of x - it looks up a pointer to a type in object's struct
x.__class__ is an attribute access, it acts like a regular attribute (like x.y). But it so happens that there is an attribute of that name defined in object class, so "descriptor protocol" kicks in. object.__class__ descriptor returns a type(x)
if __class__ is overriden in subclasses - then it will be used
if it is a descriptor - it will be triggered
if not - will be returned as is
x.__class__ = Y is an assignment, it also works as any other attribute assignment.
object.__class__.__set__ performs layout check, and if it is ok, it changes the type of x to Y
What i'm getting from this is type(x) is the same as x.__class__ unless __class__ attribute was manually overridden, which is bad practice
ok, thank you
!e
import 𝚛𝚊𝚗𝚍𝚘𝚖
𝚙𝚛𝚒𝚗𝚝(𝚛𝚊𝚗𝚍𝚘𝚖.𝚛𝚊𝚗𝚍𝚘𝚖())
:white_check_mark: Your 3.12 eval job has completed with return code 0.
0.25486736839355273
Do there exist methods that are not attributes, and do they have any usefulness?
Another similar question - do there exist properties that are not methods?
3rd question - do there exist properties that are not attributes?
I'm not sure I understand all of the questions. You can create methods (as in: instances of the method type) that aren't attributes of anything, but it's pretty useless.
if I go by definition "Attribute = Any name following a dot"
Properties as in @property: you can technically create properties that don't decorate functions, or decorate functions with them that aren't methods, but it's again pretty useless.
Same answer regarding properties that aren't attributes
thank you, i will treat them as in venn diagram
That's close enough, yeah.
attributes > descriptors > methods
> properties
I have a crazy idea
what if they remove commas in the next version of python
think about it. commas are actually not necessary
my_list = [1, 2, 3, 4]
could just be
my_list = [1 2 3 4]
also it works for functions
call_function(1 2 3 4)
want to do math for arguments? no problem
call_function(1 2 (3 + 4) 5)
int is not callable
why?
because it wouldn't make sense to
remove commas from python change my mind
pretend i'm the python interpreter
...(1, 2(3 + 4), 5)
calling an int
cant
nope
of course you cant call an int
replace the int literal with a variable
then it cant
the interpreter can be like "if its not callable then I'll treat it like parenthesis"
parsing happens before execution
the type is not known at parse time
You need to make it so it is statically distinguishable between call_function(1, 2, (3 + 4), 5) and call_finction(1, 2(3 + 4), 5
the parser has no idea whats callable and what isnt, it has a stream of tokens
python doesn't have a compiler like the C compiler
it can sort it out later
so you want to parse each statement only after executing all the previous ones?
So, built your own language :) python can do nothing about it
ehat about things with assignment expressions
ok then
nah. save it in the AST like a function call but then if its not callable later, the interpreter can treat it like args
the interpreter doesnt operate on the ast
that would be strangely inconsistent
also ^^^
the ast gets compiled to bytecode
ok
let me do that
give me a second
done
test_sources/mixins.requite line 1
// SPDX-FileCopyrightText: 2024 Daniel Aimé Valcour <fosssweeper@gmail.com>```
?
I made a compiler for you just now
see? no commas
did I mention that I am a coding ninja?
And how does it compile?
a language that is completely different to python can obviously have no commas
cf. lisp
no idea i just got some monkeys and typewriters
can someone help me im in 9th grade and im starting pyhton CSP but the teacher gave me like assignments that i dont even know anyhting about, does anyone know like the best website to learn pyhton on and like a one that would actually stick in ur memory, and how do i like make my code more accurate and shorter
the point we're making is that you cannot have python without commas
sure
this is valid in my langugae
and, thats a bit off topic isnt it
Well, I don't see a compiler 💀
same energy as "ah, this works in C, so it must work in python"
!ot
Please read our off-topic etiquette before participating in conversations.
I just see a file
my language is compiled but the ast builder from source is only 800 lines
interpreted language like python could do that easily
^^^^^
just because lisp, for example, has no commas, doesnt mean python can
no
being dynamic is exactly what makes this hard
its not lisp. look at the function calls
!ot Have fun with your language
Please read our off-topic etiquette before participating in conversations.
types are not known at compile time
they are like
this(arg1 arg2 arg3)
big language like python can't do that easily :>
no one said it was
parser ambiguity, impossible to resolve, period
for example
for example
The funny exact same message
jinx! :3
for example
god how do you talk about parsers when you can't even parse a sentence T^T
lol
do you even understand the operational semantics of english
If you are serious, (idk what you should do at this point)
If you are joking, go to ot
im gonna leave the conversation now, you're being off-topic and wrong and ignoring everyone when they gently explain to you how you're wrong
im seriously joking
ok
ok
I really want to ping a mod 💀
im done
make it whitespace sensitive
the real ambiguity would then be with implicit str concat, but you'd just give preference to passing them as args I guess
# works with positive integers
max = lambda a, b: (a//b*a + b//a*b) // (a//b + b//a)
min = lambda a, b: (a//b*b + b//a*a) // (a//b + b//a)
assert max(1, 1) == 1
assert max(2, 2) == 2
assert max(3, 5) == 5
assert max(5, 3) == 5
assert min(1, 1) == 1
assert min(2, 2) == 2
assert min(3, 5) == 3
assert min(5, 3) == 3
hmm
in C it is a bit nicer because // becomes /: ```c
int max(int a, int b) { return (a/ba + b/ab) / (a/b + b/a); }
me when I want to find min(0, 1)
I think in C it might work for negative negative as well
inf = 9999999999; min(x + inf, y + inf) - inf
BRUH
!e
result = (lambda _, __, ___, ____, _____, ______, _______, ________, _________, __________, ___________:
getattr(
__import__('builtins'),
().__class__.__eq__.__class__.__name__[:2] +
().__iter__().__class__.__name__[5:7]
)(
(lambda _, __, ___: _(_, __, ___))(
lambda _, __, ___:
bytes([___ % __]) + _(_, __, ___ // __) if ___ else
(lambda: _).func_code.co_lnotab,
_ << __________,
(((_____ << ____) + _) << ((___ << _____) - ___)) + (((((___ << __)
- _) << ___) + _) << ((_____ << ____) + (_ << _))) + (((_______ <<
__) - _) << (((((_ << ___) + _)) << ___) + (_ << _))) + (((_______
<< ___) + _) << ((_ << ______) + _)) + (((_______ << ____) - _) <<
((_______ << ___))) + (((_ << ____) - _) << ((((___ << __) + _) <<
__) - _)) - (_______ << ((((___ << __) - _) << __) + _)) + (_______
<< (((((_ << ___) + _)) << __))) - ((((((_ << ___) + _)) << __) +
_) << ((((___ << __) + _) << _))) + (((_______ << __) - _) <<
(((((_ << ___) + _)) << _))) + (((___ << ___) + _) << ((_____ <<
_))) + (_____ << ______) + (_ << ___)
)
)
)(
*(
[len] +
[ord] +
[sum] +
[int] +
list(range(7))
)
)
print(result)
where is the execution lul
huh
deletid cause it kept failing
it looks like brainf**k
its my attempt on esoteric python
lul
!e
code
oops
!e
print((lambda _, __, ___, ____, _____: getattr(__import__(_(
____(
__(NameError.__class__.__eq__.__name__[___([].__class__.__name__)])
+ ___(True.__class__.__name__) * (___(True.__class__.__name__) + ___(None.__class__.__name__)) // ___(None.__class__.__name__)
+ (___(False.__class__.__name__) - ___(NameError.__class__.__name__))
+ ___(True.__class__.__name__) + ___(None.__class__.__name__) - (___(print.__class__.__eq__.__name__) - ___(object.__class__.__name__))
)
) + _(
____(
__(NameError.__class__.__eq__.__name__[___([].__class__.__name__)])
+ ___(True.__class__.__name__) // ___(None.__class__.__name__) * ___(None.__class__.__name__)
+ (___(False.__class__.__name__) - ___(NameError.__class__.__name__))
+ (___(False.__class__.__name__) - (___(None.__class__.__name__) - (___(False.__class__.__name__) + ___(None.__class__.__name__))))
+ ___(True.__class__.__name__) + ___(None.__class__.__name__)
)
)), 'name'))(*([chr]+[ord]+[len]+[int] + [list(range(11))])))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
posix
\
What was it supposed to do
wr_i
!e
def debug(chr, ord, len, int, totenlist):
return chr(
totenlist[len(int.__class__.__name__)]
*totenlist[len(int.__class__.__name__)]
*totenlist[len(int.__class__.__name__)]
+(totenlist[len(int.__class__.__name__)]
*totenlist[len(int.__class__.__name__)]
*totenlist)[len(int.__class__.__name__)
*len(int.__class__.__name__)]
-totenlist[3]+(totenlist[len(int.__class__.__name__)+len(int.__class__.__name__)]*totenlist[len(int.__class__.__eq__.__name__)]-(len(print.__class__.__eq__.__name__)-len(int.__class__.__name__)+totenlist[len(print.__class__.__eq__.__name__)-len(int.__class__.__name__)])))+'a'+chr(totenlist[len(int.__class__.__name__)]
*totenlist[len(int.__class__.__name__)]
*totenlist[len(int.__class__.__name__)]
+(totenlist[len(int.__class__.__name__)]
*totenlist[len(int.__class__.__name__)]
*totenlist)[len(int.__class__.__name__)
*len(int.__class__.__name__)]-totenlist[4]+(totenlist[len(int.__class__.__name__)+len(int.__class__.__name__)]*totenlist[len(int.__class__.__eq__.__name__)]-(len(print.__class__.__eq__.__name__)-len(int.__class__.__name__)+totenlist[len(print.__class__.__eq__.__name__)-len(int.__class__.__name__)])))+'e'
print(debug(chr, ord, len, int, list(range(11))))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
name
Sucks
2000 letters limit
!e
def debug(chr, ord, len, int, totenlist):
return chr(
totenlist[len(int.__class__.__name__)]
*totenlist[len(int.__class__.__name__)]
*totenlist[len(int.__class__.__name__)]
+(totenlist[len(int.__class__.__name__)]
*totenlist[len(int.__class__.__name__)]
*totenlist)[len(int.__class__.__name__)
*len(int.__class__.__name__)]
-totenlist[len(int.__class__.__eq__.__name__)//len(int.__class__.__name__)+len(int.__class__.__eq__.__name__)//len(int.__class__.__name__)+len(int.__class__.__eq__.__name__)//len(int.__class__.__name__)]+(totenlist[len(int.__class__.__name__)+len(int.__class__.__name__)]*totenlist[len(int.__class__.__eq__.__name__)]-(len(print.__class__.__eq__.__name__)-len(int.__class__.__name__)+totenlist[len(print.__class__.__eq__.__name__)-len(int.__class__.__name__)])))+chr(ord('a'))+chr(totenlist[len(int.__class__.__name__)]
*totenlist[len(int.__class__.__name__)]
*totenlist[len(int.__class__.__name__)]
+(totenlist[len(int.__class__.__name__)]
*totenlist[len(int.__class__.__name__)]
*totenlist)[len(int.__class__.__name__)
*len(int.__class__.__name__)]-totenlist[len(int.__class__.__name__)]+(totenlist[len(int.__class__.__name__)+len(int.__class__.__name__)]*totenlist[len(int.__class__.__eq__.__name__)]-(len(print.__class__.__eq__.__name__)-len(int.__class__.__name__)+totenlist[len(print.__class__.__eq__.__name__)-len(int.__class__.__name__)])))+chr(ord('e'))
print(debug(chr, ord, len, int, list(range(11))))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
name
:x: Your 3.12 eval job has completed with return code 1.
001 | File "/home/main.py", line 1
002 | https://mystb.in/0ab558e1133a51abde
003 | ^
004 | SyntaxError: invalid decimal literal
sad
Your code just doesnt make sense thats why it fails
You provide less arguments to lambda than you actually have and wth is (lambda: _).func_code.co_lnotab
what about haskell?
go away with your functional nonsense
or should i better say disfunctional 🤣
thanks
hello="Hello"
world="world"
def return(a):
print(a)
return(hello, world)
!e
!e
code
I'm making a python variant of awk, pawk: https://github.com/kaddkaka/pawk
I'm thinking if there is any way to implement default print action of awk. For comparison, to print the first two lines of the input file:
awk 'NR <= 2'pawk 'if NR <= 2: print(F[0])'
I'm not sure if I want default action, I can't think of an elegant way to do it.
im not sure if this will be useful, but in single compilation mode all "unused" results are being passed to sys.displayhook ||(that is how REPL displays stuff, for example)||
>>> run = lambda s: exec(compile(s, '', 'single'))
>>> import sys; sys.displayhook = lambda obj: print(f'{obj} is being displayed')
>>> run('1;2')
1 is being displayed
2 is being displayed
None is being displayed
>>> run('3 + 4 < 5')
False is being displayed
None is being displayed
oh, so I could evaluate all unused resuts and do things with those, hmm 🤔
main.py line 44
# Poor mans way of implementing "keywords" by catching NameError```
you can have NEXT var that holds some special value, and if sys.displayhook gets this value you perform some "skipping" logic
btw NameErrors have .name attr
if e.name == 'NEXT': ...
main.py line 48
if str(e) == "name 'NEXT' is not defined":```
@fleet bridge Would you know why compile('if NR <=2: print(F[0])', '', 'single') gives syntax error?
I actually achieved a crash as well "core dumped" 🙀
python3
Python 3.10.12 (main, Jul 29 2024, 16:56:48) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> compile('if NR <=2: print(F[0])')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: compile() missing required argument 'filename' (pos 2)
>>> compile('if NR <=2: print(F[0])', '')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: compile() missing required argument 'mode' (pos 3)
>>> compile('if NR <=2: print(F[0])', '', 'single')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "", line 1
if NR <=2: print(F[0])
SyntaxError: invalid syntax
>>> Quit (core dumped)
needs \n at the end
also, you can't compile several statements one after the other in single mode
(but you can wrap them in if True: ...)
ah ok, so should use 'exec' here
(but not in single)
thanks
Hmm?
just adding \n worked with the single line if with single. But I need exec anyway for my usecase
with exec mode you will not get sys.displayhook integration
Can I hook this only for me exec call? I don't really want to add a hook for my "outer" code, just for the only I'm running with exec
oh 🤔
Hmm, then I guess this is not useful for me
I'm doing compile and then exec
(and if you're executing statements single)
What does this mean? The code I compile and exec is supplied by user, it is multi statement
hmm-
wrap it in one statement
if True:, yea-
also, look at what is done in timeit module
they make an entire function out of user's code and then compile and call it
"if True:\n" + textwrap.indent(code, "\t")
👍 Any other upsides to doing it that way?
if you combine everything into one piece of code and then just run it, you won't need messy and hacky ways of handling stuff like NEXT
btw NEXT is just continue
continue is much nicer, but for that I would have to wrap it in some run once loop?
Or rather, I want the NEXT in the user script to the next record in pawk's for loop (for line_no, line in enumerate(lines):
But I would have to do some fixups to the handling of BEGIN and NR
But still, it seems a bit backwards since I want the displayhook to only act on the user code
you can parse user code, and then unparse it, wrapping expression statements in some function
this is turning into a chore more than a hack 🤓
Not sure I like it, yet. The idea has to mature. Is it nice to parse python code?
!d ast.parse
ast.parse(source, filename='<unknown>', mode='exec', *, type_comments=False, feature_version=None)```
Parse the source into an AST node. Equivalent to `compile(source, filename, mode, ast.PyCF_ONLY_AST)`.
If `type_comments=True` is given, the parser is modified to check and return type comments as specified by [**PEP 484**](https://peps.python.org/pep-0484/) and [**PEP 526**](https://peps.python.org/pep-0526/). This is equivalent to adding [`ast.PyCF_TYPE_COMMENTS`](https://docs.python.org/3/library/ast.html#ast.PyCF_TYPE_COMMENTS) to the flags passed to [`compile()`](https://docs.python.org/3/library/functions.html#compile). This will report syntax errors for misplaced type comments. Without this flag, type comments will be ignored, and the `type_comment` field on selected AST nodes will always be `None`. In addition, the locations of `# type: ignore` comments will be returned as the `type_ignores` attribute of [`Module`](https://docs.python.org/3/library/ast.html#ast.Module) (otherwise it is always an empty list).
well, unparsing step is not required since AST can be compiled directly
it should be pretty easy to replace each ast.Expr (is it called like that?) statement with something else
ast.Expression for the statement
ah wait hold on
ast.Expr yea
ast.Expression for the eval() version
while (a := globals().setdefault("a", 5) - 1) >= 0 and (print("Correct") if 5 == (b := int(input("Give me a nr: "))) else print(f"Wrong {a} tries left")) != 5:
if b == 5: break
(d:=0,[(v:=(0 if d else int(input("Number: "))),0 if d else print("correct"if v==5 else f"incorrect: {(2-c)} tries left"),d:=v==5 or d)for c in range(3)])
one expression
nice xd
I mean that is just using ands instead of newlines
"just" is an underappreciation
i'm literally running a custom iterator to keep the loop alive
and again, this is entirely one expression
otherwise i wouldn't be able to "use and instead of newline"
I like that part
I just meant using ands and () feels like using ; instead of newlines
why?
nice 
A http server that serves from a static directory is really not hard in one line 😄
it's not hard if you reuse the logic from http.server
and why wouldn't you 😄
i haven't prevented that in the readme, so it's a valid point, thanks
the new requirement: make it async
(must run under async event loop)
and not reusing the logic from http.server
(no run_in_executor etc.)
why not 🤔
it's unclear to me if it could work with async gens, maybe this involves reimplementing @asyncio.coroutine to be able to define async lambdas
json parser should not be that hard
just take json from stdlib and translate it into one line
waiting for suggestions lol
reimplementing asyncio.coroutine as a lambda. 🤔
i should also mention that by one line i mean "one expression statement"
which is not the same as one line
import __hello__ is also one line
ah, and tests--we want to use pytest and fit all tests for a module in one expression statement
You are given a string of digits.
Your task is to split it into a strictly increasing sequence of numbers (in all possible ways).
141312 - input
possible splits:
141312
1 41312
1 41 312
14 1312
141 312
(I'm not sure that that is all possible ways :)
you also rearranged numbers
if you can rearrange them, then increasing constraint doesn't really make any sense
are those all possible ways?
yes, but most of them do not form an increasing sequence of numbers
i got ```
141312
1 41312
14 1312
141 312
1 4 1312
1 41 312
something missing?
feels right
I'm not sure how the skipping logic could actually work because I would need to break and redirect the program flow when NEXT is detected. Is it possible?
Also considering using continue instead of NEXT (not sure which one is preferable from user perspective), but naive use of continue currently and unsurprisingly leads to SyntaxError: 'continue' not properly in loop . So trying to more properly parse and combine the user script with pawk record loop might be next step.
compile eveyrthing into one loop, and continue will work
user could type NEXT but you can replace it with continue to make it do something useful
So I made a bunch of smaller modifications to the code, and currently the inner loop looks like this:
def process_file(program, lines, last_file, _locals):
"""Iterate over multiline text input and process with user program"""
for line_no, line in enumerate(lines):
last_line = line_no == len(lines) - 1
_locals["END"] = last_file and last_line
_locals["FNR"] = line_no + 1
# Full line as f[0] and the rest of columns start from f[1]
f = [line, *(intify(w) for w in line.split())]
_locals["F"] = f
_locals["NF"] = len(f)
# Poor mans way of implementing "keywords" by catching NameError
try:
exec(program, {}, _locals) # pylint: disable=exec-used
except NameError as e:
if e.name == "NEXT":
pass
else:
raise
_locals["BEGIN"] = False
_locals["NR"] += 1
I would want insert the user code at the # Poor comment, but still preferably keep this code mostly intact to get syntax highlighting and such
What are you doing actually? 
pawk!
@digital dirge https://github.com/kaddkaka/pawk
I actually don't know awk 😄
Hi
I read the readme tho, looks cool!
It's really cool and a very useful tool! From the preface of "The AWK programming language"
x PREFACE
Awk is a programming language that makes it possible to handle simple computations
with short programs, often only one or two lines long. An Awk program is a sequence of pat-
terns and actions that specify what to look for in the input data and what to do when it’s
found. Awk searches a set of files that contain text (but not non-text formats like Word docu-
ments, spreadsheets, PDFs and so on) for lines that match any of the patterns; when a match-
ing line is found, the corresponding action is performed. A pattern can select lines by combi-
nations of regular expressions and comparison operations on strings, numbers, fields, vari-
ables, and array elements. Actions may perform arbitrary processing on selected lines; the
action language looks like C but there are no declarations, and strings and numbers are built-
in data types.
Awk scans text input files and splits each input line into fields automatically. Because so
many things are automatic — input, field splitting, storage management, initialization — Awk
programs are usually much shorter than they would be in a more conventional language.
Thus one common use of Awk is for the kind of data manipulation suggested above. Pro-
grams, a line or two long, are composed at the keyboard, run once, then discarded. In effect,
Awk is a general-purpose programmable tool that can replace a host of specialized tools or
programs.
So I want a user of awk to be able to run for example pawk input_file -t 'if F[2] > 10: print(F[0])'
on an input such as:
kaddkaka 5
Trapture 9000
The output from running the command would be:
Trapture 9000
Here the 'if F[2] > 10: print(F[0])' part is the user program that I currently run by calling exec in the pawk src code.
What's the issue with exec?
It would be nice if a continue in the user code would skip to the next iteration of the for loop. Then I got get rid of the hacky try; except: NameError
# utils
Decode←10⊸×⊸+˜´⌽
Encode←10{⌽𝕗|⌊∘÷⟜𝕗⍟(↕1+·⌊𝕗⋆⁼0.5+1⌈⊢)}
# code
Splits←0⊸{𝕨𝕊⟨⟩:⟨⟨⟩⟩;∾(Decode(⊣∾¨⊣𝕊↓⟜𝕩˜)≠)¨𝕨(<⟜(Decode¨)/⊢)1↓↑𝕩}⟜Encode
Splits 141312
# result: ⟨ ⟨ 1 4 1312 ⟩ ⟨ 1 41 312 ⟩ ⟨ 1 41312 ⟩ ⟨ 14 1312 ⟩ ⟨ 141 312 ⟩ ⟨ 141312 ⟩ ⟩
So exec in itself is not a problem. But rather how the code being run interact with the surrounding code.
Is this APL?
Do you write directly in it like that? or transpile to it?
I first wrote the concept in python and then translated manually 😄
Uff 😅
You mean so it doesn't crash if the user overwrites _locals or something?
old thing but here you go
@__import__("fishhook").hook(object)
def __matmul__ (f, g): return lambda *a, **k: f(g(*a, **k))
prt = __import__("functools").partial
c = type("curried", (), dict(
__init__ =lambda s, f: vars(s).update(f=f, a=[], k={}),
__call__ =lambda s, *a, **k: s.a.extend(a) or s.k.update(k) or s,
__invert__=lambda s: prt(s.f, *s.a, **s.k)
))
all_ones = all @ ~c(map)(1 .__eq__)
there is infinite number of ways to write hello world
if you scroll this channel far enough you will find several dozens of hello worlds
Hi everyone, here's a Python framework for building distributed systems, hope our community can make it better together: https://github.com/gavinwei121/Jetmaker
seem off topic here
!e expression by itself is 207 characters ```py
s = '2726252423'
s = '141312'
result = [q for i in range(1<<len(s[1:]))if(q:=[int(x)for x in''.join(map(''.join,zip(bin(i)[2:].zfill(len(s)).replace('0','').replace('1',' '),s)))[1:].replace('','').split()])and all(x<y for x,y in zip(q,q[1:]))]
print(result)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
[[141312], [141, 312], [14, 1312], [1, 41312], [1, 41, 312], [1, 4, 1312]]
that was the first idea that came to mind: check all possible ways to split the string and take only good ones
enumeration is done by generating integers from 0 to 2**n in binary, and then interleaving it with input string
I was doing something else and stumbled across something pretty silly: It's fairly easy to convert between bases using just repeated regex application, as long as you go through base 1 :) https://paste.pythondiscord.com/65LA
congrats, you invented Markov algorithms
In theoretical computer science, a Markov algorithm is a string rewriting system that uses grammar-like rules to operate on strings of symbols. Markov algorithms have been shown to be Turing-complete, which means that they are suitable as a general model of computation and can represent any mathematical expression from its simple notation. Marko...
I actually love when that happens because it confirms my thoughts were good, I was just not the first person to come up with it 😄
144
||```python
B=len(A:=input())
for C in range(2**~-B):
D=[];E=''
for F in range(B):
E+=A[F]
if C>>F&1:D+=E,;E=''
D+=E,
eval('<'.join(D))and print(*D)
the inner loop could probably be golfed some more
142 with ||interleaving||
||python B=len(A:=input())-1 for C in range(2**B):eval('<'.join(map(str,E:=eval("".join(a+"_,"[int(b)]for a,b in zip(A,f'{C:0{B}b}1'))))))and print(*E)||
I really thought it would be way shorter 🤔
128 127 with ||leave-it-to-pychan|| ||```py
B=len(A:=input())-1
for C in range(2**B):*E,=eval("".join(a+"_,"[b>'0']for a,b in zip(A,f'{C:{B}b}1')));E==sorted(E)!=print(*E)
126 ||```py
B=len(A:=input())-1;C=2**B
while C:C-=1;*E,=eval("".join(a+"_,"[b>'0']for a,b in zip(A,f'{C:{B}b}1')));E==sorted(E)!=print(*E)
very clever
https://github.com/bswck/oneliners/tree/main
- A full-fledged JSON parser
what are you guys gonna give me if I do this?
json_parser_golf.py line 35
p=lambda s,j=''.join:({}['Extra Data Remaining']if[r:=p(I:=[*s][::-1])]and j(I).rstrip()else r)if isinstance(s,str)else float(i)if(S:=lambda s:s.__setitem__(slice(None),j(s).rstrip())or s)(s)and(i:=j(iter(lambda:s.pop()if s and s[-1]in'-+0123456789.eE'else 0,0)))else{'true':True,'false':False,'null':None}[c]if(c:=j(iter(lambda:s.pop()if s and s[-1].isalpha()else 0,0)))else[list,dict,j][(d:=ord(s.pop())//2%3)](iter(lambda:(s.pop()and p)if S(s)[-1]==(t:=']}"'[d])else[k if[k:=p(s)if d<2else s.pop()]and d==0else((k if isinstance(k,str)else{}['Keys must be Strings'],p(s))if d==1and(S(s),{}['Invalid Seperator']if s[-1]!=':'else s.pop())else(k if k!='\\'else('\b\f\n\r\t'+q)[('bfnrt'+q).index(q)]if(q:=s.pop())!='u'else chr(int(j(s.pop()for()in[()]*4),16)))if d==2else p),(s.pop()if l!=t else 0)if d<2and(l:=S(s)[-1])in','+t else 0if d==2else{}['Missing Seperator']][0],p))```
Pretty sure it mostly works?
doesnt handle infinity and nan but yeah this is kinda based
ill try to make a.. oneliner recursive descent parser
Inf and NaN aren't part of the json spec afaik
Maybe I should make a decent parser 🤔
is there a reason why does python's json handle them?
Because it's standard/for consistency I guess?
https://docs.python.org/3/library/json.html#json.JSONEncoder
If allow_nan is true (the default), then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats.
https://docs.python.org/3/library/json.html#standard-compliance-and-interoperability
This module does not comply with the RFC in a strict fashion, implementing some extensions that are valid JavaScript but not valid JSON. In particular:
- Infinite and NaN number values are accepted and output;
- Repeated names within an object are accepted, and only the value of the last name-value pair is used.
Since the RFC permits RFC-compliant parsers to accept input texts that are not RFC-compliant, this module’s deserializer is technically RFC-compliant under default settings.
Is it possible for python bytecode compiler to add a frozenset in co_consts? or from iterables it can only add tuples?
f = lambda x: frozenset((5,2,5))
dis.dis(f)
1 0 RESUME 0
2 LOAD_GLOBAL 1 (NULL + frozenset)
14 LOAD_CONST 1 ((5, 2, 5))
16 PRECALL 1
20 CALL 1
30 RETURN_VALUE
f.__code__
<code object <lambda> at 0x000001CCE7E94110, file "<stdin>", line 1>
f.__code__.co_consts
(None, (5, 2, 5))
oh, stop, it adds usual sets as frozen by default
>>> f = lambda x: {5,2,5}
>>> dis.dis(f)
1 0 RESUME 0
2 BUILD_SET 0
4 LOAD_CONST 1 (frozenset({2, 5}))
6 SET_UPDATE 1
8 RETURN_VALUE
Sort of, yeah. But then immediately turns it into a regular set with SET_UPDATE
does it mean it creates a copy?
but atleast it doesn't recalculate the hashes I guess
!e but you can put other things in co_consts:
def foo(): return 1, 2, 3
foo.__code__ = foo.__code__.replace(co_consts=(None, frozenset((1, 2, 3))))
print(foo())
:white_check_mark: Your 3.12 eval job has completed with return code 0.
frozenset({1, 2, 3})
I don't actually know, maybe it just sets a mutability flag? I don't know how frozensets work internally.
setting mutability flag will break the set for next call of the function
Ah, true
maybe there is some optimization mechanism "not to copy it completely until it's actually get mutated"
Then I guess SET_UPDATE probably makes a copy if it operates on a frozenset.
in fact you can put literally anything into co_consts, there is no restriction
It doesn't set a mutability flag, the opcodes are the equivalent of doing:
result = set()
result.update(the_constant)
But set.update() has an optimisation, if self is empty and the provided value is a set/frozenset, then it just copies the hash table over.
definitely not
using this approach you can't make two sets from one frozenset
Ohh, I didn't see the BUILD_SET before
I'm pretty sure frozensets and sets have different underlying structure, because one of them can grow, and other one is constant
..one has .hash set to -1
that's it
in the object structure the only different things between a frozenset() and a set() are the .ob_base (basically .__class__ in top-level) and .hash fields
interesting...
Does anyone know anything about OCR for batches of webtoon images for each episode using tesseract. I already have a python script that runs fine but nothing is produced in terms of text extraction.
Idk where to ask this problem of mine.
this is not a good place to ask
look at #media-processing or #data-science-and-ml
Alright thanks for letting me know.
!e ```py
print(chr(sum(range(ord(min(str(not())))))))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
ඞ
why discover this
?
They didn't
!e funny ```py
print(chr(sum(range(sum(range(29))-11))+sum(range(20))+sum(range(3))))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
𓂸
!e ```py
0xf or (lambda a, b: a + b) in [1, 2, 3, 4, 5]
:warning: Your 3.12 eval job has completed with return code 0.
[No output]
!e
import math
def m(n):return((n<<1)+(n<<(n%2+2)))^(n>>1)
a,b,c,d=0xea1dbc39,0x73ccab33,0x4f85d342,0x166454f0
e,f,g,h=0xde56059d28c30d09,0xf15340a75e9c480d,0x96d90450f0186553,0x37ec2bfd9680cf43
z,y=0x0005fe3126d76bff,0x0009d9f0f3a7d217+634418226003968
def k(n):print(n.to_bytes(12).decode())
for i in range(4):
for j in range(a%11):
a,b,c,d=b,c,d,a;a=m(a+b)+c;b=m(b+c)-d;c=m(c+d)+a;d=m(d+a)-b
e-=m(e)%(a&0xffffffff);f^=e;g^=(e+d)%0xffffffff;h=(h+a)%0xffffffffffffffff
a=a*b+c;z+=(a+b+d+e)%19
a=int((abs(a+b-c+d)%(1<<96))*(2/3));b=abs(b)%0xffffffff;z+=15.32
c=abs(c)%(b+0x003fffff);d=abs(d)%(c+0x0100b654);a=int(a+(b*c*d)**1.0331355)
for i in range(6):b,c,d=m(b),m(b+c),m(b+c+d)
k(((((((a^(b*c//d))-int(math.sqrt(e*f+c))<<7)>>20)<<20)-int(z**2))^(int(z)>>1)^y)+0x000481fffc000000)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello World!
Nice
:white_check_mark: Your 3.12 eval job has completed with return code 0.
ඞ
a,b=0,1
while a<9e5:print(a);a,b=b,a+b
anyone know an intresting way to replace the while loop or 9e5 or the print function
!e ```py
a,b=0,1
exec('print(a);a,b=b,a+b;'*10)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 0
002 | 1
003 | 1
004 | 2
005 | 3
006 | 5
007 | 8
008 | 13
009 | 21
010 | 34
here
replace 10 if necessary
okk
now i need it touhh
have it 36 bytes
which is the hard part
d=lambda p:chr(ord('A')+len(p)-1)if 1<=len(p)<=26 else''
m=lambda e:''.join(d(s)if s else' 'for s in e.split(' '))
e="............. ..... ............ ............ ............... , ....................... ............... .................. ............ ...."
print(f"Encoded message:{e}")
print(f"Decoded message:{m(e)}")
!e
code
!eval [python_version] <code, ...>
:x: Your 3.12 eval job has completed with return code 1.
001 | File "/home/main.py", line 1
002 | [python_version] <code, ...>
003 | ^
004 | SyntaxError: invalid syntax
!eval [python_version]
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | [python_version]
004 | ^^^^^^^^^^^^^^
005 | NameError: name 'python_version' is not defined
broo
:white_check_mark: Your 3.12 eval job has completed with return code 0.
a

!eval 3
d=lambda p:chr(ord('A')+len(p)-1)if 1<=len(p)<=26 else''
m=lambda e:''.join(d(s)if s else' 'for s in e.split(' '))
e="............. ..... ............ ............ ............... , ....................... ............... .................. ............ ...."
print(f"Encoded message:{e}")
print(f"Decoded message:{m(e)}")
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | Encoded message:............. ..... ............ ............ ............... , ....................... ............... .................. ............ ....
002 | Decoded message:MELLOAWORLD
its close
.uwuify
meh
uwu
print('hello world 0123456789')
✅ hello world printed
✅ digits from √2 printed
!e this uses 3 digits from √2 ```py
s = 'hweolrllod'
print(s[::2],s[1::2])
:white_check_mark: Your 3.12 eval job has completed with return code 0.
hello world
code
!eval 3
b64d=lambda e:bytes(int24>>i*8&0xFF for i in range(3,-1,-1)if e[-i]!='='for int24 in(int(q,16)<<i*6|int(q,16)<<(i-1)*6|int(q,16)<<(i-2)*6|int(q,16)<<(i-3)*6for q in(hex(b64c.index(e[i]))[2:]for i in range(0,len(e),4))))
b64c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
print(b64d("SGVsbG8gd29ybGQh"))
!e
(lambda f: (t * 1).from_address(id(int) + 88).__setitem__(0, f) or (print(1) or f))((t := (c := __import__("ctypes")).CFUNCTYPE(c.py_object, c.py_object))(lambda _: "hi!"))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
hi!
i remember i saw esoteric code which looked beautiful before
the whole program looked like it was an ascii art
anyone knows what i am saying
Donut?
That's decoding, you can search about base64, it is essential the best way to send binary data in non-binary accepting field
(That is not quite precise:
So:
def non-binary accepting field: a field that doesn't accept special character that usually ain't printable/provide a specific meaning to the computer/software in a general practice, or hardly convey any readable meaning to human
showcase of an "Operating System" concept, what extensions should i make folks?
just for clarity chatgpt did create the todo list
and the cookie clicker that wont work but i made everything else
if it's off topic then it's a challenge :p
that is not at all what an Operating System is supposed to do
so it is a concept for a set of different tools, but not an OS concept
its whatever lmao
im just a deadbeat loser programmer
Damn @fleet bridge why u have to rip him to shreds like that

i proved that python but restricted to a single expression, calls to builtin functions, the not keyword, and tuple creation is turing-complete.
(also no reflection/arbitrary code execution methods)
This subset of python is Turing-Complete by substitution with Cyclic Tag:
data string is encoded as follows:
0 => not()
1 => len(((),()))
program is encoded as follows:
; => list(map(next,map(iter,map(reversed,filter(min,enumerate(("previous code")))))))
0 => sum(list((list(map(next,map(iter,zip(list((not(),)),iter(int,sum(range(next(iter("previous code"))))))))),)),"previous code")
1 => sum(list((list(map(next,map(iter,zip(list((len(((),())),)),iter(int,sum(range(next(iter("previous code"))))))))),)),"previous code")
Substitution instructions:
Start with the program as a tuple containing the encoded data string. Then replace it with `list({said tuple})`. For each instruction, replace "previous code", with the code from the previous iteration
!e
print(chr(sum((sum(range(sum(range(ord(min(str(type(not())))))))),sum(range(sum(range(len(str(complex())),len(str(type(range(int())))))))), ord(str(len(str(not(not())))))))))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
💩
very similar to the a-z() discussions going on earlier
hmmm
were you inspired by the ctf team name https://twitter.com/chordbug/status/1834642829919781369
participating in a python ctf this weekend and our team name is chr(sum(range(ord(min(str(not()))))))
yes, in fact
i found that on the rust discord and then i sent it to my uni server. We then figured out that we could create any number. And then i decided i would figure out if it was turing-complete
one of us is working on an optimal solution finder for any given number
does someone need to post the jurassic park gif about being too busy doing something to evaluate whether the thing should be done at all
i was bored and had time to waste
seems pretty difficult if you want to support iterators, because you have to include sutff like sum(ord(k)for(k)in(str(help)))
yeah... i think they ended up giving up
zip([0],iter(int, something_that_is_zero_or_one)) my beloved
it's funny how i used iter as the main conditional, while filter is only used here to delete the first element
we considered comprehensions to be against the rules because it trivialized some things
in this particular case map does the same thing
sum(map(ord,str(help)))
but yeah in general comprehensions make things easy
comprehensions could be used duplicate lists and make those 0s and 1s above much easier
without needing to paste the code in 2 spots and making it exponentially grow
i spent like 2 hours trying to figure out how not to have that exponential growth but gave up
the condition inside the iter can be stored cant it
if only we had a way to make lambda: x
i should probably sleep instead of thinking about this
e.g. taking your conditional with the iter from earlier, you can store the condition like setattr(__loader__,str(),something_that_is_zero_or_one)
then get it with getattr(__loader__,str())
does that work for your system
the no-, restriction in the earlier challenges in this channel really took away a lot
oh, i didn't allow getattr and setattr because i considered those to be reflection and not in the spirit of the challenge, nor did i allow __loader__ because it's not a function. I originally lifted those restrictions, but i didn't think of that, so that's pretty cool
im sure theres some constant time way to get __loader__
or some other thing you can assign attributes to
after doing this challenge i feel like python's builtins are so arbitrary and random
are they reflection? they're just equivalent to x.y and x.y=a respectively
these are not typically seen under the realm of reflection i think
but something like hasattr is
getattr with a name that is not constant does feel like reflection to me
yeah, i come from a mostly statically typed background
the name is constant though
str()
i see, i didn't read the context, just "is getattr reflection"
more generally, as long as the variable name isnt being dynamically determined at runtime i would say its not reflective
e.g. using both getattr(x, str(1)) and getattr(x, str(2)) is still not reflective i would say
ah yeah
the general case of getattr is reflective definitely
when did python remove the ability to sum strings
really really long ago
oh
back from when cpython used svn instead of git
Wow I had no idea that was ever the case
I guess it makes sense, Python is older than git... I just never thought about it.
it was there since sum() was there
as in, python 2.3 alongside the addition of sum()
if i could sum strings, i could've made this a lot more concise
and format could've been used for ;
but I'm kinda glad i didn't go that route
using 2 arg iter made this really elegant
you can still
it only checks the type of start
my original plan for proving turing-completeness was fucking around with __code__ and implementing SKI calculus
!e ```py
print(sum(["a", "b", "c"], start=type('',(),{'add':lambda _,x:x})()))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
abc
..well i'll be damned
yeah, but the real question is how i would get the lambda
that falls under reflection surely
yeah that's why i didn't end up doing it
but still, sums="".join
types.LambdaType (types.FunctionType)
a lambda is a function
you can instantiate your own functions
and a function is
can't use . or imports for this
getattr with a static name 🥺
no imports is interesting though
do you not have __import__
its a builtin
i didn't allow it because itertools would make ct trivial
mm fair
and because it started with __ and didn't look like the rest
there's type(__loader__.get_code.__func__) for types.FunctionType, type(__loader__.get_code.__func__.__code__) for types.CodeType
that is if you can use those :p
question: you say only builtin functions, do you mean only builtin functions + types?
dir is reflective probably
dir always returns in alphabetical order
characterization ala unicode codepoint of the summation of the first numbers starting from zero with a length of the ordinal of the minimal character in the string produced by the boolean inverse of an empty tuple constant
:x: Your 3.12 eval job has completed with return code 1.
001 | File "/home/main.py", line 1
002 | print(getattr(next(iter(dir(iter)), help))
003 | ^
004 | SyntaxError: '(' was never closed
!e
print(type(getattr(exit,next(iter(dir(iter))))))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
<class 'method'>
we can get the method type
and that means we can get lambda: x i think
type(getattr(exit,next(iter(dir(iter)))))(iter, x) gives us lambda: iter(x)
list(map(list,map(next,map(reversed,zip(((),()),iter(type(getattr(exit,next(iter(dir(iter)))))(iter,x),()))))))
gives us [x, x]
i think i'll try to make ski calculus
import math
num = 42
is_even = True if int(int(bin(num*1)[2:],2)*69/(35+34))**(1 if 2*3.14/7.28 == 1 else max(0,-3,-7,1,83**0.00001))//num*(num-1+1)+((3.14+2.71828)*0) == num and not str(num/2).endswith(".5") or bool(round(math.exp(1.0328)-math.sin(1.0328**2)+1.0328**2-3)) else False
!e
print(type(getattr(exit,next(iter(dir(iter)))))(type(getattr(exit,next(iter(dir(iter))))),type(getattr(exit,next(iter(dir(iter))))))(lambda x,y,z:x+y+z)(1)(2)(3)(4))
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | type(getattr(exit,next(iter(dir(iter)))))(type(getattr(exit,next(iter(dir(iter))))),type(getattr(exit,next(iter(dir(iter))))))(lambda x,y,z:x+y+z)(1)(2)(3)
004 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
005 | TypeError: <lambda>() missing 1 required positional argument: 'z'
oops
oh wait that only works for 2 or less arguments
!e
print(type(getattr(exit,next(iter(dir(iter)))))(type(getattr(exit,next(iter(dir(iter))))),type(getattr(exit,next(iter(dir(iter))))))(lambda x,y:x+y)(1)(2))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
3
currying my beloved
type(getattr(exit,next(iter(dir(iter)))))(sum,()) is the I combinator. The other combinators are much more difficult to implement
every single time i tried to implement the K or S combinators, I ended up wanting a C combinator
the closest I got to a K combinator was this, but it broke the rules
lambda x: lambda y: type(getattr(exit,next(iter(dir(iter)))))(next,type(getattr(exit,next(iter(dir(iter)))))(type(getattr(exit,next(iter(dir(iter))))),type(getattr(exit,next(iter(dir(iter))))))(iter)(type(getattr(exit,next(iter(dir(iter)))))(type(getattr(exit,next(iter(dir(iter)))))(sum,()),x))(not y))()
or more compactly:
lambda x,y:bind(next,curry(iter)(bind(I,x))(not y))()
an alternative I combinator is just staticmethod
because yeah that is functionally an identity even if it doesn't return the same exact object
print(chr(sum(range(ord(min(str(not())))))))
!e
print(chr(sum(range(ord(min(str(not())))))))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
ඞ
you are a week too late with this one
Amogud
I'm so close to a K combinator. Arguments are passed in reverse order (via currying). I just need a way to get the string __init__. Also I found a nicer way to get __call__ as a str
type(str(),(),dict((("__init__",print),(min(dir(iter)),type(getattr(exit,min(dir(iter))))(sum,())))))(y)(x)
yes, I'm using print as a __init__. print has the unique property of taking a *args while also returning None. This is the only way I could think of to get a 2 or more argument function that returns None with these restrictions
you can get set.__and__ with getattr(set,min(dir(set)))
you can get __eq__ with next(reversed(next(reversed(next(reversed(next(reversed(min(filter(all,enumerate(filter(all,enumerate(filter(all,enumerate(filter(all,enumerate(dir(object()))))))))))))))))))
you can replace the print with staticmethod(getattr(type(str(),(),{},"__init__")), but that requires getting the string __init__ multiple times
@near gust have you considered the name class Lily(asyncio.tasks._PyTask):?
all python functions either return or error (or infinitely loop)
Is it possible to make "alternate returns", like in the bad old days? I.e. a function that returns to a completely different callstack.
im sure its possible
it would be fairly complicated though
It's hard to find something to link to, but before structured programming, with untamed goto (think longjmp).
This is apparently where the "single entry, single exit" rule comes from: it didn't mean "don't have several return statements", but "don't have returns that return to different places" (and also "don't enter the function anywhere other than at the beginning").
that is so unusual and pretty hard to imagine...
yup, it doesn't follow the widely standardized flow of programming
but it's plausible
silly comment i found while trying to find a way to do the above
Python/bytecodes.c line 2680
is_meth = 1; // For consistenct; it's dead, though```
okay i found out how
!e @restive void ```py
from ctypes import POINTER, c_void_p
from sys import _getframe as _gf
objhead_size = object.basicsize
ptr_size = tuple.itemsize
https://github.com/python/cpython/blob/3.12/Include/internal/pycore_frame.h
offset of f_frame from the base of struct _frame (A.K.A. PyFrameObject)
interpframe_off = objhead_size + ptr_size
def delete_frame(frame=None, depth=1):
if frame is None:
frame = _gf(1)
if depth < 1:
raise ValueError("depth must be 1 or above")
prev = cur = None
for _ in range(depth + 1):
prev = cur
cur = frame
frame = frame.f_back
if frame is None:
raise ValueError("depth exceeds top frame's child frame")
POINTER(c_void_p * 2).from_address(id(prev) + interpframe_off).contents[1] = c_void_p.from_address(id(frame) + interpframe_off)
def f():
abc()
def abc():
delete_frame()
return 7
print(f())
:white_check_mark: Your 3.12 eval job has completed with return code 0.
7
teehee~ avoiding errors :p ```pycon
def stopper():
... x = f()
... raise ValueError(x)
...
def f():
... return 2 + abc()
...
def abc():
... delete_frame(depth=2)
... return 7
...
stopper()
9
so cool
Nice
@restive void this goto implementation can jump into and out of functions: https://github.com/chilaxan/pysnippets/blob/main/goto_native.py
or at least it could when i wrote it