#esoteric-python

1 messages ยท Page 47 of 1

near gust
#

!e

print(hex(hash(max(enumerate(reversed(list(enumerate(list(enumerate(reversed(list(enumerate(reversed(list(enumerate(reversed(list(enumerate(reversed(list(enumerate(reversed(list(enumerate(reversed(list(enumerate(reversed(list(enumerate(reversed(list(enumerate(reversed(list(enumerate(reversed(list(enumerate(list(enumerate(list(enumerate(list(enumerate(list(enumerate(list(enumerate(list(enumerate(reversed(list(enumerate(reversed(list(enumerate(list(enumerate(reversed(list(enumerate(reversed(list(enumerate(reversed(list(enumerate(list(enumerate(reversed(list(enumerate(reversed(list(enumerate(reversed(list(enumerate(reversed(list(enumerate(reversed(list(enumerate(list(enumerate(reversed(list(enumerate(reversed(list(enumerate(reversed(list(enumerate(list(enumerate(list(enumerate(list(enumerate(list(enumerate(list(enumerate(reversed(list(enumerate(list(enumerate(reversed(list(enumerate(list(enumerate(reversed(list(enumerate(list(enumerate(reversed(list(enumerate(list(enumerate(reversed(list(enumerate(reversed(list(enumerate(reversed(list(enumerate(list(enumerate(list(enumerate(list(enumerate(list(enumerate(list(enumerate(list(enumerate(list(enumerate(reversed(list(enumerate(list(enumerate(reversed(list(enumerate(reversed(list(enumerate(reversed(list(enumerate(reversed(range(len(str(list()))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
night quarryBOT
near gust
#

nice

hybrid trail
#

that is really cool

#

how long did it take to bruteforce the hash?

#

hmmm, it is exactly 64 bits...

earnest wing
#

this is awesome

earnest wing
#

It's not cryptographic

digital dirge
#

hash of an int is the int, so that's extra easy

#

!e

print(hex(hash(0x133713371337)))
night quarryBOT
digital dirge
#

Still cool ๐Ÿ‘

distant wave
#

!e ```py
x=9
s=[1]x
v=[s[p:x:p]:=~-x//p
[0]for p in range(3,x,2)if sorted({*str(p)})==[*str(p)]]
print(2,*v,sep="\n")

#

I guess I can't star a :=?

night quarryBOT
distant wave
#

bleh

long fulcrum
#

most annoying thing ever ๐Ÿ˜ญ

bronze sorrel
#

the hell is this channel, the word estoric alone tells me not to try understand

grave grail
rugged sparrow
#

!e ```py
import gc

class magic:
def iter(self):
yield magic
for obj in gc.get_objects():
if isinstance(obj, frozenset) and magic in obj:
yield obj
return

weird = frozenset(magic())

print(f"{weird = }")
print(f"{weird in weird = }")
print(f"{hash(weird) = }")

night quarryBOT
karmic pumice
#

damn, the hash of a paradox

rugged sparrow
versed eagle
#

so cool

rugged sparrow
#

Similar trick works for tuples

#

!e ```py
import gc

class magic:
def length_hint(self):
return 1

def __iter__(self):
    for obj in gc.get_objects():
        if isinstance(obj, tuple):
            try:0 in obj
            except SystemError:
                yield obj
                break

weird = tuple(magic())
print(f"{weird = }")
print(f"{weird in weird = }")

night quarryBOT
rugged sparrow
#

Trying to think of a way to make a recursive frozen set without gc

fleet bridge
#

I wonder how that even works
how does that know hash of weird if it is not even fully created?

rugged sparrow
#

frozenset must account for recursion in its hash?

fleet bridge
#

why would it?

rugged sparrow
#

Tuples hash function doesn't

rugged sparrow
fleet bridge
#

hash(x) == hash({x})

versed eagle
#

oh thats delicious

rugged sparrow
#

Ah, the hash of a frozenset is cached

#

So when it's added, it's hash is computed and stored

fleet bridge
#

ah, now I get it

karmic pumice
night quarryBOT
fleet bridge
#

so this hash is not really consistent
if you recompute hash again, you will get different value

fleet bridge
#

run gc.collect() in the loop, it should produce same hashes

#

!e

import gc

class magic:
  def __iter__(self):
    yield magic
    for obj in gc.get_objects():
      if isinstance(obj, frozenset) and magic in obj:
        yield obj
        return
        
for _ in range(2):
  gc.collect()
  print(hash(frozenset(magic())))
night quarryBOT
fleet bridge
#

yay, I eyeballed it right

karmic pumice
#

hmh
what is not being collected though?

fleet bridge
#

set references itself, so it is not gc'd right away

#

and magic is in it, so you yield it into second set

fleet bridge
night quarryBOT
fleet bridge
#

ah, i missed a detail
when you found the set, you return immediately

so the first set contains itself
and the second one finds first one first, and then ends. so the seconds one also contains the first

idk how that changes hash though

humble beacon
rugged sparrow
#

I mean there are plenty of ways to make a recursive tuple

rugged sparrow
#

You can also do tuple->list-tuple

#

But its more fun to do tuple->tuple

serene stratus
rugged sparrow
#

Also only works in the versions where they have that bug fixed lol

#

!e could obviously just do this: ```py
from fishhook import hook

@hook(set)
def hash(self):
return hash(frozenset(self))

weird = set()
weird.add(weird)
print(f"{weird = }")```

night quarryBOT
rugged sparrow
#

But that's just fishhook doing the magic behind the scenes

long fulcrum
#

is there a shorter way i can be doing this to generate primes

x=7**9
s=[1]*x
for p in range(2,x):
    if s[p]:s[p::p]=~-x//p*[0]```
#

it cant be much slower unfortunately

hybrid trail
#

what does your code do

#

oh sieve i guess

#

you just don't do anything with the primes?

long fulcrum
#

i check if each digit is larger than the last and if so i print

hybrid trail
#

hmmm, i struggle with that hole a lot

hybrid trail
#

seems to be ascending primes

long fulcrum
#

yeah

hybrid trail
#

68 bytes is so short I bet that they're not doing actual primality checking

#

probably some other conditions that just happen to work for the 100 outputs

sick hound
#

Does anybody know if a regex match strings can be compared directly without checking if they are equal for all possible strings? maybe there is a way to reduce them to finite automata and compare the automata directly?

#

I want to know if regex expression r'x' and 'x' are equal for all possible strings x when passed to re.findall(x, text)

night quarryBOT
#
xy-problem

The XY problem can be summarised as asking about your attempted solution, rather than your actual problem.

Often programmers will get distracted with a potential solution they've come up with, and will try asking for help getting it to work. However, it's possible this solution either wouldn't work as they expect, or there's a much better solution instead.

For more information and examples, see http://xyproblem.info/.

versed eagle
#

i dont think this is an instance of the xy problem

fleet bridge
#

!pypi interegular

night quarryBOT
restive void
#

Or do you literally mean "Can a regex ever match something else when I add/remove the r prefix?", in that case the answer is yes (minimal example I can think of: re.findall(r"\b", "x") == ["", ""], but re.findall("\b", "x") == [])

fleet bridge
#

if a regex match strings can be compared directly
you can compare contents of matches

sick hound
fleet bridge
#

why do you want that? are absolutely sure that you need to know that?

sick hound
fleet bridge
#

r-prefix has nothing to do with regexes

sick hound
fleet bridge
#

nope
it has nothing to do with regexes

sick hound
fleet bridge
#

it is used to disable escaping in strings, which is convenient when there are a lot of backslashes in strings

#

and it just that happens that regexes have a lot of backslashes

fleet bridge
sick hound
# fleet bridge and it just that happens that regexes have a lot of backslashes
import re
text = '  \n foo  \n  '

match_0 = re.findall('[^\n\r\t\f\v ]', text, re.DEBUG)
match_1 = re.findall(r'[^\n\r\t\f\v ]', text, re.DEBUG)

print(match_0==match_1) # True
print(match_0)   # ['f', 'o', 'o']
print(match_1) # ['f', 'o', 'o']
print(id(match_0)==id(match_1)) # False

Does this mean r'y' and 'y' regexes are equivalent for all arbitrary strings and for all arbitrary regexes?

fleet bridge
fleet bridge
sick hound
lofty comet
#

It's the same string

fleet bridge
#

interesting counterexample
you already seen it in #python-discussion

Would you say regex r'[y]' is equivalent to '[y]' for arbitrary strings and regexes?
no
consider y = x]\b[y

#

for arbitrary strings and regexes?
i have no idea what you mean exactly by that

sick hound
# fleet bridge > interesting counterexample you already seen it in <#267624335836053506> > Wo...

i see, the instructions are different. so the r does change the regex after all in many cases?

import re
text = '  \n foo  \n  '

match_0 = re.search('[x]\b[y]', text, re.DEBUG)
print("--------------")
match_1 = re.search(r'[x]\b[y]', text, re.DEBUG)

print(match_0==match_1) # True
print(match_0)
print("--------------")
print(match_1)

"""

LITERAL 120
LITERAL 8
LITERAL 121

 0. INFO 12 0b11 3 3 (to 13)
      prefix_skip 3
      prefix [0x78, 0x8, 0x79] ('x\x08y')
      overlap [0, 0, 0]
13: LITERAL 0x78 ('x')
15. LITERAL 0x8 ('\x08')
17. LITERAL 0x79 ('y')
19. SUCCESS
--------------
LITERAL 120
AT AT_BOUNDARY
LITERAL 121

 0. INFO 8 0b1 2 2 (to 9)
      prefix_skip 1
      prefix [0x78] ('x')
      overlap [0]
 9: LITERAL 0x78 ('x')
11. AT UNI_BOUNDARY
13. LITERAL 0x79 ('y')
15. SUCCESS
True
None
--------------
None

"""

#

I wonder why the results show as equal even though regex used different instructions to arrive at the result in both cases

fleet bridge
#

did you even looked at the results?

#

they are empty, no wonder they are equal

#

two completely unrelated regexes can both dont match, and results would be equal

sick hound
fleet bridge
#

how is __eq__ involved in this?
None == None
there are no regex object (whatever that means) in your code

#

!e print(None == None)

night quarryBOT
sick hound
# fleet bridge how is `__eq__` involved in this? `None == None` there are no regex object (what...

you are too focused on this particular case of results. I am asking if there is a way to check if a regex is equivalent to a different regex. e.g. we know that r'y' and 'y' are different via counterexample. Now, how would you check if \S is equivalent to [^\n\r\t\f\v ] or r'[^\n\r\t\f\v ]'. We are back to square one, because we have no general checker (unless you know a tool that can directly compare regexes?)

fleet bridge
#

i linked the tool above

sick hound
fleet bridge
#

cant help you with that

#

the tool works great
it can build FSM's from regexes, and then you can compare FSM's

sick hound
sick hound
# fleet bridge the tool works great it can build FSM's from regexes, and then you can compare F...
import interegular

parse_pattern_0 = interegular.parse_pattern('[^\n\r\t\f\v ]')
parse_pattern_1 = interegular.parse_pattern(r'[^\n\r\t\f\v ]')
fsm_0 = parse_pattern_0.to_fsm()
fsm_1 = parse_pattern_1.to_fsm()
print(fsm_0)
"""
  name final? \t \n \x0b \x0c \r   anything_else 
-------------------------------------------------
* 0    False                       1
  1    True
"""
print(fsm_1)
"""
  name final? \t \n \x0b \x0c \r   anything_else 
-------------------------------------------------
* 0    False                       1
  1    True
"""
direct_comparison = interegular.compare_patterns(parse_pattern_0, parse_pattern_1)
print(list(direct_comparison)) # [(Pattern(options=(_Concatenation(parts=(_CharGroup(chars=frozenset({'\t', ' ', '\n', '\x0c', '\r', '\x0b'}), negated=True),)),), added_flags=<REFlags: 0>, removed_flags=<REFlags: 0>), Pattern(options=(_Concatenation(parts=(_CharGroup(chars=frozenset({'\t', ' ', '\n', '\x0c', '\r', '\x0b'}), negated=True),)),), added_flags=<REFlags: 0>, removed_flags=<REFlags: 0>))]

Python thinks they are the same, even though we established they can have different results on identical text searches.
Did I compare the regexes correctly, or should I have used:

parse_pattern_0 = interegular.parse_pattern("'[^\n\r\t\f\v ]'")
parse_pattern_1 = interegular.parse_pattern("r'[^\n\r\t\f\v ]'")

?

fleet bridge
#
parse_pattern_0 = interegular.parse_pattern("'[^\n\r\t\f\v ]'")
parse_pattern_1 = interegular.parse_pattern("r'[^\n\r\t\f\v ]'")
``` these two are obviously different, no tool is needed for that
sick hound
fleet bridge
#

๐Ÿคฆโ€โ™‚๏ธ

fleet bridge
sick hound
fleet bridge
#

if you use the same regex, result will always be the same

#

otherwise it would be weird if the same regex produced different results

sick hound
fleet bridge
#

of course

#

because they are different

#

first one matches only strings that start with ', second one matches only strings that start with r

sick hound
fleet bridge
#

!e print("r")

night quarryBOT
fleet bridge
#

it is just a letter in this context

sick hound
fleet bridge
#

"r''" is not the same as r''

fleet bridge
#

we should stop, this is clearly off-topic to this channel

#

open a help thread if you need further help with understanding of string literals

versed eagle
#

r'\\y' and '\\y' are two different things

#

for example

#

thats trivial

#

but for an arbitrary regex determining whether they're equivalent is not trivial

versed eagle
versed eagle
#

but generally its not trivial to determine whether two regexes match the same set of strings i think

#

if it were there wouldnt be a library for it lol

sick hound
versed eagle
#

well it depends maybe

#

its certainly not undecidable for actual regular expressions, which match against regular languages

#

but "actual regular expressions" python's regexes are not

#

nor most modern regex implementations

#

since they include things like backreferencing capture groups

sick hound
#

!e print("sigma sigma")

night quarryBOT
sick hound
#

!r

#

!r print ( "sigma sigma" )

#

!e print("ัƒ")

night quarryBOT
sick hound
# versed eagle not undecidable

the reason why I think arbitrary regex equivalence comparison is undecidable is that with complex enough regex patterns the problem will be able to be reduced to a halting problem. Wouldn't more and more recursive and self-referential behaviour appear for more and more complex regexes, making the problem just as hard as halting problem?

fleet bridge
#

vanilla regex always halts

sick hound
fleet bridge
#

no

sick hound
sick hound
# fleet bridge no

but don't regex backreferences require a turing machine to be fully supported?

fleet bridge
versed eagle
#

formal regular expressions, anyway

#

with formal regular expressions, you can enumerate the set of strings that each describes (using some sentinel for * instead of expanding it) and then compare those sets

proper vault
#

regular expressions as implemented in Python do not necessarily describe a regular language, so that's not all that applicable

versed eagle
hybrid trail
#

Another installment in the programming with only a-z and parens: given a string with space separated integers, compute their sum (eval and exec disallowed as well)

fleet bridge
#

if there is no restriction, is there a shorter way to do this?:

s='1 2 3'
print(sum(map(int,s.split())))
hybrid trail
#
print(eval(s.replace(*' +')))```
hybrid trail
quartz wave
#

world works in mysterious ways i guess

hybrid trail
#

maybe you can ;)

quartz wave
#

no idea where to start-

digital dirge
hybrid trail
#

Yes

proper vault
#

@hybrid trail is A-Z allowed?

hybrid trail
#

nope

proper vault
#

Noted

proper vault
#

!e

from operator import methodcaller
from operator import itemgetter
print(sum(int(x)for x in methodcaller(itemgetter(len(str(help)))(dir(str)))('1 2 3 4')))

Pretend the string is input()

night quarryBOT
proper vault
#

Not sure if the imports are cheating

hybrid trail
#

very interesting method, but it does have forbidden chars space and newline

proper vault
#

Oh space is bad

#

That makes this approach much harder

quartz wave
grave grail
#

Challenge: write a prime number generator with only 5 [a-zA-Z0-9 \n] character, gl

karmic pumice
#

as in, len(set(code)) <= 5? or 5 characters in general, len(code) <= 5?

quartz wave
#

done

#

no language specified so i assumed math

grave grail
#

*Challenge: write a prime number generator in python with only 5 [a-zA-Z0-9 \n] character, with no import, gl

earnest wing
#

prime

hard spoke
#

2

unborn sphinx
#

not sure if that can go here, but why not

karmic pumice
#

!e

class _arg:
  def __getitem__(self, n):
    new = _arg()
    new.n = n
    return new
  def __mul__(self, val):
    return lambda *args: args[self.n] * val
arg = _arg()
class fn:
  def __init__(self, _):
    ...
  def __rshift__(self, thing):
    return matcall(thing)
class matcall:
  def __init__(self, f):
    self.f = f
  def __matmul__(self, args):
    if not isinstance(args, tuple):
      args = (args, )
    return self.f(*args)

double = fn(int) >> arg[0] * 2

println = matcall(print)

println @ f"{double @ 4}"
night quarryBOT
unborn sphinx
grave grail
karmic pumice
unborn sphinx
#

i'll do several args later today

#

but also i just realised that my initial idea doesnt work, like add @ 2, 3 evaluates to... a tuple of add @ 2 and 3, which i forgor about

karmic pumice
#

i think it would be cool to make it curried, add @ 2 @ 3
you can use the amount of thing in fn to know how much args does it have

unborn sphinx
karmic pumice
#

i think its (add @ 2) @ 3

unborn sphinx
#

should be that way cuz... same operator same priority, ig

restive void
#

Pretty sure it's left-associative

hard spoke
karmic pumice
#

enddo functors?? monads?

#

!e

class q:
  def __init__(self, x):
    self.x = x
  def __matmul__(self, other):
    return q((self.x, other))
print((q(1) @ 2 @ 3).x)
night quarryBOT
grave grail
#

*Challenge: write a prime number generator that infinitvely generate prime number and print it until Ctrl+C in python with only 5 [a-zA-Z0-9 \n] character with no import, gl

versed eagle
#

with only 5 characters?

grave grail
#

Well, you can use unlimited amount of character that isn't those

restive void
#

Instructions unclear, please provide regex.

#

Like I have to pick five from this set but can use them as often as I like, or I get five uses of those chars total?

karmic pumice
earnest wing
#

truly ascii with a top hat

grave grail
grave grail
#

Also btw, eval/exec is allowed

#

:)

restive void
#

Ah, too bad. I have a solution without exex/eval, relatively short, but using those chosen chars several times.

grave grail
grave grail
#

But other way are welcome :)

restive void
#

45 chars, with the other interpretation:

iter((int()**int()+int()**int()).__int__,int)
#

(itern)

grave grail
restive void
#

!e probably not what you meant, but it does infinitely produce primes

x = iter((int()**int()+int()**int()).__int__,int)
print(next(x))
print(next(x))
print(next(x))
print("...")
night quarryBOT
grave grail
#

...

#

*a prime number generator that infinitely produce unique prime that wasn't generated before

craggy hamlet
#

most primes have been generated already

grave grail
#

*a prime number generator that infinitely produce incremental prime number from 2(inclusive)

craggy hamlet
night quarryBOT
grave grail
craggy hamlet
#

i dont see any restraints

grave grail
#

Basically now:

Challenge: write a prime number generator that infinitely produce incremental prime number from 2(inclusive) and print it until Ctrl+C in python with only 5 [a-zA-Z0-9 \n] character with no import, gl

hard spoke
#

i don't think there's much of anything you can write with only 5 characters

versed eagle
grave grail
earnest wing
#

why bother with a challenge if you only allow one solution

#

just show it off

grave grail
#

Such as lambda suggest, unicode abuse, I didn't block that (just don't like it

#

Because it is still reasonably fun

unborn sphinx
#

@karmic pumice there i go (also i couldnt come up with a name so coffeesnake it is ๐Ÿ’€)

fleet bridge
#

can you golf this?

import collections.abc
import typing as t

def collapse_numbers_into_ranges(
    nums: collections.abc.Iterable[int],
) -> collections.abc.Iterator[list[int]]:
    '''
    takes an iterable of ints (not necessrily in sorted order)
    returns an iterable of [x,y] or [x] (for single-element ranges)
    '''
    # reference implementation:
    import itertools

    rng = []
    for x in itertools.chain(sorted(nums), [t.cast(int, ...)]):
        if not rng:
            rng = [x, x]
            continue
        if x == rng[-1] + 1:
            rng[-1] = x
        else:
            yield rng if rng[0] != rng[1] else [rng[0]]
            rng = [x, x]

# tests:
def fmt(nums: list[int]) -> str:
    return ','.join('-'.join(map(str, rng)) for rng in collapse_numbers_into_ranges(nums))
assert fmt([]) == ''
assert fmt([1]) == '1'
assert fmt([1, 2]) == '1-2'
assert fmt([1, 2, 3]) == '1-3'
assert fmt([1, 2, 3, 5]) == '1-3,5'
assert fmt([1, 3, 5]) == '1,3,5'
assert fmt([1, 3, 5, 6, 7]) == '1,3,5-7'
assert fmt([1, 7]) == '1,7'
assert fmt([5, 4, 7, 6, 3]) == '3-7'
assert fmt([5, 4, 7, 3]) == '3-5,7'


subtle viper
#
def collapse_numbers_into_ranges(s):
 t=z=''
 for x in*sorted(s),2j:
  if''!=t!=x-1:yield(z,t)[z==t:];z=x
  t=x
``` untested
fleet bridge
subtle viper
#

actually no wait-

fleet bridge
subtle viper
fleet bridge
#

works ๐ŸŽ‰

#

good job, here is a frog for you: ๐Ÿธ

subtle viper
#

ty ^^

#

~~1b down:

def collapse_numbers_into_ranges(s):
 t=z=''
 for x in*sorted(s),2j:
  if''!=t<x-1!=(yield(z,t)[z==t:])or''==z:z=x
  t=x
```~~ nvm.
#

assert fmt(func([1, 2, 3, 3, 4, 5])) == '1-3,3-5' fails- :<

fleet bridge
#

idk if repeated numbers should be allowed

#

originally I needed that function to nicely display set of numbers, so there were no duplicates possible

subtle viper
clear venture
#

!e

a = [1,2,3,4,100]
b = a.copy()
[next(...for a[i]in b[len(a)-i-1::-1])for i in range(len(a))]

print(a)
night quarryBOT
quartz wave
unborn sphinx
#

@karmic pumice here's more

fleet bridge
#
>>> 8 // 2 .__mul__ // print
16
real leaf
#

Hey all, is there a "division" of esoteric python for minimum lines?

#

I'm not sure it's considered esoteric, but it feels like a challenge that fits in.

fleet bridge
#

that is called "code golfing" - minimizing code size (not the number of lines, but rather the number if characters)

real leaf
#

I juset found out about the compile() function python has, and was wondering if you could make any single program one line by just compressing everything into one string and compiling, then executing it?

karmic pumice
#

you can do that by exec'ing a string, yes
compile is unnecessary here

real leaf
fleet bridge
#

you can indeed compress anything into one line
exec('multiline code goes here') is even simpler than your suggestion
but you even can do that without using exec/evval/compile/etc...

fleet bridge
long fulcrum
versed eagle
grizzled rose
#

Hi

#

!code

night quarryBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

grizzled rose
#
from pygame import*;from random import*;init();j=display;z=j.set_mode((400,300));c=time.Clock();q=255;t=10;r=draw.rect;S=R,L,D,U=range(K_RIGHT,K_UP+1);s,d,f=[(100,50),(90,50),(80,50)],R,(n:=lambda:(randint(0,39)*t,randint(0,29)*t))()
while 1:
 for e in event.get():
  if e.type==QUIT:quit()
  if e.type==KEYDOWN:d=k if(k:=e.key)in S else d
 x,y=s[0];x+=(d==R)*t-(d==L)*t;y+=(d==D)*t-(d==U)*t;s=[(x,y)]+s[:-1];f=n()if s[0]==f else f
 if not(0<=x<400 and 0<=y<300)or s[0]in s[1:]:break
 z.fill([q]*3);[r(z,(0,q,0),(*p,t,t))for p in s];r(z,(q,0,0),(*f,t,t));j.update();c.tick(t)
quit()
#

Can anybody help me modify it to be lessweight to be only 400 bytes?

hybrid trail
#

do you need if e.type==QUIT:quit()?

hybrid trail
#

also your snake does not seem to get longer, not sure if that is intentional

gleaming linden
quartz wave
#

do you really need to do quit() at the end of the program?

#

never did pygame before so i don't really know- :p

quartz wave
#

shaved off 29 bytes but i'm not sure about making it to sub-400 =-=

quartz wave
#

*40b now ```py
from pygame import*
from random import*
init()
j=display
z=j.set_mode((400,300))
c=time.Clock()
q=255
t=10;T=t,t
r=draw.rect
S=R,L,D,U=79,80,81,82
s=(100,50),(90,50),(80,50)
d=R
g=randrange
f=g(40)*t,g(30)*t
while 1:
for e in event.get():e.type==QUIT!=quit();e.type==KEYDOWN!=(d:=[d,k:=e.key-2**30][k in S])
x,y=s[0];x+=(d==R)*t-(d==L)*t;y+=(d==D)*t-(d==U)*t;k=x,y;*s,l=k,*s
if k==f:s+=l,;f=g(40)*t,g(30)*t
if not 300>y>=0<=x<400 or k in s[1:]:break
z.fill([q]*3);[r(z,(0,q,0),p+T)for p in s];r(z,(q,0,0),f+T);j.update();c.tick(t)
quit()

#

is discord highlighting broken-

#

.

#

gosh

#

i just found a new bug with highlighting :D

#

*g ```py
from this import *

this is out of the codeblock!!
#

whyy--

karmic pumice
quartz wave
#
- d=r
+ d=R
karmic pumice
#

yep

quartz wave
#

it's also possible to have an apple spawn with collision to the snake but i'm not adding that check in- :p

#

the snake growing was just added in too..

karmic pumice
#

its so minimalistic and cool with rounded borders and stuff

versed eagle
hybrid trail
#

482 ```python
from pygame import*
from random import*
j=display
z=j.set_mode((400,300))
t=10;T=t,t
r=draw.rect
S=R,L,D,U=b'OPQR'
f,*s=(100,50),(90,50),(80,50)
d=R
g=randrange
while 1:
for e in event.get():e.type==QUIT!=quit();e.type==KEYDOWN<(d:=[d,k:=e.key&255][k in S])
x,y=s[0];x+=(d<L)*t-(d==L)*t;y+=(d==D)*t-(d>D)*t;k=x,y;*s,l=k,*s
if k==f:s+=l,;f=g(40)*t,g(30)*t
if not 300>y>-1<x<400or k in s[1:]:break
z.fill(-1);[r(z,5**9,p+T)for p in s];r(z,'red',f+T);j.flip();time.Clock().tick(t)

floral meteor
#

It's an old screenshot. Sometimes I am confused by the thoughts of my past mind

rugged sparrow
# floral meteor

is that interned strings modification to cause 'f' to equal ''?

floral meteor
#

yes

#

another gem from old screenshots related to this channel

hybrid trail
gilded briar
#

How to get Discord spam tool

versed eagle
#

lmao

fleet bridge
signal dock
quartz wave
# hybrid trail 482 ```python from pygame import* from random import* j=display z=j.set_mode((40...

463 ```py
import pygame as p,random as r
j=p.display
z=j.set_mode((400,300))
t=10;T=t,t
g=r.randrange
r=p.draw.rect
S=d,L,D,U=b'OPQR'
f,*s=(100,50),(90,50),(80,50)
while 1:
for e in p.event.get():a=e.type;a<257!=quit();a<769<(d:=[d,k:=e.key&255][k in S])
x,y=s[0];x+=(d<L)*t-(d==L)*t;y+=(d==D)*t-(d>D)*t;k=x,y;*s,l=k,*s
if k==f:s+=l,;f=g(40)*t,g(30)*t
(300>y>-1<x<400)<1>r;k in s[1:]>r;z.fill(-1);[r(z,5**9,p+T)for p in s];r(z,'red',f+T);j.flip();p.time.Clock().tick(t)

hybrid trail
#

if we're assuming we only need to handle the two events you could remove the 769 condition

#

also could you could replace quit() with something like Z to trigger a namerror?

quartz wave
#

second i can do

#

but first one doesn't make sense to me-

hybrid trail
#

hmm, you're right

#

i assumed the only events were quit and keydown ๐Ÿคฆ

gleaming linden
#

Nvm randint takes 2 args

gleaming linden
#

are the >rs meant to nameerror?

hybrid trail
#

not namerror, r is defined (it is aliased to random)

#

but it will error, yes

quartz wave
#

i just thought NameError was too boring :p

gleaming linden
#

oh right comparisons can error

#
import pygame as p,random as r
j=p.display
z=j.set_mode((400,300))
t=10
g=r.randrange
r=p.draw.rect
S=d,L,D,U=b'OPQR'
f=t,5;*s,=(9,5),(8,5)
while 1:
 for e in p.event.get():a=e.type;a<257!=quit();a<769<(d:=[d,k:=e.key&255][k in S])
 x,y=s[0];x+=d<L;x-=d==L;y+=d==D;y-=d>D;k=x,y;*s,l=k,*s
 if k==f:s+=l,;f=g(40),g(30)
 (30>y>-1<x<40)<1>r;k in s[1:]>r;z.fill(-1);[r(z,5**9,(x*t,y*t,t,t))for x,y in s];r(z,5**15,(f[0]*t,f[1]*t,t,t));j.flip();p.time.Clock().tick(t)
``` untested 461
quartz wave
#

seems to work

hybrid trail
#

change 'red' to 5**15 for another byte

quartz wave
#

it's 0b..

hybrid trail
#

oops

gleaming linden
#

added it anyway because it looks cooler

hybrid trail
gleaming linden
#

oh oops

#

hmm

quartz wave
#

455 459?? ```py
import pygame as p,random as r
j=p.display
z=j.set_mode((400,300))
t=10
g=r.randrange
r=p.draw.rect
S=d,L,D,U=b'OPQR'
f=t,5;s=(9,5),(8,5)
while 1:
for e in p.event.get():a=e.type;a<257!=quit();a<769<(d:=[d,k:=e.key&255][k in S])
x,y=s[0];x+=d<L;x-=d==L;y+=d==D;y-=d>D;k=x,y;s,l=k,s
if k==f:s+=l,;f=g(40),g(30)
(30>y>-1<x<40)<1>r;k in s[1:]>r;z.fill(-1);[r(z,5**9,(x
t,y
t,t,t))for x,y in s];r(z,'red',(f[0]*t,f[1]*t,t,t));j.flip();p.time.Clock().tick(t)

hybrid trail
#

change the definition of s to just (9,5),(8,5) for -2

quartz wave
#

i somehow got OverflowError: Python int too large to convert to C long

#

oh

#

it's the 5**15

gleaming linden
#

so what's the best now?

quartz wave
#

i think

gleaming linden
#

ah

quartz wave
#

oh my god it's the 5**15.

hybrid trail
# gleaming linden so what's the best now?

453

import pygame as p,random as r
j=p.display
z=j.set_mode((400,300))
t=10
g=r.randrange
r=p.draw.rect
S=d,L,D,U=b'OPQR'
f=t,5;s=(9,5),(8,5)
while 1:
 for e in p.event.get():a=e.type;a<257>b;a<769<(d:=[d,k:=e.key&255][k in S])
 x,y=s[0];x+=d<L;x-=d==L;y+=d==D;y-=d>D;k=x,y;*s,l=k,*s
 if k==f:s+=l,;f=g(40),g(30)
 (30>y>-1<x<40)<1>r;k in s[1:]>r;z.fill(-1);[r(z,5**9,(x*t,y*t,t,t))for x,y in s];r(z,'red',(f[0]*t,f[1]*t,t,t));j.flip();p.time.Clock().tick(t)
gleaming linden
#

alr

hybrid trail
#

changed 5**15 back to 'red'

quartz wave
#

oh

#

i accidentally reverted the !=quit() -> >b change

gleaming linden
#
import pygame as p,random as r
j=p.display
z=j.set_mode((400,300))
t=10
g=r.randrange
r=p.draw.rect
S=d,L,D,U=b'OPQR'
h=f=t,5;s=(9,5),(8,5)
while 1:
 for e in p.event.get():a=e.type;a<257>b;a<769<(d:=[d,k:=e.key&255][k in S])
 x,y=h;*s,l=h,*s;x+=d<L;y-=d==L;y+=d==D;y-=d>D;h=x,y
 if h==f:s+=l,;f=g(40),g(30)
 (30>y>-1<x<40)<1>r;h in s[1:]>r;z.fill(-1);[r(z,5**9,(x*t,y*t,t,t))for x,y in s];r(z,'red',(f[0]*t,f[1]*t,t,t));j.flip();p.time.Clock().tick(t)
``` 452?
quartz wave
#

crashes for some reason :p

gleaming linden
#

i guess not then

quartz wave
#

452 works ```py
import pygame as p,random as r
j=p.display
z=j.set_mode((400,300))
t=10
g=r.randrange
r=p.draw.rect
S=d,L,D,U=b'OPQR'
f=t,5;h=9,5;s=h,(8,5)
while 1:
for e in p.event.get():a=e.type;a<257>b;a<769<(d:=[d,k:=e.key&255][k in S])
x,y=h;x+=d<L;x-=d==L;y+=d==D;y-=d>D;h=x,y;s,l=h,s
if h==f:s+=l,;f=g(40),g(30)
(30>y>-1<x<40)<1>r;h in s[1:]>r;z.fill(-1);[r(z,5**9,(x
t,y
t,t,t))for x,y in s];r(z,'red',(f[0]*t,f[1]*t,t,t));j.flip();p.time.Clock().tick(t)

gleaming linden
#

~~```py
import pygame as p,random as r
j=p.display
z=j.set_mode((400,300))
t=10
g=r.randrange
r=p.draw.rect
S=d,L,D,U=b'OPQR'
f=t,5;h=9,5;s=h,(8,5)
while 1:
for e in p.event.get():a=e.type;a<257>b;a<769<(d:=[d,k:=e.key&255][k in S])
h[0]+=(d<L)-(d==L);h[1]+=(d==D)-(d>D);s,l=h,s
if h==f:s+=l,;f=g(40),g(30)
(30>y>-1<x<40)<1>r;h in s[1:]>r;z.fill(-1);[r(z,5**9,(x
t,y
t,t,t))for x,y in s];r(z,'red',(f[0]*t,f[1]*t,t,t));j.flip();p.time.Clock().tick(t)

quartz wave
#

you forgot the x and y in the bound checks

gleaming linden
#

oh right

quartz wave
#

also h is a tuple

hybrid trail
#

does 'red' -> U**8 work

#

actually it is bigger than 5**15 so probably not lol

gleaming linden
#
import pygame as p,random as r
j=p.display
z=j.set_mode((400,300))
t=10
g=r.randrange
r=p.draw.rect
S=d,L,D,U=b'OPQR'
f=t,5;h=9,5;s=h,(8,5)
while 1:
 for e in p.event.get():a=e.type;a<257>b;a<769<(d:=[d,k:=e.key&255][k in S])
 x,y=h;x+=d<L;x-=d==L;y+=d==D;y-=d>D;h=x,y;h in s>r;*s,l=h,*s
 if h==f:s+=l,;f=g(40),g(30)
 (30>y>-1<x<40)<1>r;z.fill(-1);[r(z,5**9,(x*t,y*t,t,t))for x,y in s];r(z,'red',(f[0]*t,f[1]*t,t,t));j.flip();p.time.Clock().tick(t)
``` 448
quartz wave
#

that would fail

#

that is unless the snake also consumes an apple in the same period

hybrid trail
#

version control via discord lol

quartz wave
#

okay after further testing that's a galactic edge case

#

448 valid

gleaming linden
quartz wave
#

yellow apple variant for t**8

hybrid trail
#

i keep trying and failing to use hash instead of random

gleaming linden
#

id maybe?

hybrid trail
#

I don't think id changes between runs

#

so the apple would spawn in the same place every time

gleaming linden
#

i thought it was memory address in cpython

#

which would be the same if you don't do anything in between runs ig

hybrid trail
#

you can get 429 but it depends on the position of the snake as a hash so often it is the same

quartz wave
#

also the snake can reverse directions apparently

restive void
#

The id() of an object will typically change between runs, but yeah, it's not guaranteed.

quartz wave
#

same with going up and you can press down

versed eagle
hybrid trail
#

421, pretty sure it should be legal

from pygame import*
j=display
z=j.set_mode((400,300))
t=10
r=draw.rect
S=d,L,D,U=b'OPQR'
f=t,5;h=9,5;s=h,(8,5)
while 1:
 for e in event.get():a=e.type;a<257>b;a<769<(d:=[d,k:=e.key&255][k in S])
 x,y=h;x+=d<L;x-=d==L;y+=d==D;y-=d>D;h=x,y;h in s>r;*s,l=h,*s
 if h==f:s+=l,;f=id(e)%40,id(e)%30
 (30>y>-1<x<40)<1>r;z.fill(-1);[r(z,5**9,(x*t,y*t,t,t))for x,y in s];r(z,'red',(f[0]*t,f[1]*t,t,t));j.flip();time.Clock().tick(t)
#

id should make it completely different between runs, and python tuple[int] hash should have good rng

quartz wave
#

oh

#

i just used id(e)

hybrid trail
#

that works

quartz wave
#

there's an obnoxious increase in the amount of apples spawning on edges but other than that it seems pretty random

hybrid trail
#

is it fine that the apple can never spawn in some squares

quartz wave
#

i came up with a pretty weird thing

#

428 ```py
from pygame import*
j=display
z=j.set_mode((400,300))
t=10
r=draw.rect
S=d,L,D,g=b'OPQR'
f=t,5;h=9,5;s=h,(8,5)
while 1:
for e in event.get():a=e.type;a<257>b;a<769<(d:=[d,k:=e.key&255][k in S]);g^=id(e)//9
x,y=h;x+=d<L;x-=d==L;y+=d==D;y-=d>D;h=x,y;h in s>r;s,l=h,s
if h==f:s+=l,;f=g%40,g%30
(30>y>-1<x<40)<1>r;z.fill(-1);[r(z,5**9,(x
t,y
t,t,t))for x,y in s];r(z,'red',(f[0]*t,f[1]*t,t,t));j.flip();g^=time.Clock().tick(t)

#

user dependent randomness...?

hybrid trail
#

whats the point?

quartz wave
#

what point

#

generate numbers that look random

subtle viper
#

now we just need to shave 29 more off that :p

gleaming linden
#

make a pygame fork designed for golfing

#

pygm or something

grave grail
#

lol

hybrid trail
# quartz wave 428 ```py from pygame import* j=display z=j.set_mode((400,300)) t=10 r=draw.rect...

410

from pygame import*
j=display
t=10
r=j.set_mode((400,300)).fill
S=d,L,D,g=b'OPQR'
f=t,5;x,y=h=9,5;s=h,(8,5)
while 1:
 for e in event.get():a=e.type;a<257>b;a<769<(d:=[d,k:=e.key&255][k in S]);g^=id(e)//9
 x+=d<L;x-=d==L;y+=d==D;y-=d>D;h=x,y;h in s>r;*s,l=h,*s
 if h==f:s+=l,;f=g%40,g%30
 (30>y>-1<x<40)<1>r;r(-1);[r(5**9,(x*t,y*t,t,t))for x,y in s];r('red',(f[0]*t,f[1]*t,t,t));j.flip();g^=time.Clock().tick(t)
earnest snow
rough moat
#

the most cursed part of that entire thing is the from pygame import*

earnest snow
#

S=d,L,D,g=b'OPQR'?
x+=d<L;x-=d==L;y+=d==D;y-=d>D;h=x,y;h in s>r;*s,l=h,*s?

hybrid trail
#

the second line is what moves the snake

#

the first line instantiates the arrow key directions

earnest snow
#

just saw it

#

g^=id(e)//9

#
g^=id(e)//9
#

how can something not work without a g^=id(e)//9

hybrid trail
rough moat
#

could have sworn // would still return a float in some cases

#

oh it's if you divide floats

earnest snow
#

Oh it's for random

#

just noticed, you use g for randomness

hybrid trail
#

actually .tick() is probably not random enough

earnest snow
#

id(s) should be

#
from pygame import*
j=display
t=10;W=Clock()
r=j.set_mode((400,300)).fill
S=d,L,D,g=b'OPQR'
f=t,5;x,y=h=9,5;s=h,(8,5)
while 1:
 for e in event.get():a=e.type;a<257>b;a<769<(d:=[d,k:=e.key&255][k in S]);
 x+=d<L;x-=d==L;y+=d==D;y-=d>D;h=x,y;h in s>r;*s,l=h,*s;
 if h==f:s+=l,;f=id(f)%40,id(e)%30
 (30>y>-1<x<40)<1<r;r(-1);[r(5**9,(x*t,y*t,t,t))for x,y in s];r('red',(f[0]*t,f[1]*t,t,t));j.flip();W.tick(t)

414

hybrid trail
#

that rng seems random enough to me

karmic pumice
#

what are the a<257>b doing

hybrid trail
#

if event.type < 257, exit

#

checks for the quit event

karmic pumice
#

if a<257, it will check for it being >b, and that will error?

hybrid trail
# earnest snow ```py from pygame import* j=display t=10;W=Clock() r=j.set_mode((400,300)).fill ...

398 which I assume you meant to type

from pygame import*
j=display
t=10
r=j.set_mode((400,300)).fill
S=d,L,D,g=b'OPQR'
f=t,5;x,y=h=9,5;s=h,(8,5)
while 1:
 for e in event.get():a=e.type;a<257>b;a<769<(d:=[d,k:=e.key&255][k in S])
 x+=d<L;x-=d==L;y+=d==D;y-=d>D;h=x,y;h in s>r;*s,l=h,*s
 if h==f:s+=l,;f=id(f)%40,id(e)%30
 (30>y>-1<x<40)<1<r;r(-1);[r(5**9,(x*t,y*t,t,t))for x,y in s];r('red',(f[0]*t,f[1]*t,t,t));j.flip();Clock().tick(t)
earnest snow
#

even then, for my pygame just Clock() works though

hybrid trail
#

hmm, it doesn't work for me

#

NameError: name 'Clock' is not defined

#

I wonder why

earnest snow
#

pygame-ce 2.5.0 (SDL 2.30.3, Python 3.10.5)

#

yours?

hybrid trail
#

pygame 2.6.0 (SDL 2.28.4, Python 3.10.12)

#

I just installed it yesterday for this

earnest snow
#

better install pygame-ce though as pygame is not longer in support and -ce is the comunity edition

#

maybe it's a comunity edition feature or smth

rough moat
earnest snow
rough moat
#

i know its possible to do that sort of stuff without walrus but frankly i can never be bothered

#

walrus logic is already fucked

rough moat
earnest snow
karmic pumice
#

!e

print((d:={},exec("import math as _",d))[0]["_"])

__import__ without __import__

night quarryBOT
rough moat
#

the main use i have for walruses is just changing external variables in a list comprehension

#

which is basically required for something like mandelbrot, afaik

#
>>> n = 0
>>> [n:=n+1 for i in range(10)]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> n
10
karmic pumice
#

!e

n=0
l=locals()
[0 for _,l["n"]in zip(range(10),iter(lambda:n+1,None))]
print(n)
night quarryBOT
rough moat
#

that is fucked up

#

ngl i didnt even know you could use iter() like that, ive never really used it

#

why does that work with the sentinel set to None but it doesn't without it??

karmic pumice
#

single argument iter is for, well, iterating iterables, usually __iter__
i suppose they could make something like

def iter(thing):
  if callable(thing):
    while True:
      yield thing()

but then iter(callable & iterable) would be weird

rough moat
#

oh

karmic pumice
#

nowadays walrus could be used here instead

while block := f.read(64):
  ...
rough moat
rough moat
#

i dont think ive literally ever seen this used

jolly rock
#

Yeah I don't really see the point

rough moat
#

ive had a few cases where i imagine itโ€™d be handy

#

sometimes py will treat a positional one like a keyword one and then when i declare that keyword argument somewhere else it errors

not sure if this would prevent that though

karmic pumice
# jolly rock Yeah I don't really see the point

something like def __init__(self, **kwargs): or __call__ in functools.partial could make use of it, to avoid collision of the self that is being passed as the partial arg with the partial instance itself (the "implicitly" passed one)

mortal thorn
#

I have used both * and /.

If you don't want to expose the internal names of the variables or want to be able to change the parametrar names without having to maybe update other code that calls that function.

quartz wave
# hybrid trail 398 which I assume you meant to type ```python from pygame import* j=display t=1...

391 ```py
from pygame import*
j=display
t=10
r=j.set_mode((400,300)).fill
S=d,L,D,U=b'OPQR'
f=t,5;x,y=h=9,5;s=h,(8,5)
while 1:
for e in event.get():a=e.type;a<257>b;a<769<(d:=[d,k:=e.key&255][k in S])
x+=d<L;x-=d==L;y+=d==D;y-=d>D;h=x,y;h in s>r;*s,l=h,s
if h==f:s+=l,;f=id(f)%40,id(e)%30
(30>y>-1<x<40)<1<r;r(-1);[r(5**9
(p!=f)or'red',(p[0]*t,p[1]*t,t,t))for p in s+[f]];j.flip();Clock().tick(t)

#

oh wait a minute

#

390 ```py
from pygame import*
j=display
t=10
r=j.set_mode((400,300)).fill
S=d,L,D,U=b'OPQR'
f=t,5;x,y=h=9,5;s=h,(8,5)
while 1:
for e in event.get():a=e.type;a<257>b;a<769<(d:=[d,k:=e.key&255][k in S])
x+=d<L;x-=d==L;y+=d==D;y-=d>D;h=x,y;h in s>r;s,l=h,s
if h==f:s+=l,;f=id(f)%40,id(e)%30
(30>y>-1<x<40)<1<r;r(-1)
for p in
s,f:X,Y=p;r(5**9
(p!=f)or'red',(Xt,Yt,t,t))
j.flip();Clock().tick(t)

#

388 ```py
from pygame import*
j=display
t=10
r=j.set_mode((400,300)).fill
S=d,L,D,U=b'OPQR'
f=t,5;x,y=h=9,5;s=h,(8,5)
while 1:
for e in event.get():a=e.type;a<257>b;a<769<(d:=[d,k:=e.key&255][k in S])
x+=d<L;x-=d==L;y+=d==D;y-=d>D;h=x,y;h in s>r;s,l=h,s
if h==f:s+=l,;f=id(f)%40,id(e)%30
30>y>-1<x<40or b;r(-1)
for p in
s,f:X,Y=p;r(5**9
(p!=f)or'red',(Xt,Yt,t,t))
j.flip();Clock().tick(t)

#

okay i'm doing my assignments bye

hybrid trail
#

376 ```python
from pygame import*
j=display
t=10
r=j.set_mode((400,300)).fill
d,L,D=b'OPQ'
f=t,5;x,y=h=9,5;s=h,(8,5)
while 1:
for e in event.get():a=e.type;a<257>b;a<769>78<(k:=e.key&255)<83>(d:=k)
x+=d<L;x-=d==L;y+=d==D;y-=d>D;h=x,y;h in s>r;*s,l=h,s
if h==f:s+=l,;f=id(f)%40,id(e)%30
30>y>-1<x<40or b;r(-1);c='red'
for X,Y in f,s:r(c,(Xt,Y
t,t,t));c=5**9
j.flip();Clock().tick(t)

quartz wave
somber raptor
#

guiys i wanna make this code work my redfininf the meaning of the keyword false

False = 1
print(False)

this should print 1

#

someone help

versed eagle
#

use codecs

somber raptor
#

python crashed

grave grail
#

Idk if using ctypes would be possible cuz they a different in bytecode

somber raptor
#

it worked

#

๐Ÿ™

#

python crashed

versed eagle
somber raptor
#

it did

versed eagle
#

well no

#

obviously not

somber raptor
#

well urm aktchully

versed eagle
# somber raptor

you're screwing with refcount stuff (which is why python is crashing)

#

what you are NOT doing is changing the value

somber raptor
#

should i not screw with it

versed eagle
#

correct

#

at least not how you're doing

somber raptor
#

oh no

#

my python file got corrupted

#

ANYWAYS

karmic pumice
#

!e

import ctypes as c
(c.c_char * 12).from_address(id(True) + 16)[:] = c.string_at(id(False) + 16, 12)
print(True == False)
night quarryBOT
versed eagle
#

!e ```py
x = 0 # using x to prevent const-folding
print(True + x + True)
from ctypes import *
cast(id(True), POINTER(c_int))[6] = 2
print(True + x + True)

night quarryBOT
versed eagle
#

@somber raptor im guessing that's something like what you want

somber raptor
#

oh wow

#

hope my pc doesnt crash

karmic pumice
versed eagle
#

its different in the actual code, but that's an equivalent struct wrt. object offsets

karmic pumice
#
typedef struct _PyLongValue {
    uintptr_t lv_tag; /* Number of digits, sign and flags */
    digit ob_digit[1];
} _PyLongValue;

struct _longobject {
    PyObject_HEAD
    _PyLongValue long_value;
};

is what i found

versed eagle
#

PyObject_HEAD has the refcount stuff and the ob_type

#

theres actually stuff before the objects also

#

gc tags and whatnot

karmic pumice
karmic pumice
#

it should be possible to pretty easily replace the repr and other dunders with ctypes

karmic pumice
night quarryBOT
versed eagle
#

you can replace it for just one

karmic pumice
#

how do you replace a method for a single value? the method is only part of the type, no? or you mean that i could define a new type and set True's type to that?

versed eagle
night quarryBOT
versed eagle
#

exactly that

karmic pumice
#

yeah i see that makes sense

#

oh, also, if you keep an eye on peps,

#

!pep 667

night quarryBOT
karmic pumice
#

when thats implemented, that should make it pretty easy to modify the locals of the calling function, right?
like just modifying inspect.stack()[1].frame.f_locals should work
is there an easy way to do that currently?
like

import inspect
def var(name, value):
  inspect.stack()[1].frame.f_locals[name] = value

def f():
  var("x", 42)
  print(x)

or that wont work even with it? because at parse time x is not seen defined in f so it will not count as local?

#

!e

def f():
  exec("x = 1")
  return x
print(f())
night quarryBOT
karmic pumice
#

like here
(i think thats whats happening here)

somber raptor
#
m=lambda A,B:[[sum(a*b for a,b in zip(r,c))for c in zip(*B)]for r in A]
p=lambda M,n:(R:=[[1]*len(M)for _ in range(len(M))],(R:=m(R,M)if n%2 else R,M:=m(M,M),n:=n//2)[0])[-1]if n else 0
f=lambda n:p([[0,1],[1,1]],n-1)[0][1]if n else 0
print(f(100))

outputs 2 why

#

based on the binet formula with matrix multiplication

karmic pumice
#

maybe you wanted to have some form of a loop in p? because you just do the thing once and end up with [[1, 2], [1, 2]]

clear venture
#

What's the most cursed way to reverse a list?

#

I posted this earlier but it got buried

#

!e

a = [1,2,3,4,100]
b = a.copy()
[next(...for a[i]in b[len(a)-i-1::-1])for i in range(len(a))]

print(a)
night quarryBOT
versed eagle
clear venture
#

The example is in place but any way as long as it's cursed

somber raptor
#
def matrix_fib(n):
    def m(A, B):return[[sum(A[i][k]*B[k][j]for k in range(len(B)))for j in range(len(B[0]))]for i in range(len(A))];
    def pow(M,p):
        if p==0:return[[1,0],[0,1]];
        half=pow(M,p//2);
        if p % 2 == 0:return m(half,half);
        else:return m(m(half,half),M);
    if n == 0:return 0;
    elif n == 1:return 1;
    result=pow([[0,1],[1,1]],n);return result[0][1];
print(matrix_fib(100));

cpp moment

fleet bridge
#

you don't really need matrix multiplication here

somber raptor
#

proof

somber raptor
# karmic pumice like here (i think thats whats happening here)
matrix_fib = lambda n: (
    (lambda m: (lambda pow: (
        lambda M, p: (
            [[1, 0], [0, 1]] if p == 0 else
            (m(pow(M, p // 2), pow(M, p // 2)) if p % 2 == 0 else m(m(pow(M, p // 2), pow(M, p // 2)), M))
        )
    ))(
        lambda A, B: [[sum(A[i][k] * B[k][j] for k in range(len(B))) for j in range(len(B[0]))] for i in range(len(A))]
    )
    )(
        [[0, 1], [1, 1]], n
    )[0][1] if n > 1 else (0 if n == 0 else 1)
)
print(matrix_fib(100))

help

karmic pumice
#

what did you expect? (lambda m: (lambda pow: (...)))(whatever) gives you the lambda pow, which only takes a single argument, and you are passing it two with the ([[0, 1], [1, 1]], n)

somber raptor
#

what the almighty hell have i got myself into

#
matrix_fib = lambda n: (
    (lambda m: (
        lambda pow: (
            pow([[0, 1], [1, 1]], n) if n > 1 else 1 if n == 1 else 0
        )(lambda M, p: (
            (lambda x: m(x, x))(M) if p % 2 == 0 else m(m(M, M), M) if p > 1 else M
        )(M, p // 2))
    ))(lambda A, B: [[sum(A[i][k] * B[k][j] for k in range(len(B))) for j in range(len(B[0]))] for i in range(len(A))])
)
print(matrix_fib(100))
#
fibonacci = (
    lambda n: (
        (lambda matrix_mult: (
            lambda matrix_pow: (
                matrix_pow(
                    [[0, 1], [1, 1]], 
                    n
                )[0][1] if n > 1 else (0 if n == 0 else 1)
            )
        )(
            lambda M, p: (
                [[1, 0], [0, 1]] if p == 0 else
                M if p == 1 else
                (lambda half_pow: (
                    matrix_mult(half_pow, half_pow) if p % 2 == 0 else
                    matrix_mult(M, half_pow)
                )(matrix_pow(M, p // 2)))
            )
        )(
            lambda A, B: [[sum(A[i][k] * B[k][j] for k in range(len(B))) for j in range(len(B[0]))] for i in range(len(A))]
        )
    )
)
print(fibonacci(100))
karmic pumice
#

missing parens, but also, you're using matrix_pow inside lambda M, p: ...: it isnt bound at that point
i dont know how are you even writing this, are you just doing random stuff?

somber raptor
#

im using code to dranslate it

#

๐Ÿคท

#

wtf is this:
<function <lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda> at 0x7fb8a5621040>

karmic pumice
#

!e

print((lambda:(lambda:(lambda:(lambda:()))))()()())
night quarryBOT
fleet bridge
#
from __future__ import annotations
import typing as t
import collections.abc as t_abc


def c3[X](x: X, get_bases: t_abc.Callable[[X], list[X]], /) -> list[X]:
    def merge(mros: list[list[X | None]]) -> list[X | None]:
        if not any(mros):
            return []
        for candidate, *_ in mros:
            if all(id(candidate) not in map(id, tail) for _, *tail in mros):
                return [candidate] + merge(
                    [tail if head is candidate else [head, *tail] for head, *tail in mros]
                )
        else:
            raise TypeError("no legal mro")

    def _c3(x: X) -> list[X | None]:
        if bases := get_bases(x):
            return [x] + merge([_c3(base) for base in bases])
        else:
            return [x, None]

    m = _c3(x)
    assert m[-1] is None
    assert all(x is not None for x in m[:-1])
    return m[:-1]  # type: ignore


def test():
    # fmt: off
    assert c3(1, {1:[],2:[],3:[1,2]}.get) == [1]
    assert c3(2, {1:[],2:[],3:[1,2]}.get) == [2]
    assert c3(3, {1:[],2:[],3:[1,2]}.get) == [3, 1, 2]

    assert c3(1, {1:[],2:[],3:[],4:[1,2],5:[2,3],6:[3,1]}.get) == [1]
    assert c3(4, {1:[],2:[],3:[],4:[1,2],5:[2,3],6:[3,1]}.get) == [4, 1, 2]
    assert c3(5, {1:[],2:[],3:[],4:[1,2],5:[2,3],6:[3,1]}.get) == [5, 2, 3]
    assert c3(6, {1:[],2:[],3:[],4:[1,2],5:[2,3],6:[3,1]}.get) == [6, 3, 1]
    try:
        c3(7, {1:[],2:[],3:[],4:[1,2],5:[2,3],6:[3,1],7:[4,5,6]}.get)
    except TypeError:
        pass # ok
    else:
        raise Exception(f"expected error")

    assert c3(7, {1:[],2:[],3:[],4:[1,2],5:[2,3],6:[1,3],7:[4,5,6]}.get) == [7, 4, 5, 6, 1, 2, 3]
    # fmt: on

    return True
assert test()
``` C3 linearization
how far can you golf it?
versed eagle
subtle viper
versed eagle
#

all the import stuff is for typing lol

fleet bridge
fleet bridge
#

what's the shortest way to raise TypeError?

raise TypeError
1+()
()()
id()
{[]} # not sure what exception this will raise, iirc unhashability errors are TypeError

is it possible in less than 4 chars? what are other fun ways to do it in pretty low number of chars?

#
+()

f() # only if you have variable f that is not callable or does not allow passing 0 args 
+x # only if you have non-numeric variable x
~x # non-int x
gleaming linden
#

0@0

fleet bridge
#
0[0]
0()
mortal thorn
#
-""
-()
-[]
-{} 
versed eagle
#

here

def M(*m):
 if not any(m):return[]
 for c,*_ in m:
  if 1^any(id(c)in map(id,t)for _,*t in m):return[c]+M(*[([h,*t],t)[h is c]for h,*t in m])
 else:0@0
c3=lambda X,G:(_:=lambda x:[x]+(M(*map(_,b))if(b:=G(x))else[0]))(X)[:-1]
#

i dont know what c3 linearization is so i dont know how to golf the underlying algorithm at all lol

#

but that passes the tests

long fulcrum
#

is it possible to simplify these to be shorter?

*2//10
*2%10
fleet bridge
#
n = 123
x=n*2//10;y=n*2%10
x,y=n*2//10,n*2%10
x,y=divmod(n*2,10)
long fulcrum
#

and then to add them just sum() isnt it

#

or would that be longer

quartz wave
versed eagle
#
n*2//10+n*2%10
sum(divmod(n*2,10))
#

ยฏ_(ใƒ„)_/ยฏ

long fulcrum
#

yeah ๐Ÿ˜ญ

karmic pumice
# versed eagle i dont know what c3 linearization *is* so i dont know how to golf the underlying...

the thing that flattens and orders class hierarchies to form an MRO
usually it just ends up flattening things

# there is an implied "object" at the end of each one
class A:
  ... # A.mro = [A]
class B(A):
  ... # B.mro = [B, *flatten(A.mro)] = [B, A]
class C:
  ... # C.mro = [C]
class D(B, C):
  ... # D.mro = [D, *flatten(B.mro), *flatten(C.mro)] = [D, B, A, C]

but when there are multiple parents with the same thing in the mro it gets funny, how i understand it is

class A: ...

class B: ...

class C: ...

class D: ...

class E: ...

class K1(C, A, B): 
  ... # K1.mro = [K1, C, A, B]

class K3(A, D): 
  ... # K3.mro = [K3, A, D]

class K2(B, D, E): 
  ... # K2.mro = [K2, B, D, E]

class Z(K1, K3, K2):
  ... # Z.mro = ?
  # well, obviously start with Z itself,
  # then K1,
  # K1 has     [K1, C, A, B      ],
  # K3 has     [K3,    A,    D   ],
  # K2 has     [K2,       B, D, E],
  # so,
  # we take K1,
  # from it we take C because its unique in it, but we dont take A, B because they are also met in the mro's of the later things in the inheritance tree
  # then, from K3 we take K3 and A (its the last one with it), and dont take D,
  # then, from K2 we take K2 and B, D, E
  # Z.mro = [Z, K1, C, K3, A, K2, B, D, E]

https://en.wikipedia.org/wiki/C3_linearization

"In object-oriented systems with multiple inheritance,
some mechanism must be used for resolving conflicts when inheriting different definitions of the same property
from multiple superclasses." C3 superclass linearization is an algorithm used primarily to obtain the order in which methods should be inherited in the presence of multiple inherita...

versed eagle
#

so if you just want the result of adding them, that's probably the best for you

long fulcrum
#

oh shit that works?

#

i thought it would fuck with the floor

versed eagle
worldly trail
#

I saw something similar in this channel, few weeks ago:
Inspired me to do this:

def main() -> exec('import random;print(random.random())'): return "Hello"
print(main())
night quarryBOT
#

:white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | 0.2733108063088745
002 | None
worldly trail
#

!e

def main() -> exec('import random;print(random.random())'): return "Hello"
print(main())
night quarryBOT
versed eagle
#

whats your point

fleet bridge
night quarryBOT
worldly trail
versed eagle
#

im just curious which part of it is interesting to you

#

because i might be able to offer resources into further interesting things

worldly trail
versed eagle
#

have you looked at hooking __annotations__ to do silly things?

#

one of the simplest things you can do is just give it globals

#

!e ```py
annotations = globals()
test: "hello, world"
print(test)

night quarryBOT
versed eagle
#

but you can also give it any object with custom __setitem__ behaviour

worldly trail
versed eagle
#

have fun! and make sure you drink plenty of water, alcohol is dehydrating

worldly trail
#

back again.
This is nuts:

!e

asd = '''def main() -> print(__import__('random').random()): return "Hello"
\nprint(main())'''
zxc = [ord(x) for x in asd]
qwe = [chr(x) for x in zxc]
rr = "".join(qwe)
print(exec(str(rr)))
unique heath
#

in a way i hate

versed eagle
#

its quite lovely

#

i think

unique heath
#

esopy in a nutshell

fleet lintel
#

Also I just said "Method Order Resolution resolution" smhing my head

unique heath
#

tree mro when????

distant salmon
#

I have a challenge to you guys, try to list the 12 constants of Python listed under https://docs.python.org/3/library/constants.html.
Hint: the first two are False and True.
No cheating

subtle viper
#

||True, False, None, ..., "", (), 0, 1, math.e, math.pi, 1j, 0.0?||

#

oh-

distant salmon
#

Still 8 missing

gleaming linden
#

||__builtins__||?

subtle viper
#

there's actually only, like, 6

#

the rest are ||only in specific environments (i.e. the REPL)||

gleaming linden
#

does ||Ellipsis|| count separately?

unique heath
#

||__builtins__||

subtle viper
subtle viper
unique heath
unique heath
subtle viper
unique heath
#

uh this is hard

unique heath
subtle viper
#

also ||no ints||

unique heath
#

waitwaht

#

3:

#

oH

#

||None||

#

how did i not think of that

#

idk i give up

#

imma do math now

gleaming linden
#

does ||__file__|| count?

unique heath
#

(in math class lmfaoo)

subtle viper
#

||actually gonna go check agai nope||

distant salmon
gleaming linden
#

ok at least I got one

subtle viper
#

fun unrelated fact there are cached strings

#

just lile cached ints

gleaming linden
#

are the repl ones ||quit, exit, copyright, credits, license, help, _||?

subtle viper
gleaming linden
#

actually the last one shouldn't be a constant

#

yeah

#

||open|| then?

distant salmon
gleaming linden
#

hm ok

subtle viper
#

god i hate typing on phone-

gleaming linden
#

||interestingly they're all listed at the end of __builtins__.__dir__() in the repl||

subtle viper
#

why are they even there ||on the constants||

gleaming linden
#

idk it just does that

#

I gtg soon I'm gonna check the answers

#

OH ||NotImplemented|| is a constant?

#

til

#

||__debug__|| is also really sneaky

unique heath
#

imma check

#

oh i didnt know ||notimplemented|| was a const

#

i refuse to believe ||exit/quit|| are consts

subtle viper
gleaming linden
subtle viper
gleaming linden
#

||It triggers when you access the name at all||

subtle viper
gleaming linden
#

||hm, it's the repr?||

subtle viper
#

i'll check the source later

#

i guess.

gleaming linden
#

I thought it would be hardcoded somewhere, or it doesn't need to be a constant

night quarryBOT
#

Lib/_sitebuiltins.py lines 17 to 18

def __repr__(self):
    return 'Use %s() or %s to exit' % (self.name, self.eof)```
night quarryBOT
#

Lib/site.py lines 437 to 438

builtins.quit = _sitebuiltins.Quitter('quit', eof)
builtins.exit = _sitebuiltins.Quitter('exit', eof)```
unique heath
#

cursed

versed eagle
distant salmon
versed eagle
#

yeah

#

iirc there's 6 in each

#

so missing one from repl and one from the main ns

distant salmon
#

yes

versed eagle
#

but i dont know what they are lol

#

ill probably figure it out in a few minutes and then realise how silly i am for not remembering them

fleet bridge
#

||__debug__|| is from main ns

#

|| _ || from repl

distant salmon
versed eagle
#

|| _ || isnt a constant i dont think

fleet bridge
versed eagle
#

doesnt count as one

fleet bridge
#

ah, right, not a constant

versed eagle
#

because it swooshes around to the result of the previous thingy

#

yeah

earnest wing
#

my thoughts
||

True, False, None, ..., Ellipsis, NotImplemented, __debug__
# maybe the repl specific builtins / dunders?
# there was also a dunder constant that was specific to like 3.10 but it's probably not listed in the documentation

||

#

it was ||__peg_parser__||

flint hollow
#

it's not in 3.12 ๐Ÿ˜”

fleet bridge
#

it was in the last version that had peg parser

#

all versions after it use ll1 (is it called like that?) parser

#

LL1
LL(1)

flint hollow
#

i thought python switched from ll1 to peg

fleet bridge
#

hmmm

flint hollow
#

!pep 617

night quarryBOT
fleet bridge
#

I don't know, tbh
you might be correct

flint hollow
earnest wing
#

!e ```py
for i in 1,...,3:
print('looping :)')

night quarryBOT
karmic pumice
earnest wing
#

it goes straight into co_consts unfortunately

earnest snow
grave grail
#

It just happen to work (as far as I aware

#

!e ```py
for i in -1,...,30000:
print('looping :)')

night quarryBOT
grave grail
#

Ye, I'm not wrong

earnest snow
#

Oh, got scared for a moment

#

mb

somber raptor
#
def tobindec(x):
    w,b=int(x),'';f=x-w
    while f and len(b)<10:f*=2;b+=str(int(f));f-=int(f)
    return f"{bin(w)[2:]}.{b}"

print(tobindec(1.4))

theres no way to golf this code

fleet bridge
distant salmon
somber raptor
#

damn

#

DAMn

#

howww

karmic pumice
#
- f"{bin(w)[2:]}.{b}"
+ f"{w:b}.{b}"
earnest snow
#

also, to many int(x)s, make it a variable

def tobindec(x):
    i=int;w,b=i(x),'';f=x-w
    while f and len(b)<10:f*=2;b+=str(i(f));f-=i(f) # f-=i(f) is 4 chars, as f-=f//1
    return f"{w:b}.{b}"

print(tobindec(1.4))
somber raptor
#

brooo

earnest snow
#

since b grows linearly, you can substract len(b) by 10 and will have the same effect as len(b)<10

#

but with len(b)-10 since it's zero on len(b) = 10, you can multiply f instead of use an and

#
def tobindec1(x):
    i=int;w,b=i(x),'';f=x-w
    while f*(len(b)-10):f*=2;b+=str(i(f));f-=i(f)
    return f"{w:b}.{b}"

sitting at 122, test it just in case I'm wrong

somber raptor
#

124

#

!e
print(len("""def tobindec1(x):
i=int;w,b=i(x),'';f=x-w
while f*(len(b)-10):f*=2;b+=str(i(f));f-=i(f)
return f"{w:b}.{b}"
"""))

night quarryBOT
earnest snow
somber raptor
#

oh

earnest snow
#

!e

print(len("""def tobindec1(x):
    i=int;w,b=i(x),'';f=x-w
    while f*(len(b)-10):f*=2;b+=str(i(f));f-=i(f)
    return f\"{w:b}.{b}\""""))
night quarryBOT
earnest snow
#

tf 119

#

even better that what sublime text said

#

don't know how, I copy/pasted it

somber raptor
#
def tobindec1(x):
 i=int;w,b=i(x),'';f=x-w
 while f*(len(b)-10):f*=2;b+=str(i(f));f-=i(f)
 return f"{w:b}.{b}"

golfed it even more

#

just removed some spaces

#

would doing lambda remove char count

earnest snow
#

you just removed some identation

#

if you're gonna do that, put tabs, they're big enough their comfortable to look at and only 1 char

hybrid trail
#

does something like

bindec=lambda x:f'{int(x):b}.{int(x%1*2**10):010b}'.rstrip('0')
``` work
somber raptor
#

holy s***

#

wow

somber raptor
#

why does the og have more persicion

distant salmon
somber raptor
#

explain it

#

63

#

bro removed 44 from the og function

distant salmon
unique heath
subtle viper
hybrid trail
#

hint: there is one more byte that i can see be saved ๐Ÿ˜‰

distant salmon
hybrid trail
rapid temple
#

I pretty much stopped using inheritance thanks to __getattr__ and ducktyping

#

Literally my favorite thing ever

rugged sparrow
# earnest wing !e ```py for i in 1,...,3: print('looping :)') ```

!e ```py
from fishhook import hook, orig

@hook(tuple)
def iter(self):
for sz in range(3,6,2):
if len(self) == sz and all(isinstance(v,int) for v in self[::2]) and all(v==Ellipsis for v in self[1::2]):
yield from range(*self[::2])
return orig(self)

for i in 1,...,10,...,2:
print(i)```

night quarryBOT
rugged sparrow
#

@fleet bridge ^ can always hook tp_iter

#

!e ```py
from fishhook import hook, orig

@hook(tuple)
def iter(self):
for sz in range(3,6,2):
if len(self) == sz and all(isinstance(v,int) for v in self[::2]) and all(v==Ellipsis for v in self[1::2]):
yield from range(*self[::2])
return orig(self)

for i in 0,...,5:
print(i)```

night quarryBOT
fleet bridge
hybrid trail
#

challenge: how low of a number can you get the output of the following program

def score(s):
    if 'eval' in s or 'exec' in s:
        raise ValueError('No silliness')
    if eval(s) != eval(s) == eval(s):
        return len(s)
    else:
        raise ValueError('Invalid input')
    

print(score(input()))
#

sorry for editing im thinking of how to best patch some cheese

subtle viper
#

oh wait-

#

||(s,s:=0)||

hybrid trail
#

hmm, actually both don't work for me

#

seems like reassigning variables in an eval is not that simple

subtle viper
#

nvmnvm-

grave grail
#

||(s:=0 if "s" not in dir() else 1,)||

#

Oh wait

subtle viper
grave grail
#

||Change s to t or something like that||

#

||Did notice it was used to replace the variable, that variable should use in standalone||

subtle viper
#

||[t:='t'in dir()]||

#

-?

hybrid trail
#

yeah, that works

#

A sequel:

def safe_eval(s):
    return eval(s, {}, {})

def score(s):
    if 'eval' in s or 'exec' in s:
        raise ValueError('No silliness')
    
    if safe_eval(s) != safe_eval(s) == safe_eval(s):
        return len(s)
    else:
        raise ValueError('Invalid input')
    

print(score(input()))
restive void
unique heath
#

lol

karmic pumice
earnest wing
#

1, 0.5, 0.25, ...

restive void
#

1, 1, 2, 3, ...

wooden sail
#

Hello friends, please help me with the task

And the last practical task, a more complex format:
Parsing the Marvel website (https://www.marvel.com/characters) - collect the following information about Marvel heroes:
Hero name,
Link to the page with him,
Create a dataset and save it to a CSV file using Python methods.
Use DevTools to find out the names of tags.

Learn about your favorite Marvel characters, super heroes, & villains! Discover their powers, weaknesses, abilities, & more!

earnest wing
craggy hamlet
#

Hello friends, please help me with the task

And the last practical task, a more complex format:

graceful prism
zenith forum
versed eagle
night quarryBOT
fleet bridge
#

!e ```py
def score(s):
if 'eval' in s or 'exec' in s:
raise ValueError('No silliness')
if eval(s) != eval(s) == eval(s):
return len(s)
else:
raise ValueError('Invalid input')

inp="type('',(),dict(init=lambda*:import('gc').get_referents(str.dict)[0].setitem('len',lambda*:float('-inf')),eq=lambda*:True,ne=lambda*:True))()"

print(score(inp))
print('a'.len())

night quarryBOT
fleet bridge
#

I'm confused

#

need help
why doesn't it work?

#

!d sys

night quarryBOT
#
sys

This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It is always available.

fleet bridge
#

!e ```py
def score(s):
if 'eval' in s or 'exec' in s:
raise ValueError('No silliness')
if eval(s) != eval(s) == eval(s):
return len(s)
else:
raise ValueError('Invalid input')

inp="type('',(),dict(init=lambda*:[import('gc').get_referents(str.dict)[0].setitem('len',lambda*:float('-inf')),import('sys').clear_type_cache()][0],eq=lambda*:True,ne=lambda*_:True))()"

print(score(inp))

night quarryBOT
fleet bridge
#

fuck it

#

I will go enjoy cat pictures

versed eagle
#

that is not a cat

earnest wing
#

๐Ÿ˜ญ

worthy blade
worthy blade
#

Your're

#

righ

#

It's a lemon... How could I see it a cat

worthy blade
#

!e

import time
reminder=input("What do you want to be reminded of? ")
seconds=int(input("Seconds (0-60)"))
minutes=int(input("Minutes (0-60)"))
hours=int(input("Hours"))
if seconds>60:
    print("You have given more than 60 seconds. Restart the program")
    exit()

if minutes>60:
    print("You have given more than 60 minutes. Restart the program")
    exit()

if seconds==60:
    seconds=0
    minutes=minutes+1

if minutes==60:
    minutes=0
    hours=hours+1
    
minutes=minutes*60
hours=hours*60
hours=hours*60
total=hours+minutes+seconds

start=input("press enter to start your timer ")
print(reminder, "in", total, "seconds")

while total!=0:
    total=total-1
    print(total)
    time.sleep(1)

if total==0:
    print(reminder)
night quarryBOT
# worthy blade !e ```py import time reminder=input("What do you want to be reminded of? ") seco...

:x: Your 3.12 eval job has completed with return code 1.

:warning: Note: input is not supported by the bot :warning:

001 | What do you want to be reminded of? Traceback (most recent call last):
002 |   File "/home/main.py", line 2, in <module>
003 |     reminder=input("What do you want to be reminded of? ")
004 |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
005 | EOFError: EOF when reading a line
worthy blade
#

ey then

#

nvm

mild wren
mild wren
# worthy blade How?
reminder="my reminder"#input("What do you want to be reminded of? ")
seconds=123 #int(input("Seconds (0-60)"))
minutes=0#int(input("Minutes (0-60)"))
hours=0#int(input("Hours"))

#

the bot will most likely time out though at some point

#

Also, this isn't really esoteric ๐Ÿ˜„

rugged sparrow
# fleet bridge I'm confused

len is handled by a slot method, so just modifying the dict isn't enough. Hook it with fishhook or similar code and that would work

fleet bridge
#

yeah I get it

#

but why clearing type cache didn't help?

#

what is this cache for? what does it contain

#

I have memories that clearing it helped with modifying builtins

rugged sparrow
#

I think it just clears the dict cache

#

Not the slot functions

rugged sparrow
#

At least for the native types

somber raptor
#
p=lambda n:n>1 and all(n%i for i in range(2,int(n**.5)+1))
print([x for x in range(2,int(input())+1)if p(x)])

try to make the code smalelr

fleet bridge
#

!e print({*{}})

night quarryBOT
fleet bridge
#

lmao

#

another empty set literal

sage lintel
quartz wave
# sage lintel what makes it a "literal"?
# literal
[] ; [a, b, ...]  # list
() ; (a, b, ...)  # tuple
{} ; {k0: v0, k1: v1, ...: ...}  # dict
{*()} ; {a, b, ...}  # set
"" ; "..."  # string
r"" ; r"..."  # r-string
b"" ; b"..."  # bytes
f"" ; f"a{b}c..."  # f-string
# and all the other string literal combinations...
...  # like literally just `...`
0 ; 1 ; ...  # int
0. ; 1.5123 ; ...  # float
1j ; ...  # complex
# constant
None
True
False
NotImplemented
__debug__
... ; Ellipsis
0 ; 1 ; ...
0. ; 1. ; 0.12 ; ...
0j ; 1.5j ; ...
() ; (1, 2, ...)
"" ; "..."
r"" ; r"..."
b"" ; b"..."
sage lintel
#

ok hmm

#

just to see if i understand

quartz wave
#

literals have dedicated syntax

sage lintel
#

is something like {*{*{*{*{*{*{}}}}}}} a literal?

quartz wave
#

you could technically say that, yup

sage lintel
#

i think i'm following

#

func(3) is not

#

3 + 3 is (wait maybe not because of the +?)

quartz wave
#

well it's 2 integer literals with an operation

sage lintel
#

in func(*args), *args is a literal i guess

#

just testing myself lol

quartz wave
#

*args is unpacking a variable args

sage lintel
#

hm

quartz wave
#

the empty set "literal" is just using the literal of the set with an unpacking of another empty literal to make an empty set

sage lintel
#

what about [*args], and that vs [*[]] and [1, 2, c]

sage lintel
quartz wave
#

well it's contained within a dedicated syntax, so yes

quartz wave
sage lintel
#

and it's ok to have variables in a literal? like [1, 2, b]

quartz wave
#

yup

sage lintel
#

ok

#

then *args can be one too, i think :p

#

i'm not sure

#

maybe not here

#

i get your point

quartz wave
#

it can be used inside of a literal but it's not a literal itself

sage lintel
#

ok that's true

#

[*args] is but *args not really

quartz wave
#

mhm ^^

sage lintel
#

interestingg

#

thanks

quartz wave
#

the definitions may differ for each language or person you ask but that's how i define it

sage lintel
#

ok that's good to know too, thank you

#

your definitions seem consistent though

quartz wave
#

i've looked it up on SO and someone defines a literal as "something that represents itself" which i think is a pretty good way to term it

sage lintel
#

but yeah it does get the idea across

fleet bridge
#

alternative definition: literal is an expression that evaluates to the same thing no matter what (assuming no weird stuff happened)

# literals:
0
[]
(1,2)
{*()}
1+2
[1]+[2,3]
[0][0]

# not literals:
len('abc') # relies on len var not being shadowed
x
[x, y]
x + 1
#

I'm sure you can come up with weird examples that will prove this definition to be not very good

sage lintel
#

your definition is also interesting regardless

fleet bridge
fleet bridge
sage lintel
#

!e print([1, 2] is [1, 2])

night quarryBOT
fleet bridge
sage lintel
#

!e print((1, 2) is (1, 2))

night quarryBOT
# sage lintel !e print((1, 2) is (1, 2))

:white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | /home/main.py:1: SyntaxWarning: "is" with 'tuple' literal. Did you mean "=="?
002 |   print((1, 2) is (1, 2))
003 | True
sage lintel
#

whoa

#

i didn't know that

fleet bridge
#

compiler is smart and noticed a duplicate constant
so it reused the same constant in two places
same happens with string literals, for example

sage lintel
#

that's very cool

#

that does make sense too, strings are similar

#

!e print((1,) + (2,) is (1, 2))

night quarryBOT
# sage lintel !e print((1,) + (2,) is (1, 2))

:white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | /home/main.py:1: SyntaxWarning: "is" with 'tuple' literal. Did you mean "=="?
002 |   print((1,) + (2,) is (1, 2))
003 | True
fleet bridge
#

compiler also can perform some operations on constants at compile time, as you can see from your snippet

sage lintel
#

!e print({*{*{*{*{*{*{}}}}}}} is set())

night quarryBOT
fleet bridge
#

it is not smart enough to do that

sage lintel
#

hm makes sense

fleet bridge
#

try dis('x in {1,2}')
you will see that instead of creating new set each time, only one frozenset is created and reused

sage lintel
#

!e print({*()} is set())

night quarryBOT
fleet bridge
#

set() must produce new set each time

sage lintel
#

!e print(dis('x in {1,2}'))

night quarryBOT
# sage lintel !e `print(dis('x in {1,2}'))`

: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 |     print(dis('x in {1,2}'))
004 |           ^^^
005 | NameError: name 'dis' is not defined. Did you mean: 'dir'? Or did you forget to import 'dis'?
sage lintel
#

sorry i haven't actually used dis before ๐Ÿชฆ

gleaming linden
#

you need from dis import dis

sage lintel
#

!e print(set() is set())

night quarryBOT
quartz wave
sage lintel
#

sorry if i'm doing too many bot calls

fleet bridge
quartz wave
#

yup

sage lintel
#

!e

from dis import dis
print(dis('x in {1,2}'))
night quarryBOT
quartz wave
#

now if it creates the exact same object in the entirety of the program it's a constant

sage lintel
quartz wave
#

that's my definition

fleet bridge
quartz wave
#

but python doesn't optimize that out

#

yeah hold on i'm gonna fix my terms a bit

#

literal has dedicated syntax that, under normal circumstances, evaluates to pretty much the same thing in every runtime

#

constants are those that are the exact same object in the entirety of the program

#

and constant literals are those like (), (1, 2), 5, 7j, etc.

#

now drawing the line on "dedicated syntax" are operations applied on a literal

#

but not in the literal

fleet bridge
#

is [x,y] a literal?

quartz wave
fleet bridge
#

then it is not very clear what "to pretty much the same thing" means exactly
it can produce different values depending on x and y

quartz wave
#

non-literals are considered constant in "pretty much the same thing"

#

that sounds like a circular definition for some reason

#

[x, y] is a literal for me because it uses the [] syntax for lists

#

x[1::5] is a variable x being subscripted with a slice literal

fleet bridge
quartz wave
#

that's a better way to term it, yes

quartz wave
fleet bridge
#

is print('foo') a constant? it evaluates to None pretty much always

quartz wave
#

well not if print is redefined

fleet bridge
#

then replace print with some weird reliable way of getting it, and ask the question again

quartz wave
#

getting "it"?

fleet bridge
#

__builtins__['print']('foo') or something like that
I assume that nobody is touching built-in namespace

#

is __import__('os')._exit(0) a constant? ๐Ÿค”

quartz wave
#

any variable to me is by default a non-constant

#

and anything obtained from a constant is technically a constant

#

so that's why ().__class__.__base__ is a constant

#

but print('foo') i have a hard time defining

fleet bridge
#

so constant expression also must use only constant expressions as parts of it
by that logic [].__len__() is not a constant, because it uses non-constant as a part of it

quartz wave
#

under normal circumstances that's a constant

#

print('foo') is also a "constant" under normal circumstances but it does something else other than return a value

#

it's like an undefined error happening in my brain when function calls are involved T^T

fleet bridge
#

(0 for x in []).gi_frame.f_globals['__builtins__']['print']('foo')

quartz wave
#

constant UNC

#

it's like the halting problem now

#

"determine whether or not this line will do the same thing for the entirety of the program"

fleet bridge
#

is (a thing that returns 1 if Riemann hypothesis is true otherwise returns random number) a constant