#esoteric-python

1 messages · Page 68 of 1

sick hound
#

so you are checking the sum of the binary expansion of the number

gilded orchid
#

oh right

#

is there a way I can fix that without duplicating sum(map(int,bin(i)[2:]))?

sick hound
#

it looks like the shortest way to fix it is to use py [j%a!=0for j in[sum(map(int,bin(i)[2:]))]for a in range(2,j)]

#

@gilded orchid

gilded orchid
#

even if I duplicate it over into that range (or copy your thing) it just outputs the numbers 1-50

sick hound
#

(you can also remove the !=0 there)

#

does it output all of them?

gilded orchid
#

#bot-commands

#

yeah it does

sick hound
#

it doesn't

#

it doesn't output 43

#

or 45

#

or 15

gilded orchid
#

oh

#

it still isn't right

sick hound
#

1 isn't prime

gilded orchid
#
3 5 6 7 9 10 11 12 13 14 17 18 19 20 21 22 24 25 26 28 31 33 34 35 36 37 38 40 41 42 44 47 48 49 50

it should be this

sick hound
#

your prime-checking code thinks that 1 is prime

gilded orchid
#

I can just adjust the first range to ignore that, cos 1 isn't a pernicious number anyware

sick hound
#

all of the powers of two are not pernicious

#

but your code says they are

gilded orchid
#

weird

#

earlier it was just printing the powers of two 🤔

sick hound
#

the powers of two have exactly one 1 in them

#

(in binary)

#

so they are pernicious iff 1 is prime

#

but 1 isn't prime

gilded orchid
#

I can just put if j!=1 at the end to counter that

humble tartan
#
print(*(x for x in range(50)if 1^all(sum(map(int,bin(x)[2:]))%i for i in range(2,x))))

is the best i could do

#

i hate that i can't use something clean like reduce

sick hound
#
[print(i)for i in range(1,51)if all([j%a for j in[sum(map(int,bin(i)[2:]))]for a in range(2,j)])and~-bin(i).count('1')]```
gilded orchid
#

now that I think about it, can you use bin(x).count('1') instead of sum(map(int,bin(x)[2:]))

sick hound
#

...yes

gilded orchid
#

wow I overcomplicated that

marsh void
#

hm, you need primes?

gilded orchid
#

we're doing all the pernicious numbers from 0 to 50 ('A pernicious number is a positive number where the sum of its binary expansion is a prime number.')

sick hound
#
[print(i)for i in range(1,51)for j in[bin(i).count('1')]if all([j%a for a in range(2,j)])and~-j]```
gilded orchid
humble tartan
#
print(*(i for i in range(1,51) if 1^all(bin(i).count('1')%a for a in range(1,i))))

shorter

sick hound
#

43 is not a pernicious number

#

that doesn't work

humble tartan
#

fuck

gilded orchid
#

(also each one needs to be on a new line)

humble tartan
#

does it have to be a single line? (the golf)

gilded orchid
#

nope

wind maple
brisk zenith
#

i can get 57 hmm

gilded orchid
marsh void
#

so huh

#

y'all challenging here 👌

sick hound
#

that quine is actually kind of easy to do if you know how to do it

#

@gilded orchid ' "yields falsehood when preceded by its quotation" yields falsehood when preceded by its quotation.' - Williard Van Orman Quine

gilded orchid
marsh void
#

I guess time to apply for the V'th code jam lol

gilded orchid
#

I would apply but I suck at python

marsh void
#

Hmm

sick hound
#

I would but I'm not sure if I should since it's (as always) right in the middle of exam block

#

or not exam block but the period with all my assignments due

gilded orchid
#

Is there a short way to remove 1 character from the end of string? (for a code golf)

sick hound
#

[:-1]

#

@gilded orchid

gilded orchid
#

oh wow I'm dumb

#

thanks

marsh void
#

I’ve thought about a challenge to write some kind of program with only two variables

gilded orchid
#

couldn't you just make those variables lists, and store in your variables in those though?

brisk zenith
#

even better, just make your own globals dict

#

¯_(ツ)_/¯

marsh void
#

lit

#

@gilded orchid I mean no without that things

#

What might be the point of appending list to itself?

gilded orchid
#

nested lists are actually really useful for some things

#

for example, I used one in my minesweeper a while ago, with a list that had 10 more lists inside it

brisk zenith
#

nested lists aren't the same as appending a list to itself

#

!e ```py
thing = [1, 2, 3]
thing.append(thing)
print(thing)

night quarryBOT
#

@brisk zenith Your eval job has completed.

[1, 2, 3, [...]]
gilded orchid
#

oh nvm lol

brisk zenith
#

as for appending a list to itself, i haven't yet found a practical application for it.

marsh void
#

Really, what is the reason?

#

!e
thing = [1, 2, 3]
thing.append(thing)
for _ in range(100):
thing = thing[3]
print(thing)

night quarryBOT
#
Noooooo!!

Sorry, but you may only use this command within #bot-commands.

marsh void
#

Eww ok

#

It’ll return the same as the thing was

#

So really, what can it be used for?

marsh void
#

Code Jam V code - 31 lines, excluding docstring thinkmon

#

maybe I should make a one-liner LOL

stone apex
marsh void
#

LOL

#

real python tbh

cunning wave
#

interestingly enough computers in general seem to struggle with roots

#

if you do ^(1/3) instead of cube root in wolframalpha it will also struggle to solve some equations

marsh void
#

print(str().join(list(map(chr, [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])))) who can make Hello World even more weird?

shut wadi
#
import string
print(string.ascii_uppercase[7])
print(string.ascii_lowercase[4])
print(string.ascii_lowercase[11])
print(string.ascii_lowercase[11])
print(string.ascii_lowercase[14])```
marsh void
#

Too long lol

honest lotus
#

There was a one in the pins if i remember correctly

marsh void
#
from string import ascii_letters as a; b = a + "! "; print(str().join(b[_] for _ in [33,4,11,11,14,53,48,14,17,11,3,52]))

@shut wadi improved yours I guess

shut wadi
#
from string import ascii_letters as a

def helloWorld():
    b = a + "! "
    return str().join(b[_] for _ in [33,4,11,11,14,53,48,14,17,11,3,52])

print(helloWorld())```
marsh void
#

Too long

tepid glacier
#

import __hello__ :^)

marsh void
#

Wait what

#

Mfw why this exists

#

@tepid glacier we need more weird stuff lol

fallen heath
#

from __future__ import braces

nocturne saddle
#

The version in the pins is for 2.7, but there's a great Python 3 version of that obfuscated hello world as well

#

!e

(lambda _, __, ___, ____, _____, ______, _______, ________:
    getattr(
        __import__(True.__class__.__name__[_] + [].__class__.__name__[__]),
        ().__class__.__eq__.__class__.__name__[:__] +
        ().__iter__().__class__.__name__[_:][_____:________]
    )(
        _, (lambda _, __, ___: _(_, __, ___))(
            lambda _, __, ___:
                bytes([___ % __]) + _(_, __, ___ // __) if ___ else
                (lambda: _).__code__.co_lnotab,
            _ << ________,
            (((_____ << ____) + _) << ((___ << _____) - ___)) + (((((___ << __)
            - _) << ___) + _) << ((_____ << ____) + (_ << _))) + (((_______ <<
            __) - _) << (((((_ << ___) + _)) << ___) + (_ << _))) + (((_______
            << ___) + _) << ((_ << ______) + _)) + (((_______ << ____) - _) <<
            ((_______ << ___))) + (((_ << ____) - _) << ((((___ << __) + _) <<
            __) - _)) - (_______ << ((((___ << __) - _) << __) + _)) + (_______
            << (((((_ << ___) + _)) << __))) - ((((((_ << ___) + _)) << __) +
            _) << ((((___ << __) + _) << _))) + (((_______ << __) - _) <<
            (((((_ << ___) + _)) << _))) + (((___ << ___) + _) << ((_____ <<
            _))) + (_____ << ______) + (_ << ___)
        )
    )
)(
    *(lambda _, __, ___: _(_, __, ___))(
        (lambda _, __, ___:
            [__(___[(lambda: _).__code__.co_nlocals])] +
            _(_, __, ___[(lambda _: _).__code__.co_nlocals:]) if ___ else []
        ),
        lambda _: _.__code__.co_argcount,
        (
            lambda _: _,
            lambda _, __: _,
            lambda _, __, ___: _,
            lambda _, __, ___, ____: _,
            lambda _, __, ___, ____, _____: _,
            lambda _, __, ___, ____, _____, ______: _,
            lambda _, __, ___, ____, _____, ______, _______: _,
            lambda _, __, ___, ____, _____, ______, _______, ________: _
        )
    )
)
night quarryBOT
#

@nocturne saddle Your eval job has completed.

Hello world!
marsh void
#

What the hell LOL

gilded orchid
#

Judging from the import, is that an obfuscated import of hello?

marsh void
#

Lol

gilded orchid
#

wow discord formatting is annoying

marsh void
#

yes

#

oops

#

eval("print('Hello World!')")

gilded orchid
#

To avoid discord formatting, is that an obfuscated version of __import__(‘__hello__’)?

marsh void
#

<module '__hello__' (frozen)>

#

well, yeah, it’s ok

nocturne saddle
#

Hmm

#

I don't know, but it's repeatable and an import should only be executed once

#

No, it's using another method

fallen heath
#

So it's importing os

shut wadi
#

@nocturne saddle are you satan

nocturne saddle
#

It's not my code

#

The blogpost explaining it is actually quite interesting

marsh void
#

Well, makes me feel I need to learn python more

#

Actually, I’ll try to make my own one of this kind, but shorter

gilded orchid
#
>>> getattr(__import__('random'),'randint')(1,10)
5

never knew you could do getattr on an import

sick hound
#

why could you not "do getattr on an import"

#

that's like saying "never knew you could call a variable"

gilded orchid
#

idk I just never thought about doing that

sick hound
#

also you can call a variable

#
f = print
f('hello')```
gilded orchid
#
import inspect

a = lambda x:print('x')
print(inspect.getsource(a))

this outputs a = lambda x:print('x')

#

couldn't this be used for a quine?

#

oh wow it can

#
a=lambda x:x;print(__import__('inspect').getsource(a))

outputs itself

viral bough
#

doesnt work locally for me

#
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.5/inspect.py", line 944, in getsource
    lines, lnum = getsourcelines(object)
  File "/usr/lib/python3.5/inspect.py", line 931, in getsourcelines
    lines, lnum = findsource(object)
  File "/usr/lib/python3.5/inspect.py", line 762, in findsource
    raise OSError('could not get source code')
OSError: could not get source code
gilded orchid
#

has to be in a file, doesn't work in interactive shell

viral bough
#

that was very smart of me

#

yes it does work in a file

grave rover
#

@gilded orchid doesnt count as quine since it uses file i/o

gilded orchid
#

oh rip

glacial rampart
#

expanding_brain1 self.meth(x)
expanding_brain2 type(self).meth(self, x)
expanding_brain3 type(self).meth.__get__(self, type(self))(x)
expanding_brain4 type(self.meth)(type(self).meth, self)(x)

fresh osprey
#

def(((((((((Function))))))))))))

onyx jacinth
last locust
#

@onyx jacinth there’s an answer in #bot-commands I just did but not very esoteric

onyx jacinth
#

thx for help but it is really not very esoteric

last locust
#

That gives you somewhere to start at least

onyx jacinth
#

yes

vocal oyster
#

shucks my first solution is 75 74

onyx jacinth
#

i will come back to this tomorrow

gilded orchid
#

You can change if not x%y to if x%y==0 to save a character

#

Also you can remove the space before the if at the end

#

And the space before the first for

#

@onyx jacinth

#

Also can also do range(1,i) for the last range

calm rampart
#

if~(x%y)

#

wait no

#

if(x%y-1)
if x%y==0

#

oh well it was a thought

#

x can probably just be range(101) @onyx jacinth

#

wait, no

#

it says print them, how are you printing them

#
for x in range(1,101):print(*[y for y in range(1,101)if x%y==0])```
#

@gilded orchid what would i be? if it's x, the output won't include x itself, which is unclear in the spec but different from what the code is currently doing.

gilded orchid
#

Oh oops

calm rampart
#

wait

#

hmm no

gilded orchid
#

just tried it and got 59 chars

gilded orchid
#

Idea for a challenge: could we have a second version of the esolang challenge, with a restriction on the syntax of the esolang?

marsh void
#

hm

sick hound
#

only use list comprehensions

night quarryBOT
#
Not gonna happen.

Sorry, but you may only use this command within #bot-commands.

young mantle
#

is this a valid way to do if/elif in one line to imitate a ternary by exploiting short circuiting:

((not <condition1>) or (<execute1> or True)) and ((not <condition2>) or (<execute2> or True)) and ((not <condition3>) or (<execute3> or True)) and ...
#

ie would it be equivalent to

if <condition1>:
    <execute1>
elif <condition2>:
    <execute2>
elif <condition3>:
    <execute3>
...
#

and how would i implement an else condition

honest lotus
#

why not just use ternary?

young mantle
#

ternary doesnt do elif does it

honest lotus
#

I mean, you could chain them if you want

#

True if condition else (True if othercondition else (...)) or something

#

just replace the True/False with whatever

#

just seems way more readable then chaining al those short circuits, less typing too

gilded orchid
snow beacon
#

This is a cute way to do infinite loops: python while ...: do_something()

sick hound
#

@gilded orchid not really but it's also shorter

#

I think

honest lotus
#

Yeah

#

forgot to mention that

sick hound
#

well you said "less typing too"

honest lotus
#

oh, I did

marsh void
#

@snow beacon cute but not the shortest.

while 1:
    do_something()
snow beacon
#

True, but 1 doesn't symbolise continuing

#

No pun intended.

marsh void
#

yes

#

@snow beacon but real infinity is:
a=[];a.append(a);print(a)

sick hound
#
>>> a=[];a.append(a);print(a)
[[...]]```
gilded orchid
#
>>> ...
Ellipsis

What does ... actually do?

brisk zenith
#

not much on its own, it's just a singleton like None and the booleans. it's used often in numpy though.

gilded orchid
#

oh ok

#

also are ... and Ellipsis the same thing?

brisk zenith
#

yup

gilded orchid
#

oh ok

#

thanks

marsh void
#

Ellipsis is used in slicing if I remember

#

though [[...]] means infinite stuff

honest lotus
#

so it just recieves everything? or just gives you an error?

marsh void
#
a = []; a.append(a)
for i in range(1000):
    a = a[0]
print(a)
>>> [[...]]
#

It is just a in a, so each a in a also contains a

#

If that makes sense

sick hound
#

in the representation of lists, [...] represents a copy of the entire list

#
>>> a = []
>>> a.append(1)
>>> a.append(a)
>>> a.append(2)
>>> a
[1, [...], 2]```
marsh void
#

yeah, yeah

sick hound
#

that 1st (from 0) element, [...], represents a

marsh void
#

but this thing is pretty much a, which contains a and so on

sick hound
#

yes, a is the entire list

#

but so is the 1st element of a

marsh void
#

yeah

#

@sick hound but what can be the point of having a in a? Like, if you edit a, a in it will also change

gilded orchid
#

So ... is a reference to Ellipsis, and Ellipsis can be assigned, whilst ... can't

sick hound
#

yes

#
>>> ... is Ellipsis
True```
gilded orchid
#
>>> Ellipsis = 42
>>> ... is Ellipsis
False

wouldn't ... be 42 if it's a reference?

marsh void
#

Hm

sick hound
#

... isn't a reference to Ellipsis

#

... is a reference to an internally stored ellipsis object

#

Ellipsis is also a reference to that object

marsh void
#

^

gilded orchid
#

How come ... can't be assigned then?

#

if they're both pointing to the same object

sick hound
#

because syntax

#

actually

#

... is a LOAD_CONST

#

it's like 5

#
x = 5```
#

you can assign x

#

but you can't assign 5

#

how come 5 can't be assigned then? if they're both pointing to the same object

#
>>> __builtins__.Ellipsis
Ellipsis```
#

Ellipsis is just in __builtins__

#

like print

#
>>> print = 42
>>> print
42```
marsh void
#

You can assign print as a variable and so it won’t work

#

Yeah, I was slower grumpy

sick hound
#

you actually can reassign ... if you use ctypes

#
>>> ...
None```
#

but it's not None ```py

... is None
False```

#

you can even flip it around and turn None into Ellipsis ```py

print(None)
Ellipsis```

#

ctypes is fun

gilded orchid
#

I just realised you could probably use memmove and memset to make your programme ridiculously obfuscated

brisk zenith
#

and ridiculously unstable

#

but yes, entirely possible

sick hound
#
>>> _.value
KeyError: 'unknown symbol table entry'```
#

that might be the most bizarre error I've ever seen

marsh void
#
>>> 7<<(7<<60)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
MemoryError
>>> 9<<(9<<99)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
OverflowError: too many digits in integer

🤔

#

Why is the last one causing OverflowError and not MemoryError?

sick hound
#
>>> 9<<(9<<99)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C ssize_t```
#

the number is too large to get converted to a normal C number

marsh void
#

So 7<<(7<<60) can be converted but it needs too much memory? @sick hound

sick hound
#

7<<60 can be converted into a C number

#

but it's still ridiculously large ```py

7<<60
8070450532247928832```

#

@marsh void 7<<60 can be converted to a C integer, 7<<(7<<60) is far bigger than the number of atoms in the universe

#

the biggest number that you can put in a C ssize_t is 9223372036854775807

#
>>> 2<<9223372036854775807
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
MemoryError
>>> 2<<9223372036854775808
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C ssize_t```
#

9<<99 is 5704427701027032306735164424192, which is too big. python can't even start doing 9<<5704427701027032306735164424192

#

but it can try 7<<8070450532247928832, it just runs out of memory before it can finish

marsh void
#

Okay gotcha, thanks for explaining

tropic gulch
#

huh, but internally Python can handle much larger ints than 9223372036854775807. Is this only because of the << bitshift operator which is probably implemented in C?

gilded orchid
#

yeah, python can literally handle 2**90000

brisk zenith
#

@tropic gulch python's long types are essentially stored as arrays of C integers. when the size of this array of integers becomes larger than can be represented by the Py_ssize_t which stores the length of this array, that becomes a problem.

tropic gulch
#

ah, cool

brisk zenith
#

so it's not that 9223372036854775808 is too big for python integers, it's that the size of the array of integers needed to represent 2 << 9223372036854775808 is too big.

#

that's what i imagine it is, at least.

sick hound
#

...Oh

#

that makes sense

#

...except for the fact that it's wrong ```py

4<<9223372036854775807
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
MemoryError
2<<9223372036854775808
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C ssize_t```

#
>>> 1024<<9223372036854775807
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
MemoryError
>>> 1024<<9223372036854775808
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C ssize_t```
#

@brisk zenith

#

i'm guessing it's just << trying to put the second number into an ssize_t

brisk zenith
#

hmm fair.

unique kettle
#

so like... i haven't been able to write this in a version of python < 3.8 yet...

#
fn = lambda: (a := lambda: a)```
#
Out[43]: False```
#

it's making new lambdas every time you call it

#

verified by poking at them with hash()

thorny granite
#

what about x = fn(); x()()() is x()()()

sick hound
#
>>> fn=(lambda x:x(x))(lambda x:lambda:x(x))```
#

@unique kettle

#

works in any python version with lambda, and it makes a new lambda every call

#

also LOL ```py

0<<9223372036854775807
0
0<<9223372036854775808
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C ssize_t```

unique kettle
#

@sick hound i finally got that syntax into something readable... ```python
def a(x):
return x(x)

def b(x):
def c():
return x(x)
return c

fn = a(b)

#

but yeah it does behave as claimed

desert garden
#

Wait, := was approved for 3.8?

#

Honestly it would make more sense to just make = an expression

#

And a=b=1 becomes a=(b=1) internally

unique kettle
#

yeah it was

sick hound
#

a=b=1 already works?

honest lotus
#

yeah, it make a = 1 and b = 1

#

wait am I missing some context?

brazen geyser
#

@desert garden thats not how chained assignments work in cpython, at least not yet

#
>>> dis.dis('a = b = c = d = 1')
  1           0 LOAD_CONST               0 (1)
              2 DUP_TOP
              4 STORE_NAME               0 (a)
              6 DUP_TOP
              8 STORE_NAME               1 (b)
             10 DUP_TOP
             12 STORE_NAME               2 (c)
             14 STORE_NAME               3 (d)
             16 LOAD_CONST               1 (None)
             18 RETURN_VALUE
>>> 
#

which causes issues when you try to do stuff like this:

>>> k = {}
>>> original_k = k
>>> k = k['test'] = [1,2,3]
Traceback (most recent call last):
  File "<pyshell#92>", line 1, in <module>
    k = k['test'] = [1,2,3]
TypeError: list indices must be integers or slices, not str
>>> k
[1, 2, 3]
>>> original_k
{}
>>> 
#

basically assignment has no conventional kind of associativity

desert garden
#

Yeah I know how the currently work

#

But a = (b = 1) would be a nicer way to do it

#

And would also mean you didn't need to add :=

#

Because unless I'm mistaken, we could a := (b := 1) and just replace every single occurance of = with := and nothing would change

brazen geyser
#

nah, can't do stuff like a[thing] := thing

#

no subscripts allowed it seems

#

oh, and you cant use it with attributes either

#
>>> ((a, b) := (1, 2))
SyntaxError: cannot use named assignment with tuple
>>> 
#

lol

sick hound
#

@desert garden the pep states that's sorta a side effect of the syntax

#

It's not supposed to be used that way

#

It's for setting the values in for loops /similar expressions

#

Unless I'm not getting what your meaning in the way it's meant to be used?

#

Also that

desert garden
#

I know what it's meant to do, but I just feel it'd be simpler, and kill two birds with one stone, to just make a=b an expression that evaluates to b

sick hound
#

Maybe

snow beacon
#

Lots of programming languages do it like that.

#

(I can't name any, but I'm confident they exist.)

wind maple
#

C

livid seal
#

the side effect of doing that would be that if a = b: ... would become valid, when it's definitely a mistake people make now. that seems bad.

wind maple
#

yes

#

one of the reasons they decided to not turn the current assignment into an expression

frank hazel
#

golfers everywhere probably wish it was = and not := too

tropic gulch
#

damn that extra byte! 😂

grave rover
#

@unique kettle what's that syntax

unique kettle
#

@grave rover the thing posted just before me: fn=(lambda x:x(x))(lambda x:lambda:x(x))

grave rover
#

Wew

#

TIL AEs were accepted

night quarryBOT
#
No way, José.

Sorry, but you may only use this command within #bot-commands.

frank hazel
#

@grave rover ya just before Guido retired

#

the AE fight was part of why

grave rover
#

oof

#

rip Guido

nocturne saddle
#

It wasn't so much AE in itself, but the stress that came from the social media debates surrounding it

supple flume
#

What're AEs?

tepid glacier
#

Assignment Expressions

supple flume
#

Ooh walrus?

tepid glacier
#

!pep 572

night quarryBOT
#
**PEP 572 - Assignment Expressions**
Status

Accepted

Python-Version

3.8

Created

28-Feb-2018

Type

Standards Track

tepid glacier
#

yep

supple flume
#

Thanks!

night quarryBOT
#
Nuh-uh.

Sorry, but you may only use this command within #bot-commands.

stray needleBOT
stray needleBOT
brisk zenith
#

challenge 09 has arrived: lolcat!

to stick with the ongoing pride event this month, we have a rainbow-themed challenge for you today! this time, you will be recreating lolcat, a simple little program that some of you may know already. don't worry if you don't though, further details and an example can be found on the repo as always :D the task will be focused on golfing, but other interesting solutions are encouraged as well.
https://github.com/python-discord/esoteric-python-challenges/tree/master/challenges/09-lolcat

#

hopefully we'll get some submissions this time round. :D

marsh void
#

@brisk zenith so our task is to write code that makes the output rainbow-colored?

grave rover
#

oh shit I had code for this

brisk zenith
#

the task is to print the contents of a file but make it rainbow in the process

grave rover
#

but it's on my friend's SSD

tropic gulch
#

most of these agonizing 290 bytes are hsv2rgb conversion, though I could probably simplify that a lot if I modify the formula to assume constant s and v (which I do right now anyway)

marsh void
#

Okay printing contents of a file or text (which is kinda pre-defined I’d say) would be not too hard imo

#

I need to remember how coloring in the terminal works since I am less used to linux because haven’t used it for a long time

wind maple
scarlet osprey
#

Ava is an Xpert ablobsunglasses

wind maple
#

If instead of 8+8 colours you want to use 256-colour pallette you can use CSI 38;5;#COLOUR m

#

Yes I spent roughly twenty hours creating stupid applications abusing ANSI escape sequences

#

very expert

#

The 256-colour pallette uses the formula 16 + 36 * r + 6 * g + b

#

e.g. \33[38;5;248m

#

You can also use true RGB by doing CSI 38;2;(r);(g);(b) m

#

where each value r, g, b is in the range [0, 255]

scarlet osprey
#

Make a lib for it

wind maple
#

So you basically have 3 options

#

8+8, 256 and true colour

#

True RGB support might be scarce though

#

I googled around it looks like most modern terminal emulators support true colour

tropic gulch
#

even managed to hit a nice and fitting fortune as showcase 😄

brisk zenith
#

ooh spicy

sick hound
#

sl | lolcat --seed 1 -a

marsh void
#

@tropic gulch really cool! though, really long lines look quite weird tho(in output)

tropic gulch
#

Well yeah, it does not determine your terminal width to insert additional line breaks for wrapping, and to adjust colors based on that

#

But that would be waaay out of scope, I think

#

lolcat doesn't do that either

#

You could pipe your input through fold -w $COLUMNS first to wrap lines around at the width of your terminal before coloring

marsh void
#

Yeah

brisk zenith
#

@tropic gulch is your solution already good for merging, or are you still working on it?

tropic gulch
#

I'm done.

#

Could have added support for concatenating multiple input files, but... meh

#

maybe some other time.

brisk zenith
#

i'll merge it in now then. if you want to go back and make any changes, just open a new PR :D

tropic gulch
frank hazel
#

so that's truecolor?

#

I expect, then, that...

tropic gulch
#

24 bit colors

#

although raincat only ever uses 360 different shades at most

frank hazel
#

360?

#

that's an odd number

tropic gulch
#

probably less, didn't examine the converted numbers

brisk zenith
#

no it's not

tropic gulch
#

Hue is measured in degrees

brisk zenith
#

360 degrees in a circle

#

actually i'd prefer if you used 2π colours, disappointing :^)

tropic gulch
#

😛

frank hazel
#

not using radians

tropic gulch
#

don't you mean one Tau?

frank hazel
#

yup as expected doesn't work on my system

#

or, wait

#

ye

tropic gulch
#

it needs a terminal capable of interpreting ANSI escapes and supporting 24bit color

#

i.e. not cmd.exe

brisk zenith
#

can confirm it works in my terminal (termite)

frank hazel
#

@tropic gulch e.x. not i.e.

#

and I'm on Linux

tropic gulch
frank hazel
#

but my terminal emulator doesn't have truecolor

#

so it doesn't work

#

sorry

#

e.g.

#

lol

tropic gulch
#

which do you use?

brisk zenith
#

i.e. would be the correct one

frank hazel
#

urxvt

#

really? why?

tropic gulch
#

gnome-terminal and xterm work

frank hazel
#

I always thought i.e. is for if you're giving every example

brisk zenith
#

i.e. basically means in other words

frank hazel
#

and e.g. is for if you're giving some

#

cmd.exe is not the only terminal that doesn't have truecolor

#

I don't think xterm has truecolor

#

it pretends it does but converts to 256color

tropic gulch
frank hazel
#

ye that's what I thought

tropic gulch
#

what the fuck is this preview image

frank hazel
#

reminds me of that dumb joke in the emoji movie

#

the challenges here are far less strict than PPCG's

tropic gulch
#

well, it's more about the fun and creativity here than about hard byte scoring

brisk zenith
#

well yeah, this is just a bit of fun and creativity.

#

heck

#

stop stealing my words

#

those were my words

tropic gulch
frank hazel
#

stop having fun

brisk zenith
#

i mean, you could post a hilariously long solution to a code golf challenge for all i care, as long as it's creative and interesting. like my tic-tac-toe script which was over 400MB and segfaulted the interpreter. that was nice.

frank hazel
#

all challenges must have observable requirements

#

r

#

EEEEEE

brisk zenith
#

yeah the requirement is to have fun while being creative and unique

#

seems pretty reasonable to me :D

frank hazel
#

that's not observable

brisk zenith
#

i don't care /shrug

#

i shrugged in the wrong place

frank hazel
#

yes

#

you did

brisk zenith
#

yes i know i did

#

thanks for confirming that haha

stray needleBOT
frank hazel
#

import sys;print(open(sys.argv[1]).read()) here's your cat by the way, it works on terminals that support 1 colour

brisk zenith
#

not short enough

#

:^)

frank hazel
#

boi

#

from sys import*;print(open(argv[1]).read())

#

that's one byte longer

brisk zenith
#

now add rainbow

frank hazel
#

it's already rainbow

#

it's just very small

marsh void
#

LOL

brisk zenith
#

how do you make the colours small..?

frank hazel
#

it's a small rainbow

#

it consists of 1 colour

#

it is a list of colours comprised of 1

#

on a cycle

#

prove me wrong

marsh void
#

Mate, just go make a normal rainbow xd

brisk zenith
frank hazel
#

"generally said to be"

brisk zenith
#

shush, this channel has been thrown wayyyyy off the rails. i think we should stop before lemon throws us off the rails.

marsh void
#

yeah we should tbh

frank hazel
#

wait, this channel is special?

#

...why?

#

because it runs its own events?

brisk zenith
#

it's not an off-topic channel.

frank hazel
#

the topical channels are also not

brisk zenith
#

your point is..?

#

:D

marsh void
#

^

frank hazel
#

why is this special and not topical

marsh void
#

Same, I don’t get what you’re saying lol

brisk zenith
#

i'm not too sure actually. it just is.

marsh void
#

why isnt it topical?

frank hazel
#

exactly

brisk zenith
#

lyricly's referring to the channel categories

#

i think it's because #esoteric-python is different from the other channels. this is entirely recreational, and we wouldn't want people picking up bad habits from here. mixing it in with the topical channels would likely cause problems.

#

that's my take on it at least, but if you want a definite answer, ask in #community-meta

frank hazel
#

making languages look like other languages is always fun

tropic gulch
#

it's TOPICAL CHAT/HELP

frank hazel
#

I almost made it so you can run BF in Python with only +-[]><,._

tropic gulch
frank hazel
#

yeah there's no help here

#

but the problem is chaining

#

and < chain

#

and you can't get around it

#

so if you try to write like

#

_>_>_

#

it chains and you can't overload and

#

so there's nothing you can do

#

to take that over

brisk zenith
#

you could overload __bool__ somehow

#

but doing it properly would be tricky, if not impossible

frank hazel
#

yeah I don't think it can be done

#

well, actually

#

it's easy if you use globals but that's no fun

snow beacon
#

Maybe if you had the bytecode...

sick hound
#

For some strange reason I really want to write a python bytecode interpreter in python
absolutely pointless but it's basically a solution to number 8
it's sorta the same with the AST except AST is a slightly higher level

gilded orchid
#

I’m kind of tempted to golf a brainfuck interpreter, and then right a programme in brainfuck that ‘rainbowfies’ the input given

#

would that be a valid solution?

snow beacon
#

I'm sure it would be.

brazen geyser
#

@sick hound it's very much not pointless

#

i've been doing the same in another language and it's a great learning experience

#

if you do id recommend forking and downloading the cpython source from the repo then opening it in Visual Studio or some other IDE/editor so you can find the C++ implementations for each opcode, as examples to work off of

#

you can search that page by itself but sometimes youll have to chase down some other implementation details elsewhere in the source and having the files open in an IDE helps with that

#

helped speed things up a lot

sick hound
#

C++?
I thought Python was C?

marsh void
#

Yeah same

sick hound
#

But yeah it's probaby not pointless
It's just a lot of time that I don't have

#

(github thinks .h files are cpp, ignore that)

brazen geyser
#

my mistake then

marsh void
#

What is M4? thinkingglare

brazen geyser
#

though c is a subset of c++ so they could technically be mixing them

#

g++ can compile both

sick hound
#

not sure
clicking on it yields no results

brazen geyser
#

oh actually im not sure what theyre using to compile them

sick hound
#

I don't think C is really that interoperable with C++
wikipedia agrees

brazen geyser
#

depends on what youre doing i guess

livid seal
#

@marsh void it's a dependency of autoconf: https://en.wikipedia.org/wiki/M4_(computer_language)

m4 is a general-purpose macro processor included in all UNIX-like operating systems, and is a component of the POSIX standard.
The language was designed by Brian Kernighan and Dennis Ritchie for the original versions of UNIX. It is an extension of an earlier macro processor m...

marsh void
#

oh ok

sick hound
#

(C)Python written in C

#

The total LoC in python files are greater than LoC in C because

#

All of the tests written in python, most of the stdlib and tools like argument clinic that doesn't affect usage

#

the core part is located in Python/ directory.

#

also you can compile python in a c++ compile

#

because all of code has extend c {}

last locust
#

🤔

brisk zenith
#

@last locust yup. things like int and str are types. for example, an object can be an int type or a str type, but not a print type. similarly, type is also a type; it creates other types/classes, and is therefore a metaclass. when you do py class Thing: ...
an instance of the type type is implicitly created.

last locust
#

Ah, I see

#

Thanks

last locust
vocal oyster
#

run it on your own machine, print x in the loop and see?

last locust
#

On phone

#

That’s why I’m using the bot :p

#

So not quite sure why it’s timing out...

brisk zenith
#

for every iteration you're adding a new item into the list, so you'll never reach the end of the list like that.

last locust
brisk zenith
#

a[i] is the same object as a

#

so you're still appending to a

last locust
#

🤔

#

a is [[[...]]] right

brisk zenith
#
>>> a = []
>>> a.append(a)
>>> a
[[...]]
>>> a[0].append(a)
>>> a
[[...], [...]]
>>> a[0] is a
True
>>> 
last locust
#

Wait what

#

a[0] isn’t a though

brisk zenith
#

it is

#

it literally is

#

you're appending a to a so that a[0] is a

last locust
#

a = [[...], [...]] and a[0] is [...]?

brisk zenith
#

[...] is just python's way of saying "oh hey this list contains itself, let's avoid infinite nesting here"

#

otherwise you'd get [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ ... ]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]

#

forever, and would ultimately crash python. which is what happened in python 2, actually.

last locust
#

🤔

#

I’m so confused though

#

if you add [] to [] it becomes [[]]?

#

Yea, so why doesn’t a.append(a) work the same when a is []

brisk zenith
#

yes, but that's not exactly how lists work in python. if they weren't the same list, that would happen. for example:

#

!e ```py
a = []
b = [] # this is a new, different list
a.append(b)
print(a)

c = []
c.append(c) # this is adding the same list to itself. so it becomes a list that contains itself, which is a list that contains itself, which is a list that contains itself... and so on.
print(c)

night quarryBOT
#

@brisk zenith Your eval job has completed.

001 | [[]]
002 | [[...]]
brisk zenith
#

i can make a diagram for it, hold on. :D

nocturne saddle
#
# this is adding the same list to itself. so it becomes a list that contains itself, which is a list that contains itself, which is a list that contains itself... and so on.

Did you just kill the universe?

brisk zenith
#

perhaps not haha

last locust
#

🤔

#

This is so confusing

brisk zenith
#

sure it is, give me a moment and i'll clear it up a bit

last locust
#

Surely because a = [] it should be the same as a.append([])?

brisk zenith
#

nope

#

because the [] in a.append([]) is a different list in memory to a

#

it's the same as a, sure, but it's not the exact same object

last locust
#

So it doesn’t get the actual value?

nocturne saddle
#

Say, you use the analogy of a list being a container, say a box you can put things in. In the first example above, you're just putting one box inside of another box. Two different boxes.

#

In the second example, you're putting the SAME box inside of the SAME box

vocal oyster
#
>>> a = []
>>> a.append(a)
>>> a
[[...]]
>>> a[0]
[[...]]
>>> a[0][0]
[[...]]
>>> a is a[0]
True
>>> a[0] is a[0][0]
True
last locust
#

So... to get around that you’d have to do something like this?

vocal oyster
#

depends on what you want to achieve

nocturne saddle
#

Well, the empty list you've put in a is now in two positions

vocal oyster
#
>>> a = []
>>> a.append([])
>>> a
[[]]
>>> a.append(a[0])
>>> a
[[], []]
>>> a[0].append(5)
>>> a
[[5], [5]]
last locust
#

Say something like this... would each element of a now contain 1?

nocturne saddle
#

That, we can test!

#

!e

a = []
a.append([1])
a.append(a)
print(a[1][0])
night quarryBOT
#

@nocturne saddle Your eval job has completed.

[1]
last locust
#

So like a[0] is a[1] and a[0] is a[1][0] which is a[1][0][0]?

vocal oyster
#
>>> a = []
>>> a.append([1])
>>> a
[[1]]
>>> a.append(a)
>>> a
[[1], [...]]
>>> a[0]
[1]
>>> a[1]
[[1], [...]]
>>> a[1][0]
[1]
>>> a[1][1]
[[1], [...]]
nocturne saddle
#

a[0] is just refering to another list, another container: [1]

vocal oyster
#

a[0] is [1], a[1] is a

nocturne saddle
#

a[1] refers to the whole of a itself, like a Droste image

#

If you take the speaker on the left to be [1] and the tv to be a itself, you get the idea

#

Each nesting has first a reference to [1] and then a reference to the whole thing again

#

Making an infinite recursion into the depths of infinity

brisk zenith
last locust
#

So a[0] != a[1] but a[0] == a[1][0]?

nocturne saddle
#

is actually

last locust
#

^^

vocal oyster
#

not just a[0] == a[1][0], a[0] is a[1][0]

nocturne saddle
#

It's refering to the same list of [1]

last locust
#

Yea I know it’s is just easier to type == lol

nocturne saddle
#

!e

a = []
a.append([1])
a.append(a)
print(id(a[0]))
print(id(a[1][0]))
night quarryBOT
#

@nocturne saddle Your eval job has completed.

001 | 140422767086088
002 | 140422767086088
last locust
#

And then a[0] is a[1][0][0]?

nocturne saddle
#

a[1][1][0]

vocal oyster
#

a[1][0] is [1]

#

so a[1][0][0] is 1

last locust
#

🤔

#

That makes sense

vocal oyster
#

the first index will always point to [1], the second index will always point to the original list

last locust
#

At least I understand that

marsh void
#

Lol what are ya doin? sounds like my nickname started it

last locust
#

^^ lol

#

I think I’ve finally understood this

#

But if you have like a=[[1,2,3]] then you do a.append(a) is a[1][0] going to be [1,2,3]?

vocal oyster
#

yap

#

the exact same one

last locust
#

And a[1][1][0] would be as well?

vocal oyster
#

yap

marsh void
#
a = []; a.append(a)
for i in range(1000):
    a = a[0]
print(a)
>>> [[...]]
#

Tho

last locust
#

This is so god damn confusing lol

marsh void
#

Yeah lol

last locust
#

But I think I finally got it

marsh void
#

well, in my example: a contains a, so when you do a[0] python says: well, it’s the same list, so it contains a too

last locust
#

Yeah... I think I get this

marsh void
#

And well, if you wanna get a copy of list elements, you can do:
a = [1,2,3]
a.extend(a) # or a += a

brisk zenith
#

or a.append(a.copy())

marsh void
#

^

#

But it’s longer

brisk zenith
#

something along those lines

last locust
#

Anyway I just spent all my lunch break doing this so got to go now :p thanks for helping me with this lol

marsh void
#

lol

#

also, to get n copies, you can do:
a = [1,2,3]
a*=n # n is integer, that you needa define

#

@brisk zenith where have you got this cool .append() explanation in picture? scroll up a bit

brisk zenith
#

you mean my little diagram?

#

i threw it together in draw.io quickly

marsh void
#

Ok thanks for sharing

#

not esoteric enough

#

How can I make subclass of a tuple that takes *args on __init__? How am I gonna do super().__init__()?

brisk zenith
#

example?

marsh void
#
class ntuple(tuple):
    def __init__(self, *args):
        super().__init__(args) # throws an error if I remember
#

oh, I meant tuple

#

Yeah, tuple throws TypeError: tuple expected at most 1 arguments, got 3

#

@brisk zenith whatcha think?

#

I wish to be able to do ntuple(1,2,3) for example

#

Oh, I should get to help channel I guess 😂

brisk zenith
#

@marsh void i think you need to override __new__ for built-in types, not __init__.

nocturne saddle
#

It works for me

#
>>> class n(tuple):
...     def __init_(self, *args):
...             super().__init__(args)
... 
>>> n((1,2,3))
(1, 2, 3)
brisk zenith
#

__init_

#

you haven't defined __init__ haha

nocturne saddle
#

oh

#

haha

marsh void
#

Lol

nocturne saddle
#

:(

marsh void
#

And also, you are giving it one arg, tuple

#

I want n(1,2,3), not n((1,2,3))

#

🤔

brisk zenith
#
>>> class ntuple(tuple):
...     def __new__(cls, *args):
...             return super().__new__(cls, args)
... 
>>> x = ntuple(1, 2, 3)
>>> x
(1, 2, 3)
>>> type(x)
<class '__main__.ntuple'>
>>> 
#

as i said, override __new__

marsh void
#

Okay cool

#

Should I do the same for nlist? Or just override __init__? (It works with overriding init)

brisk zenith
#

i'm not sure.

marsh void
#

Just like, I guess I should stick to one style

nocturne saddle
marsh void
#

Awww collections

#

Why not subclassing built-in though? Are there real problems with it? (It’s ok, I’m just curious)

brisk zenith
#

it's generally trickier to work with

#

using a UserList makes your code cleaner

#

and easier to maintain and all that stuff

marsh void
#

Oki

grave rover
#
class IndexRegister:
    def __index__(self, target: list):
        class RegisterMetaClass(type):
            def __new__(mcs, *args):
                obj = type.__new__(mcs, *args)
                target.append(obj)
                return obj
    return RegisterMetaClass

RegisterMeta = IndexRegister()

# Usage
all_things = []

class A(metaclass=RegisterMeta[all_things]):
    ...

class B(A):
    ...

class C(metaclass=RegisterMeta[all_things]):
    ...

print(all_things)  # => [<class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>]
sick hound
#

I was gonna say why not a class deco but then I realised this is #esoteric-python

grave rover
#

well, if you're enforcing a specific base class this might be really useful

#

Since subclasses don't automatically call the parent decorator but a metaclass works at all times

#

I personally use this concept in some of my projects

#

All I have to do is make sure the module is imported and I can use it whenever

last locust
#

Or it just doesn’t check that far and raises the error... since this should work

edgy kelp
#

not sure if int can convert string floats

last locust
frosty quartz
#

Use int(float("1.0"))

ivory tangle
#
a = []
a.append(a)
a
tropic gulch
#

[[...]]

last locust
#

How do you do from x import y in terms of __import__?

#

Trying to figure out if there’s a neater way to do the imports on py salt = str(__import__('uuid').uuid4()); print(__import__('hashlib').sha512((input("Enter Pass")+salt).encode()).hexdigest(), salt, sep="\n\n")

desert garden
#

Might be able to use a map

#

Depending on how many chars that would use

wind maple
#

i=__import__

#

also no you can't really do from x import y in terms of __import__ on it's own

last locust
#

@wind maple what do you mean by i=__import__?

wind maple
#

you can assign it like that to shorten the code

last locust
#

Oh I see

#

So py i = __import__; i('hashlib')

#

That sort of thing?

wind maple
#

ye

last locust
#

Thanks, didn’t think of that xD

rose crystal
#

how do yall do python so good

#

i have a huge interest in coding but im not good at it

#

im trynna learn

wind maple
#

read lots of code from other people

last locust
#

Either you have a flair or you practice loads

#

I’ve got a natural flair

wind maple
#

you'll start recognizing patterns

last locust
#

Learnt python in about a week or two

#

And yeah you start to learn patterns

brisk zenith
#

saying you "learnt python in a week or two" is silly. python has so many things to learn that i'd say it's impossible to "learn it" in even a few years.

last locust
#

I learnt the basics

#

That’s what I meant

#

Loops, functions, data types, libraries, json, csv e.t.c

#

Probably more things I’m forgetting right now

#

Oh yeah classes

nocturne saddle
#

You know more than I do then

fallen heath
#

So can you explain juan's hello world program?

brisk zenith
#

my hello world program?

#

which one? i have a few.

fallen heath
#

The one with all the shifts

brisk zenith
#

ah that one. it's pretty cool

nocturne saddle
#

The one with the empty lists converted via bool to zeros?

#

and/or 1s depending on the context

brisk zenith
#

well that's one version of it, sure.

#

!e ```py
print(bytes([((not[])<<((not[])^(not[])<<(not[]))^(not[])<<((not[])^(not[])<<((not[])<<(not[])))^(not[])<<((not[])<<(not[])^(not[])<<((not[])<<(not[])))), ((not[])^(not[])<<((not[])<<(not[]))^(not[])<<((not[])^(not[])<<((not[])<<(not[])))^(not[])<<((not[])<<(not[])^(not[])<<((not[])<<(not[])))), ((not[])<<((not[])<<(not[]))^(not[])<<((not[])^(not[])<<(not[]))^(not[])<<((not[])^(not[])<<((not[])<<(not[])))^(not[])<<((not[])<<(not[])^(not[])<<((not[])<<(not[])))), ((not[])<<((not[])<<(not[]))^(not[])<<((not[])^(not[])<<(not[]))^(not[])<<((not[])^(not[])<<((not[])<<(not[])))^(not[])<<((not[])<<(not[])^(not[])<<((not[])<<(not[])))), ((not[])^(not[])<<(not[])^(not[])<<((not[])<<(not[]))^(not[])<<((not[])^(not[])<<(not[]))^(not[])<<((not[])^(not[])<<((not[])<<(not[])))^(not[])<<((not[])<<(not[])^(not[])<<((not[])<<(not[])))), ((not[])<<((not[])^(not[])<<((not[])<<(not[])))), ((not[])<<(not[])^(not[])<<((not[])^(not[])<<(not[]))^(not[])<<((not[])<<((not[])<<(not[])))^(not[])<<((not[])^(not[])<<((not[])<<(not[])))), ((not[])^(not[])<<((not[])^(not[])<<(not[]))^(not[])<<((not[])^(not[])<<((not[])<<(not[]))))]).decode())

night quarryBOT
#

@brisk zenith Your eval job has completed.

hello :)
nocturne saddle
#

Yeah, that one

gilded orchid
#

what on earth

fallen heath
#

Juanita isn't on earth sadly.

brisk zenith
#

yeah for sure

fallen heath
#

They look down upon us from the great outdoors.

gleaming path
#

i think i understand it, but i don't like it

nocturne saddle
#

You can make it a bit easier to comprehend by not using the bytes and decode in there

brisk zenith
#

how do you mean? like, just making individual integers?

nocturne saddle
#

!e

print(*(chr(n) for n in [((not[])<<((not[])^(not[])<<(not[]))^(not[])<<((not[])^(not[])<<((not[])<<(not[])))^(not[])<<((not[])<<(not[])^(not[])<<((not[])<<(not[])))), ((not[])^(not[])<<((not[])<<(not[]))^(not[])<<((not[])^(not[])<<((not[])<<(not[])))^(not[])<<((not[])<<(not[])^(not[])<<((not[])<<(not[])))), ((not[])<<((not[])<<(not[]))^(not[])<<((not[])^(not[])<<(not[]))^(not[])<<((not[])^(not[])<<((not[])<<(not[])))^(not[])<<((not[])<<(not[])^(not[])<<((not[])<<(not[])))), ((not[])<<((not[])<<(not[]))^(not[])<<((not[])^(not[])<<(not[]))^(not[])<<((not[])^(not[])<<((not[])<<(not[])))^(not[])<<((not[])<<(not[])^(not[])<<((not[])<<(not[])))), ((not[])^(not[])<<(not[])^(not[])<<((not[])<<(not[]))^(not[])<<((not[])^(not[])<<(not[]))^(not[])<<((not[])^(not[])<<((not[])<<(not[])))^(not[])<<((not[])<<(not[])^(not[])<<((not[])<<(not[])))), ((not[])<<((not[])^(not[])<<((not[])<<(not[])))), ((not[])<<(not[])^(not[])<<((not[])^(not[])<<(not[]))^(not[])<<((not[])<<((not[])<<(not[])))^(not[])<<((not[])^(not[])<<((not[])<<(not[])))), ((not[])^(not[])<<((not[])^(not[])<<(not[]))^(not[])<<((not[])^(not[])<<((not[])<<(not[]))))]), sep="")
night quarryBOT
#

@nocturne saddle Your eval job has completed.

hello :)
brisk zenith
#

oh i see

nocturne saddle
#

the sep in there is just ugly

#

But I like the bytes version better

#

If you want to obfuscate, that's better

brisk zenith
#

i do want to make more interesting ways of obfuscating things.

vocal oyster
#

inb4 juan becomes a core developer to add functionality that secretly allows them to golf more

brisk zenith
#

haha i wouldn't

#

(but i guess that's what i would say, isn't it?)

#

i mean, it's possible to make any string using that method without using a list of codepoints @nocturne saddle it just gets very very very long for most strings.

wind maple
#

I mean it's not like core devs get magic veto powers

#

Could alreadly just PR something like that

nocturne saddle
#

Don't we :(

fallen heath
#

They'll make something like jsfuck possible in python.

vocal oyster
brisk zenith
#

i'm trying to make a way of obfuscating any string in such a way that it only takes two different characters to represent everything, but it requires some nasty ctypes stuff. i think it'll be cool if i can get it working though

wind maple
#

eh 🤔

brisk zenith
#

it sounds a bit naff but i think you'll like it

#

once i get it working that is :D

vague gust
#

!eval ```py
from ctypes import *
print(cast(pointer(ARRAY(3, c_longlong)(7596287720685593975, 8314039776092037230, 495958581792)), POINTER(ARRAY(24, c_char)))[0][:21].decode())

night quarryBOT
#

@vague gust Your eval job has completed.

we cookin on gas boys
gilded orchid
#

Is there a way to make any number only using the characters ()<1?

#

(using left bitshifts)

#

I feel like ^ might be required but I'm not sure

wind maple
#

no since shifts only operate in powers of two

#

if you added - then yes

brisk zenith
#

@vague gust isn't that just a union without the union? yert

vague gust
brisk zenith
#

i have done a bad thing ```py
print([][::][::[]][:[]:[]][[]]) # prints 11

#

can make any number up to 255, which means that all strings should be possible with a bit of fiddling

#
print(bytes([[][[]:[]:][[]::[]][:[]:[]][[]],[][[]:[]:][[]::[]][:[]:[]][::][[]],[][[]:[]:][[]::[]][[]::][:[]:[]][::][[]],[][[]:[]:][[]::[]][::][[]]]).decode())

will output "hiya"

whole kiln
#

What kind of hiya?

#

The hello kind or the fighting kind?

brisk zenith
#

whichever you want :D

#

i would have done "hello world" but i haven't made anything to generate these strings automatically yet

whole kiln
#

Is it easily chainable?

brisk zenith
#

yeah

whole kiln
#

Ah so making a generator will be ez

brisk zenith
#

yup.

#

but until then, try to figure out how it works, i dare you. :D

whole kiln
brisk zenith
#

take my original example: ```py
print([][::][::[]][:[]:[]][[]])

which prints `11`
whole kiln
#

This isn't default behaviour right? You've modified something?

brisk zenith
#

well yeah, i've replaced the pointer to list.__getitem__

#

using ctypes of course

#

i'll try to think of interesting ways to obfuscate without use of anything like ctypes though

whole kiln
#

In your hiya example did you wrap it in a list just so you could convert to bytes or something

brisk zenith
#

yeah

#

but there were four different numbers

#

representing the ascii codepoint of each character

whole kiln
#

Yeah that much was pretty obvious

#

and you always start with an empty list

brisk zenith
#

yep.

#

and i always end with [[]] as an implementation detail, but it has no significance in terms of the value of the number

whole kiln
#

I am gonna be boring and give up

#

I tried to see if there was a correlation between binary representation of numbers and the slices but couldn't really figure it out

brisk zenith
#

basically, the slices represent a binary number,
[::] is 0b000
[:[]:] is 0b010
[[]:[]:] is 0b110
and so on.

then, these binary numbers (which can go from 0 to 7) are used as powers of 2. so, with [:[]:[]] i would get 0b011 which is just 3, so the number would become 2³ which is 8. so that means i can make any binary number from 1 (which is 2¹) to 128 (which is 2⁷). then i can chain these numbers together to make any number like you would with regular binary.

[][::][::[]][:[]:[]][[]] is simply [::] + [::[]] + [:[]:[]],
which becomes, 0b000 (0) and 0b001 (1) and0b011 (3),
which then becomes 2⁰ + 2¹ + 2³, or just 11

whole kiln
#

ah I didn't think of using powers of 2

#

I was thkining of it sequentially

#

But it makes sense programtically that you'd use powers of 2

#

cause you can't just squish two halfs of a binary number together

#

I was considering endianness too lol

brisk zenith
#

oh haha fair enough

whole kiln
#

I understood as soon as your said powers of 2 so it's fine

brisk zenith
#

oh haha nice. but it's there in case anybody else is lurking, then. :D

cunning wave
#

@brisk zenith it doesnt work for me 😦

#

halp

brisk zenith
#

yeah i know, as i said i had to do some ctypes stuff beforehand to make it work

#

but my code is really weird and won't work properly so i'll sort it out tomorrow

whole kiln
#

Hey peeps I need some code for a unittest that will use up a lot of memory in under 2 seconds

#

The basic stuff I could think of will time out before it runs out of memory

#

"a lot" of memory is specifically more than 52428800 bytes

#

Ok well I decided to just look it up but if you come up with something fun then I can use that instead

#

Here's a question: Is there a way to exceed memory limits while avoiding MemoryError being raised?

#

Like disabling the mechanism for that and just letting it crash and burn

chrome moth
whole kiln
#

I can clarify. I need Python to exceed a memory limit set by a cgroup. The process should get killed by something else but Python kills itself beforehand

mortal ingot
#

oh that explains why i got a TypeError on that slice thingy

chrome moth
#

Idk but I just crashed my computer

#

Trying to fuck with Memory Errors

whole kiln
#

Thanks for trying

#

I guess crash and burn was a bit further than what I actually had in mind

grave rover
#

@whole kiln load a hella lot of cython modules, they crunch RAM

sick hound
sick hound
#
>>> f = -0.
>>> f
-0.0
>>> f + 0
0.0```
#

yay, weird float edge cases

#
>>> f = 0.
>>> f
0.0
>>> f - 0
0.0``` in a way this is consistent but in another way it's not
#

wtf floats

wind maple
#

blame ieee 754

brazen geyser
#

why is this the case?

>>> float('inf') - float('inf')
nan
>>> 
edgy kelp
#

What would you expect it to put out?

brazen geyser
#

0

edgy kelp
#

That's not how infinity works

brazen geyser
#

TIL

gilded orchid
#

I'd say it'd either be negative infinity or infinity, but even then both are technically wrong

wind maple
#

It's undefined so give the number mandated by the standard for that

#

Then again 0 ** 0 is 1 🤔

brisk zenith
#

i guess because those are integers and there's nothing in python for undefined integers? but i guess an error could be thrown or something

fallen heath
#

The most common possibilities are 1 or leaving the expression undefined, with justifications existing for each, depending on context. In algebra, combinatorics, or set theory, the generally agreed upon value is 00 = 1, whereas in mathematical analysis, the expression is generally left undefined. Computer programs also have differing ways of handling this expression.

gentle pagoda
#

is there a way around this? ```py
exec("stuff") # fine
exec("stuff;exec('stuff')") # fine
exec("stuff;exec('stuff;exec in here?')")

what about even higher levels of exec?```

sick hound
#

you can use \s

#
exec("stuff;exec('stuff;exec(\"hello\")')")```
#

a \ before a character like ' (or \) tells python "ignore anything special about this character, it's just an actual character, nothing else"

#

a \ before a normal character like a or x tells python "this isn't an actual character, this is something else"

gentle pagoda
#

ah ok

#

so \n vs n

sick hound
#

yes

#

n is just n

#

\n is a newline

#

" ends the string (if the string began with ")

#

\" is just "

#

\\ is just \

gentle pagoda
#

does that work for even more sublevels of exec?

#

or does it become \\" then \\\" etc

sick hound
#

it should work if you add more backslashes

#

but i'm not entirely sure how many backslashes you'd need

#

and it's kind of a bit weird

gentle pagoda
#

one more thing, does that work for multiline strings?

#

if i put \"\"\"

sick hound
#

yes

#

...but also

gentle pagoda
#

perfect thanks :p

sick hound
#

you don't need to worry about getting exactly the right number of backslashes

#

the python REPL can tell you

gentle pagoda
#

thanks 😄

sick hound
#
>>> input()
aaaaaaa
'aaaaaaa'
>>> input()
bbbbbbb; exec('aaaaaaa')
"bbbbbbb; exec('aaaaaaa')"
>>> input()
ccccccc; exec("bbbbbbb; exec('aaaaaaa')")
'ccccccc; exec("bbbbbbb; exec(\'aaaaaaa\')")'
>>> input()
ddddddd; exec('ccccccc; exec("bbbbbbb; exec(\'aaaaaaa\')")')
'ddddddd; exec(\'ccccccc; exec("bbbbbbb; exec(\\\'aaaaaaa\\\')")\')'```
#

if you use input() and enter some stuff, what it prints will be the representation of that stuff, which you can then put back into code and it will be a properly \d string

gentle pagoda
#

ooh cool thanks

gentle pagoda
#

another question about this, im a bit lost. why does this give me EOL while scanning string literal? py exec('x="\n"')

wind maple
#

You need to escape the \

#

Right now it's trying to exec

x="
"```
ivory tangle
#

wait yeah you're right

gentle pagoda
#

ahh ok

#

thanks

#

i keep forgetting its a string so it interprets \n and stuff before interprets the code itsself :P

night quarryBOT
#
Nuh-uh.

Sorry, but you may only use this command within #bot-commands.

gilded orchid
#

rip

marsh void
#

Very brainf*cking tho

snow beacon
#

I'm writing a subleq interpreter

#

Sort of.

#

I figured it would be easy to golf the subleq interpreter, even if the subleq program itself has to be hellishly lengthy.

stone apex
#

Quiz time: Without checking, what is the effect of the following blocks? python a = [] a[0] = [1, 2]

a = []
a[0:0] = [1, 2]```
```python
a = []
a[::] = [1, 2]```
whole kiln
#

a = [[1, 2]] a = [] a = [1, 2]

#

not sure on the 2nd one

stone apex
#

my guess was error, error, error

mortal ingot
#
  1. raise IndexError
  2. do nothing (a = [])
  3. a = [1, 2]
whole kiln
#

Oh yeah it would raise indexerror

#

I was treating it like a dict

snow beacon
#

I thought: [[1, 2]], [1, 2], [1, 2]

marsh void
#
  1. raise IndexError
  2. a = [1, 2]
  3. a = [1, 2]
#

Surprisingly, a[0:0] = [1, 2] works finger_gun

#

I thought it would do nothing, so opened idle to check that

#
>>> a = []
>>> a[0:0] = [1, 2]
>>> a
[1, 2]
whole kiln
#

The 0 slice prepends. Makes sense that way

#

Whereas just the colons replaces all previous values

grave rover
#

But what if a is already initialized

#

Like, with some values

#

Huh, I guess it makes sense it still prepends

marsh void
#
>>> a = list('xyz')
>>> a
['x', 'y', 'z']
>>> a[0:0] = [1,2]
>>> a
[1, 2, 'x', 'y', 'z']
wind maple
#

index error, [1, 2], value error

#

huh

#

I wonder why the last one works

marsh void
#

yes

#

same lol

wind maple
#

wait of course it does

grave rover
#

Wait

#
>>> a = list(range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[3:6] = list(range(10,15))
>>> a
[0, 1, 2, 10, 11, 12, 13, 14, 6, 7, 8, 9]``` this feels so broken wtf
marsh void
#

Lol

#

@grave rover
Why list(range(x))? Not esoteric at all.

a = [*range(10)]

much better 😂

marsh void
#

@sick hound of course

sick hound
sick hound
#

@marsh void that isn't very esoteric either

#
*a, = range(10)```
marsh void
#

Oh yes

#

[*range(10), *range(11, 20)]

young mantle
#

assignment expressions make do while loops available, correct?

#
user_input = input("\"quit\" to quit")
while user_input != "quit":
    ...
    user_input = input("\"quit\" to quit ")

vs

while (user_input := input("\"quit\" to quit ")) != "quit":
    ...
    user_input = input("\"quit\" to quit ")
bronze idol
#

A do while checks the condition after executing the code in the block. So the code block always get's executed at least once. Even with assignments that will not always be the case with a while loop.

#

Assignment let's you make the same old while loop but without the priming statement on the previous line.

brisk zenith
#

there's loads of do ... while(0) in the python interpreter source code. i sorta understand why, but it just feels weird that it has to be done that way. but that's C, not python.

sick hound
#

do while 0?

#

isn't that the same as just not having the do...while loop at all?...

bronze idol
#

Yep

#

Well it's like not having the loop. You'll still execute all the code in the loop once.

sick hound
#

yes, exactly

#

why do you need to have a do ... while(0)

bronze idol
#

I think it allows them to skip any following code and jump to the end of the loop using break or continue.

sick hound
#

oh, that kind of makes sense actually

bronze idol
#
do{
    do_a_thing();
    break;
    dont_do_this();
} while(0)
#

Yep just tested it in JS, ends the loop execution. Pretty clever.

brisk zenith
#

but it's C so they could just use goto or whatever

bronze idol
#

Yeah but goto is so 1980s lol

brisk zenith
#

i think they use do while(0) in macros because macros can only contain one block or statement or whatever

#

and goto is used quite a lot in the cpython source code too

#

not loads and loads, but you'll notice it in places when looking through it

#

such as in ceval.c or something like that.

#

or it might be the bytecode compiler or something

#

just to name one example

sick hound
#

just to name one example that I can't remember

brazen geyser
#

so wait

#

continue in a do while doesnt check the condition?

#

oh nvm i misunderstood

sick hound
#

you’re here too? @sick hound

gilded orchid
#
def run(code, inp=''):
    codePos = 0
    pos = 0
    cells = [0]
    cellPos = 0
    indentations = []
    while True:
        if code[codePos]=='[':
            if cells[cellPos] == '0':
                while code[codePos]!=']':
                    codePos += 1
                codePos += 1
            else:
                indentations.append(cellPos)
        elif code[codePos]==']':
            codePos = indentations[-1]
            del(indentations[-1])
        elif code[codePos]=='>':
            try:
                cellPos += 1
                cells[cellPos]
            except IndexError:
                cells.append(0)
        elif code[cellPos]=='<':
            cellPos -= 1
        elif code[cellPos]=='+':
            cells[cellPos] += 1
        elif code[cellPos]=='-':
            cells[cellPos] -= 1
        elif code[codePos]=='.':
            print(chr(cells[cellPos]),end='')
        elif code[codePos]==',':
            cells[cellPos] = ord(inp[0])
            del(inp[0])
        else:
            continue

I'm trying to make a brainfuck interpreter, but this isn't doing anything. Any clue why?

#

(note that it doesn't raise an error, it just halts forever doing nothing)

#

nvm, turns out I just needed to add codePos += 1 at the end

marsh void
#

Lol

#

It happens when you forget to put something like incrementing variable and then think why the hell nothing is working

sick hound
#

it looks like your loops aren't quite going to work @gilded orchid

#

you never actually jump backwards to the beginning of the loop

gilded orchid
#
def run(code, inp=''):
    codePos = 0
    pos = 0
    cells = [0]
    cellPos = 0
    indentations = []
    while True:
        if code[codePos]=='[':
            if cells[cellPos] == '0':
                while code[codePos]!=']':
                    codePos += 1
                codePos+=1
            else:
                indentations.append(cellPos)
        elif code[codePos]==']':
            codePos = indentations[-1]
            codePos-=1
            del(indentations[-1])
        elif code[codePos]=='>':
            try:
                cellPos += 1
                cells[cellPos]
            except IndexError:
                cells.append(0)
        elif code[codePos]=='<':
            cellPos -= 1
        elif code[codePos]=='+':
            cells[cellPos] += 1
        elif code[codePos]=='-':
            cells[cellPos] -= 1
        elif code[codePos]=='.':
            print(chr(cells[cellPos]),end='')
        elif code[codePos]==',':
            cells[cellPos] = ord(inp[0])
            del(inp[0])
        else:
            continue
        if cells.count(256)>0:
            cells[cells.index(256)]=0
        if cells.count(-1)>0:
            cells[cells.index(256)]=255
        codePos += 1
        
run('+[.+]')

I changed a couple of things, just didn't post it here (this still doesn't work lmao)

#

It should output all the ascii characters from 1-255, but it only outputs every other one (and also it never ends)

sick hound
#
            codePos = indentations[-1]
            codePos-=1```
#

...actually that should be fine

#

wait

#
        else:
            continue```
gilded orchid
#

the code-=1 is meant to counteract the codePos+=1 at the end, so that means when it runs next it'll be at the start of the loop

sick hound
#

if it's not a valid character, you don't increment codePos

gilded orchid
#

all of the characters in the thing i'm trying are valid (+[].), so that isn't the issue thats affecting this (although nice spot)

sick hound
#

HANG ON

#
                indentations.append(cellPos)```
#
            codePos = indentations[-1]```
gilded orchid
#

ohhhhh

#

I put cellPos instead of codePos

sick hound
#

yes

gilded orchid
#

ok, it's actually functioning correctly now, except it's never ending

sick hound
#
            if cells[cellPos] == '0':```
#

all the cells are numbers

#

not strings

#

0 != '0'

gilded orchid
#

oh yeah