#esoteric-python

1 messages · Page 69 of 1

gilded orchid
#

wow I made a load of mistakes lmao

#

(probably cos' I coded this all in one go and then tested it afterwards, probably not the smartest idea)

sick hound
#
            del(inp[0])``` you can't do that with a string, do `inp = inp[1:]` instead
gilded orchid
#

now it actually works 😃 (after I put the whole thing in a try except to avoid the index error from codePos at the end)

#

now I need to find a way to implement cells before the first one, so doing < at the begining works

west hornet
#

Which channel here is for talking about Python design patterns ?

vocal oyster
#

for general discussing, #python-discussion
if it's related to a problem you have and you need specific help, then any of the help channels will do

gilded orchid
#

this channel is for people who take python way too far

west hornet
#

I am taking python way to far :), but the issues is not too far 😄

onyx jacinth
#

This channel is also for people who take python too far to make it small

brisk zenith
#

well, we're more than just golfers :D

marsh void
#

we're

special = [chr(c) for c in (*range(33, 48), *range(58, 65), *range(91, 97), *range(123, 127))]

[Credits][Eviee#0666]

sick hound
#

we're py special=[chr(c)for a,b in((33,15),(58,7),(91,6),(123,4))for c in range(a,a+b)]

tepid glacier
#

we're

special=[*__import__('string').punctuation]
gilded orchid
grave rover
#

wait

#

is that Dennis ♦

gilded orchid
#

I'm currently working on a stack-based esolang, and this is the syntax I have so far

| = Pops the number off of the top of the stack
. = Pushes 0 to the stack
; = Pushes X on to the stack. If X is not passed, pushes 5 to the stack
+ = Adds X to the top number of the stack
- = Subtracts X from the top number of the stack
* = Multiplies X by the top number of the stack
# = Square roots the number at the top of the stack
/ = Divides the top number of the stack by X, then rounds it to the nearest whole number
( = Begin a loop. If after it there is a number, repeats by that number. If after it there is a =, followed by a number, 
the loop will end once the end is reached and the top number of the stack is equal to X.
) = End a loop.
> = Swaps the top value of the stack, with the X from bottom of the stack
< = Swaps the top value of the stack, with the X from top of the stack
[ = Begins a function that gets added to the function slot. There is only one space for functions, and it'll get replaced if a new one is began
] = Ends a function
^ = Clears the function
% = Runs function X. If function X is not passed, runs the function in the function slot
? = Runs the function in the function slot if the number of the top of the stack is equal to X
= = Runs the single instruction after it, if the top value of the stack is equal to X
~ = Roll the stack by X
' = Outputs the number X. If X is not passed, outputs the number at the top of the stack
" = Outputs the unicode character of X. If X is not passed, outputs the unicode character of the number at the top of the stack

(Note that 'X' refers to a number directly after the instruction, and it can be any positive integer)

any suggestions?

marsh void
#

@gilded orchid fucks brains well

gilded orchid
#

I'm thinking of having a seperate stack for functions, but I don't know how I'd implement that

#

(I'm thinking up the syntax before actually starting making it for context)

calm rampart
#

suggestion: operands are for cowards, just make digits operators that pop the stack, multiply by 10, add the number, and push

#

😛

gilded orchid
#

🤔

calm rampart
#

and every other operator's X is just popped from the stack

#

(this is arguably less esoteric, but more stack-based)

#

anyway the other thing i'd do is have a way to create strings and a way to evaluate them - dc builds loops and functions on this

gilded orchid
#

Could I maybe have a string slot that can be appended to, cleared and outputed

calm rampart
#

how about hollerith style strings: H: Reads the next [top of stack] bytes of input and places them on the stack as a string object

#

to build loops and functions dc-style, you need string objects that can be placed on the stack and string variables, not just a single string slot

gilded orchid
#

maybe I can have 3 different stacks, the number stack (the main one), the string stack and the function stack

#

and then have 3 different instructions that switch what stack the commands are running on

calm rampart
#

for conditionals you could have an operator that's "If the number on the top of the stack is non-zero, pop two items. Otherwise, pop the number and remove the third item from the stack, leaving the second"

#

honestly you can probably build loops from that and an eval function without even having an explicit loop operator

#

oh, a way to copy any given item from the stack can probably usually be used in place of variables.

gilded orchid
#

to replace X?

calm rampart
#

no i meant for the features i've been suggesting that require variables

gilded orchid
#

oh right

calm rampart
#

what if the language were stringly typed

#

then you could just have one stack and all elements on the stack are strings

#

math operators just treat the string as a number

gilded orchid
#

quick question, is the second number in the stack second from the top, or second from the bottom?

snow beacon
#

Top. Always top.

marsh void
#

Heh, more stack fun incoming? @gilded orchid

gilded orchid
#

I'm making the language way more limiting, to make it a lot harder to code in

#
. = Pushes 0 to the stack
# = Pops the number off of the top of the stack
; = Duplicates the value at the top of the stack
< = Swap the two values at the top of the stack
> = Roll the stack by the top number of the stack
^ = Makes a string out of the top number of the stack characters below the top character of the stack, and then pops all of those, and pushes that string to the stack
~ = Runs the string at the top of the stack. If it isn't a string, do nothing.
? = Run the string at the top of the stack, if the second number of the stack is non-zero
- = Subtract one from the number at the top of the stack
+ = Add one to the number at the top of the stack
" = Outputs the string at the top of the stack, and pops it off of the stack. If it is a number, do the same with that number corresponding unicode character.
#

how does this look, I got rid of a load of stuff and added @calm rampart's string suggestion, to make it way more annoying to code in

calm rampart
#

always the top

#

in most stack languages each operator only cares about however many operands on the top of the stack, and ignore an unlimited amount below

marsh void
#

@gilded orchid write Hello world lol

#

full of expectations

gilded orchid
#

I'll do that after I quickly write an interpreter (also I'm gonna add a * command to make it so you don't have to do 40 or more +'s to start a loop lmao)

marsh void
#

lol

gilded orchid
#

what's an easy way to swap the two things at the end of a list?

#

wait nvm, figured it out

marsh void
#

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

#

Anyway >.>

#

with my subclass of list called nlist, I can do:

from ntools import nlist  # not on pypi yet
a = nlist(1,2,3,4)
a.swap(-1, -2)
#

So it’s cool :)

gilded orchid
#

you should find a way to modify lists so they function as nlists when using []

brazen geyser
#

a[-2:] = a[:-3:-1]

#

lel

gilded orchid
#

ok, just finished the interpreter (I haven't actually tested it yet so it probably won't work lmao)

stack = []
def run(code):
    codePos = 1
    while codePos<=len(code):
        exec({'.':'stack.append(0)',
              '#':'stack.pop()',
              ';':'stack.append(stack[-1]',
              '<':'stack[-1],stack[-2]=stack[-2],stack[-1]',
              '>':'[stack.append(stack.pop(0))for i in range(stack[-1])',
              '^':'[stack.append("".join([chr(i)for i in stack[-1:-stack[-1]:-1]));del(stack[-2:-(len(stack[-1]))-2])'
              '~':'(run(stack[-1])if type(stack[-1])==str else pass)',
              '?':'((run(stack[-1])if type(stack[-1])==str else pass)if stack[-2]!=0)',
              '-':'stack[-1]-=1'
              '+':'stack[-1]+=1'
              '*':'[stack.append(stack[-1]*stack[-2]),del(stack[-2:-3:-1])]'
              '"':'(print(stack[-1]if type(stack[-1])==str else print(chr(stack[-1])))'}[code[codePos-1]])
        codePos += 1
#

(I used a really long dict cos' I was lazy)

brazen geyser
#

why not put the dict outside the loop

#

in a var somewhere

gilded orchid
#

ok, I've done that

#

here's a (I think) working version

codeDict = {'.':'stack.append(0)',
              '#':'stack.pop()',
              ';':'stack.append(stack[-1]',
              '<':'stack[-1],stack[-2]=stack[-2],stack[-1]',
              '>':'[stack.append(stack.pop(0))for i in range(stack[-1])',
              '^':'[stack.append("".join([chr(i)for i in stack[-1:-stack[-1]:-1]]))];del(stack[-2:-(len(stack[-1]))-2])',
              '~':'(run(stack[-1])if type(stack[-1])==str else pass)',
              '?':'((run(stack[-1])if type(stack[-1])==str else pass)if stack[-2]!=0)',
              '-':'stack[-1]-=1',
              '+':'stack[-1]+=1',
              '*':'stack.append(stack[-1]*stack[-2]);del(stack[-2:-4:-1])',
              '"':'print((stack[-1]if type(stack[-1])==str else chr(stack[-1])),end="")'}
stack = []
def run(code):
    codePos = 1
    while codePos<=len(code):
        exec(codeDict[code[codePos-1]])
        codePos += 1
run('.+++++++++++.+++*"')
brazen geyser
#

you can use this syntax for dicts too:

some_dict = {
    'key': 'value',
    'key': 'value',
}
#

if you want it a little cleaner

gilded orchid
#

that's basically what I'm already doing, except it looks stupid because of short discord line lengths

marsh void
#

@gilded orchid hello world when?

gilded orchid
#

i'm working on it

marsh void
#

Oki

gilded orchid
#

god damn it, I just made 'Hello corld!'

#

ok got it, hello world is .++++++.++++++*;.++*"#;.+++*;-------"#""+++"#;----"#;.+++*---------------------"#;.+++*+++"+++"------"--------"#;---" @marsh void

#

Imma try and create the fibonacci sequence using it

marsh void
#

noms a cookie

gilded orchid
#

I'm gonna add a new instruction that outputs the number, just to make this not take an eturnity to make

jade dust
#

What can you do with the ~ or ? operator?

#

Are you limited to executing single instructions, or is there some way to set up a chain?

gilded orchid
#

it runs a string, and the string can be as long as you want

#

it can be used, for example, for loops by using a string that keeps on running itself

jade dust
#

Oh right, I didn't see the ^ operator

#

This is really cool

gilded orchid
#

@marsh void I just realised to do that, I’m gonna need nested loops, so i need to make a strong that makes another string

#

oh god

jade dust
#

Time to make a quine!

gilded orchid
#

Quines actually aren’t possible lmao, because it uses eval so it breaks if you try to output "

#

lmao

jade dust
#

Wait, how?

gilded orchid
#

wait nvm I'm dumb

#

it used to be impossible, but I changed it a while ago

jade dust
#

Maybe you can replace those commands with functions

#

for readability

gilded orchid
#

yeah maybe

#

I was sort of just bodging it together, so readability didn't really matter when I was making it

#

I didn't even do any testing until after I made it, and then I fixed the 9 different syntax errors lmao

gilded orchid
#

Currently my roll instruction is moving everything down, and moving the bottom item of the stack to the top

#

is that what roll is meant to do?

calm rampart
#

what do you mean by down

#

sorry, my brain's always twisted up by this part because the first stack-based language I learned was HP48 calculators, which displays the top of the stack at the bottom of the screen

#

anyway, the HP48 description of ROLL is
ROLL
Moves a specified level to level 1
( e.g. 4 ROLL will move level 4 to level 1 )

#

i.e. it moves the X'th item of the stack (after popping X) to the top.

#

so I think yours is right then

#

swap is just 2 roll; rot is 3 roll; and dup is just 1 pick, so it might be worthwhile to make your available primitives roll/rolld/pick instead of dup/swap/roll

#

@gilded orchid

gilded orchid
#

I think mine's wrong, because doing roll on [1, 1, 2, 1, 2] gives [2, 1, 2, 1, 1]

#

and I think it should give [1,2,1,1,2]

frank hazel
#

@gilded orchid what does "roll" do?

gilded orchid
#

'Rotate: Also referred to as “roll,” specifies the number of elements in a stack which are rotated in their order. For example, rotating the top four elements of a stack would move the topmost element into the fourth position while the next three elements move up one position.'

frank hazel
#

so that should rotate the top 2 elements on the stack, then?

#

wouldn't that be [1, 1, 1, 2]

gilded orchid
#

my roll thing rolls the entire stack by the top value on the stack

frank hazel
#

okay

#

then the result you said is correct...?

gilded orchid
#

now that I think about it, I might change it to roll the top X of the stack (where X is the number at the top of the stack)

frank hazel
#

and I think it should give [1,2,1,1,2] this makes no sense

#

why isn't it popping the top number on the stack?

gilded orchid
#

good point, I should probably change that

gilded orchid
#

I'm trying to implement the 'proper' definition of rol, but I'm really struggling to actually get it to work

#

I currently have [stack.insert(-i,stack.pop(-1))for i in [stack[-1]]*stack.pop(-1)], but that rolls the entire stack, instead of only X from the top of the stack

#

nvm, I got it to work

brazen geyser
#

top of the stack is index 0?

brisk zenith
#

well if we consider how we can use lists as stacks, doing list.append(x) is like pushing to the stack and list.pop() is obviously popping from the stack

brazen geyser
#

im just a lil confused as to how rolling [1, 1, 2, 1, 2] should give [1,2,1,1,2]

#

thought maybe the top of the stack was index 0 in this case

brisk zenith
#

i'd expect it to be -1 🤔

gilded orchid
#

I used [stack.insert(-i+1,stack.pop(-1))for i in [stack.pop(-1)]] to make it work like that definition I sent earlier

#

(pop the top object off of the stack and roll X below it by one)

marsh void
#

hm

marsh void
#

Hey guys

#

listcomp vs unpacking

#

which is faster?

brisk zenith
sick hound
#

I wonder what features of Python can be turing complete

#

Lambdas and function calls are because lambda calculus (although technically you do run into a recursion limit)

#

but what else?...

grave rover
#

metaclass abuse for sure

wind maple
#

almost all operators are turing complete because you can put anything you want inside the operator overload 😃

gilded orchid
#

Can one-liners be Turing complete?

grave rover
#

Anything can be a oneliner

distant wave
#

Anything can be anything

#

behold:

>>> def a():
...     print("1")
...
>>> a()
1
>>> a.__qualname__ = "b"
>>> a
<function b at 0x10a79d0d0>
>>> a.__code__ = compile("print('c')", "<string>", 'exec')
>>> a()
c
#

That function you passed me is now mine :P

gilded orchid
#

Is there a list of all the different double underscore things in python?

brisk zenith
#

look at the python data model in the documentation

#

there's an entire page on it, but it shows and explains all dunders as well as other things

#

specifically section 3.3

gilded orchid
#

are you able to override all dunders?

#

eg: could you override new to run something whenever a new instance of a class is made

marsh void
#

yep, you can

#

maybe there are some dunders you can't override though

gilded orchid
#

Would you just create a class called new?

marsh void
#

I don't think so

gilded orchid
#

After doing some research, I’m pretty sure you just create a class that derives from object and then define new in that

#

wait nvm I’m actually an idiot

marsh void
#

@gilded orchid yep, you define __new__ in class, and actually run something in it lol

gilded orchid
#

how would you do that?

marsh void
#

hm

#
class ntuple(tuple):
    def __new__(cls, *args):
        do_some_stuff()
        return super().__new__(cls, args)
#

little example I guess

gilded orchid
#

what is super()?

marsh void
#

I am bad at explaining, honestly

gilded orchid
#

I just googled it and ‘
super() gives you access to methods in a superclass from the subclass that inherits from it.’

#

I don’t understand any of that lmao

marsh void
#

lol

#

so, like, lemme give an example

brisk zenith
#

there's hardly anything esoteric about this :D

gilded orchid
#

(I’m just bad at python)

marsh void
#
>>> class nlist(list):
...     def __init__(self, *args):
...         super().__init__(args)
>>> n = nlist(1,2)
>>> dir(n)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
gilded orchid
#

so super() would represent list in that case? (For the class at the top)

marsh void
#

so nlist has access to methods from the list

#

yeah, kinda

gilded orchid
#

But it only modifies the init

#

whilst keeping everything else the same

marsh void
#

don't really understand what you mean >.>

gilded orchid
#

Nvm

rugged sparrow
gilded orchid
#

so super just adds the mainClass's code onto it?

rugged sparrow
#

Super() gives you the instance of the class that the methods are inherited from

#

Sort of

#

But it's specifically that instance

gilded orchid
#

oh ok

rugged sparrow
#

Yeah

gilded orchid
#

so super().test() is an instance of mainClass().test()?

bronze idol
#

Sorta, it's actually more like mainClass.test(self), giving the method of main class the current instance of subClass

#

super() is just shorthand for getting the parent class and passing the current instance.

sick hound
#
class MainClass:
    def print_me(self):
        print(self)

class SubClass(MainClass):
    def print_me(self):
        print('hello!')
        super().print_me()

main = MainClass()
main.print_me() # <MainClass object at 0x......>

sub = SubClass()
sub.print_me() # hello! <SubClass object at 0x......>```
gilded orchid
#

completely random, but what would you guys say is the worst esolang hello world?

#

(it's longer then 2k chars so it can't fit in a discord message lmao)

wind maple
#

definitely fugue

gilded orchid
#

AND OUTPUT IT FOR THE CURRENT PERSON USING THIS PROGRAM TO SEE lmao

wind maple
#

naming your language verbose and deciding to use roman numerals instead of unary

#

:pathetic_skinner:

gilded orchid
#

I find it hilarious that you can't see the text "Hello World!" in 99% of these

calm rampart
#

i'd say the numbers should be spelled out in english

marsh void
#
>>> def nrange(start, end, step):
...     ret = []
...     while start < end:
...         ret.append(start)
...         start += step
...     return ret
... 
>>> nrange(1,2,0.1)
[1, 1.1, 1.2000000000000002, 1.3000000000000003, 1.4000000000000004, 1.5000000000000004, 1.6000000000000005, 1.7000000000000006, 1.8000000000000007, 1.9000000000000008]
#

Can someone explain a bit?

bronze idol
#

Floats aren't the most accurate.

#

So you get some drift.

marsh void
#

It feels quite weird

bronze idol
brisk zenith
bronze idol
#

With a domain like that it's esoteric 😝

marsh void
#

That’s actually quite neat melt

gilded orchid
#

wow, Minifuck is quite something

#
< : Same as Brainfuck
. : Move to next bit and invert it and output letter stored in first 8 bits, if none then input
[ : Move to next bit and invert it, skip next instruction and invert next bit if zero
#

I feel like it'd be fun to try and golf that

gilded orchid
#

Is there a short way to convert a list of binary into a denary number? (eg: [1,0,1] would become 5)

polar plover
#

int("".join(map(str, my_list)), 2) might work

#

!e ```py
my_list = [1, 0, 1]
my_number = int("".join(map(str, my_list)), 2)

print(my_number)```

night quarryBOT
#

@polar plover Your eval job has completed.

5
gilded orchid
#

Ves Zappa#3787 (not gonna ping) just gave me an identical solution in #help-coconut lmao, thanks though

#

(also the reason I asked here is because someone said I should because I was trying to golf it)

polar plover
#

np 😃 xD

gilded orchid
#

oh wow, 2/3 char brainfuck exists

< = Move pointer one cell to the left. (If pointer is currently over the first bit, do nothing.)
( = Move to next bit and flip it, skip next instruction if zero.
any other character = No-op instruction.
snow beacon
#

I'm working on a compiler to Subleq, which only has one instruction. It's a little different though because it has operands.

gilded orchid
frank hazel
#

@gilded orchid hello do you have a minute to talk about our Lord and savior

#

@snow beacon what does it compile to?

snow beacon
#

No, It compiles to Subleq. No way am I going to write any programs with one instruction.

frank hazel
#

oh I see

#

what does it compile from then

snow beacon
#

Just some syntax I threw together, with a lot of prewritten compiler macros in Python.

frank hazel
#

cool

snow beacon
#

I've got a bnf, but no language name.

#

I think I'll upload it somewhere once I'm happier with it. I was planning on using it for the pride esoteric python golf challenge. I'd have some golfed Subleq code, a golfed Subleq interpreter, and probably the compiler as a reference.

gilded orchid
#

@frank hazel ?

frank hazel
#

@gilded orchid you said you didn't know how subleq works

gilded orchid
#

Oh right

#

so subleq (the instruction not the language) takes 3 arguments

#

but what do they do?

frank hazel
#

the first two are memory addresses

#

the third is a...

#

memory address

gilded orchid
#

Does the third run the 3 numbers that are there as a subleq instruction?

frank hazel
#

all 3 are memory addresses, shockingly

#

it takes address 1

#

wait no

#

subleq x, y, z is like y = x - y; if y <= 0: jmp z

#

it sets y to x subtracted by y then if y is leq (less than or equal to) 0 it jumps to z

#

pretty simple

gilded orchid
#

What’s does jump do?

frank hazel
#

jumps the instruction pointer to that memory address

#

are you familiar with how control flow in assembly works?

gilded orchid
#

not really

frank hazel
#

it's all about jumping

#

time for pseudoassembly

#

say I want to check if two addresses contain the same number

#

I might do something like

#
00 cmp $F0E2 $F0E3
10 jeq 30
20 jeq 40
30 <if code>
40 <rest of code>
#

not real assembly, but

#

the idea is to structure it around jumping around since that's the only option you have

gilded orchid
#

So jump changes what instructions are running?

frank hazel
#

yes

#

a while True loop with jumps would look like

#
0xE000: uhh do something
0xE001: do another thing
0xE002: jmp 0xE000
#

jumping based on addresses is more of a machine code thing, though

#

in assembly you have something called labels to make it make much more sense

#
:loop 
wow
stuff here
wow code
jmp loop
#

this is more similar to something a real assembly language would have

#

Python has gotos, by the way, guess what

#

pip install goto

#

then you can import it

gilded orchid
#

oh wow

#

so does the third value jump to X line of code?

frank hazel
#

sort of, yeah

#

but in machine code there are no "lines of code"

#

only instructions

#

it would jump to the instruction stored at X memory address

gilded orchid
#

Would the first instruction be instruction 0?

frank hazel
#

yes

#

well that's not exactly defined by subleq itself, it might begin executing at some other memory address

#

I think most subleq emulators start at 0

gilded orchid
#

Also, does it jump to value X, or jump to the value stored at address X (where X is the first value)

frank hazel
#

it jumps to address X

#

the way execution works is there's an instruction pointer, which is an address

#

each time it reads the 3 values the pointer points to

#

executes that as subleq

#

then increases the pointer and goes again

#

jumping just sets the instruction pointer, basically

gilded orchid
#

So basically subleq has control flow, if statements and subtraction

#

in one instruction

frank hazel
#

yes, that's basically the idea

gilded orchid
#

wow

#

Do all memory addresses start at 0?

frank hazel
#

wdym

#

memory addresses, like list indexes, always start at 0

#

but some of the lower numbers might be reserved, like with CHIP-8

#

where the program actually starts at 0x200

gilded orchid
#

I meant does their value start at 0?

frank hazel
#

wdym value

gilded orchid
#

I’m so confused lmao

frank hazel
#

not sure what you mean by does the value start at 0

#

oh I see

#

sure

gilded orchid
#

I was thinking kind of like brainfuck

frank hazel
#

at the beginning your program is loaded into memory

#

anything else is 0, I guess

gilded orchid
#

are memory addresses nothing until you try and use it for something

#

and then it gets assigned to 0 and runs that instruction?

frank hazel
#

@gilded orchid it's always something

snow beacon
#

Your code can and should modify itself. Your code is in memory starting from zero generally. After that it's probably zeroes, or it could throw errors. My interpreter has accessing unset values terminate the program.

#

That way I can put everything in a list

#

The first thing I put in my compiler was labels, so I didn't have to bother with absolute addresses in code I'm going to change later.

marsh void
#

I know, kinda not esoteric, but how can I make the following code faster?

x, y = 1280, 720
a = []
for i in range(x):
    for j in range(y):
        a.append(
            (i, j)
        )
#

I found one though

from itertools import product as f
x, y = 1280, 720
a = [(i, j) for i, j in f(range(x), range(y))]

Is there a faster one?

nocturne saddle
#

I think you saved one character with that as f import

edgy kelp
#

simple list comp is considerably faster than the original

distant wave
#

Smaller, bit slower

x, y = 1280, 720
a = [(i // y, i % y) for i in range(x*y)]
edgy kelp
#

That's... slower?

#
from itertools import product
a=[]
a.extend(product(range(x),range(y)))
snow beacon
#

How does python x, y = 1280, 720 a = [(i, j) for i in range(x) for j in range(y)] compare?

marsh void
#

@nocturne saddle lol xd

#

@snow beacon didn't think it was working xd

snow beacon
#

Or perhaps using python list(itertools.product(range(x), range(y)))?

edgy kelp
#

the extend of product or list-ing it are the fastest, and probably the same (with list being more readable)

gilded orchid
#

It's suprisingly complicated because of the how input output works in it

marsh void
#

@gilded orchid ultimate bf sounds like ultimate boyfriend lol

gilded orchid
#

lmao

marsh void
#

I know what it is though

#

I'll golf when Code Jam ends

gilded orchid
#

is there a short way to do 1-liner assignment to variables?

marsh void
#

wym?

gilded orchid
#

like in the middle of a one-liner

#

assigning to a variable

marsh void
#

a = 1; do_stuff()

#

this?

gilded orchid
#

i'm trying to do it in a list

marsh void
#

oh

#

give me an example please, I am bad at abstract stuff

#

you can write it normally, and I can try to one-line

gilded orchid
#

I was just wondering for it generally

#

I'm not actually doing anything atm

#

(apart from my failed attempt to make that esolang interpreter I mentioned earlier)

polar plover
#

!e py foo = [1, 2, (locals().__setitem__("bar", 5), 3)[1], bar * 2, bar * 3] print(foo)

night quarryBOT
#

@polar plover Your eval job has completed.

[1, 2, 3, 10, 15]
polar plover
#

something like this?

#

@gilded orchid

gilded orchid
#

yeah that works

polar plover
#

but, why?

gilded orchid
#

idrk

#

why not?

polar plover
#

and is it not coming something like this in the next python version

#

!pep 572

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

Accepted

Python-Version

3.8

Created

28-Feb-2018

Type

Standards Track

marsh void
#

yup

#
print(a:=10)
#
def _():
    try:
        idx0 = width_height.index(t0)
    except ValueError:
        idx0 = 0
    try:
        idx1 = width_height.index(t1)
    except ValueError:
        idx1 = 0

how to make that shorter?

gilded orchid
#
for i in [(idx0,t0), (idx1,t1)]:
   try:
      eval(f'{i[0]}=width_height.index({i[1]})')
   except:
      eval(f'{i[0]}=0')
#

not really pythonic but this works I think

#

@marsh void

edgy kelp
#

could be a bit shorter sinceo nly the numbers change on idx and t

marsh void
#

lol, it gives NameError obv

gilded orchid
#

oh yeah

edgy kelp
#

but when you get to eval the question if you really want it to be shorter comes up

gilded orchid
#

then yes

#

else no

edgy kelp
#

well there are plenty variables that are terribly long in there 😄

gilded orchid
#
for i in [0,1]: #shorter then range(2) lmao
 try:
  eval(f'idx{i}=width_height.index(t{1})')
 except:
  eval(f'idx{i}=0')

(that's shorter btw)

#

@marsh void

marsh void
#

my ass was lazy so for readability I just made a function for that lol

gilded orchid
#

not really related but I just realised you can do 0,1 instead of [0,1] for golfing

#

neat

snow beacon
#

It says t{1} rather than t{I}

gilded orchid
#

oh yeah

#

oops

#

'Many people are familiar with it even if they don't know any other programming language.'

grave rover
unique kettle
#

i'm having trouble thinking of what i might even want to overload it to do

bronze idol
#

Nifty

#

I think the meaning would be too vague for most anything outside of numbers.

worthy ridge
#

well, maybe it would be useful if you had a lib to do particle physics too

bronze idol
#

Invert could be used for doing fuzzy checks ~my_fancy_thing == my_var, __invert__ would need to return an object that overloads __eq__... Would be way more clear with a named method lol

unique kettle
bronze idol
#

Wow lol

brazen geyser
#

@marsh void you can use two loops in one list comp

#

[(i, j) for i in range(w) for j in range(h)]

#

not sure if faster though

#

one cool thing you can do with the invert operator is inverting sequence indexes

>>> def palindromic(sequence):
    for i in range(len(sequence)//2):
        if sequence[i] != sequence[~i]:
            return False
    return True

>>> palindromic('abba')
True
>>> palindromic('abbo')
False
>>> palindromic('aboba')
True
>>> 
#

i like how much semantic sense it makes

#

plus you probably save some cycles over -i-1

marsh void
#

@brazen geyser this one is shorter?

def palindromic(seq):
    return reversed(seq) == seq
brazen geyser
#

the goal wasnt shortness

#

it was a demo of using the ~ operator with indexes

mortal ingot
#

would that really work? doesn't reversed returns an iterator?

candid haven
#

It works, since I tested it yesterday

distant wave
#

seq[::-1] == seq

mortal ingot
#
In [1]: def palindromic(seq): 
   ...:     return reversed(seq) == seq 
   ...:                                                                         

In [2]: palindromic('abba')                                                     
Out[2]: False
distant wave
#
>>> a = "abba"
>>> a[::-1] == a
True
mortal ingot
#

that does beg the question though, what's the shortest way to check palindromeness for any type of iterable?

candid haven
#

mmm maybe I tested it yesterday and I didn't use it because it returned an iterator 😐

#

sorry

mortal ingot
#

no worries

distant wave
#

[*a][::-1] == [*a]

marsh void
#

@mortal ingot wait weird lol

mortal ingot
#

any iterable, including iterators

brazen geyser
#

is the [:] necessary

distant wave
#

no

mortal ingot
#

(though it's probably just a=[*i];return a[::-1]==a or something)

marsh void
#
def palindrome(seq):
    return seq[::-1]==seq
#

hm

sick hound
#

@marsh void nope

#
>>> def test():
...     yield 1
...     yield 2
...     yield 1
...
>>> g = test()
>>> [*g]
[1, 2, 1]
>>> [*g]
[]```
distant wave
#

ugh I forget about that

sick hound
#

the best I can do is py def p(s):l=[*s];return l[::-1]==l

#

wait no

#
def p(s):*l,=s;return l[::-1]==l```
brazen geyser
#

the shortest one is where you add a special palindromic check operator to cpython and use that 😛

sick hound
#

that's cheating though

brazen geyser
#

~a~ coming soon

#

it's not cheating cpython and i have an open relationship

sick hound
#

relationship.close()

#

not any more :P

brazen geyser
#

😠

sick hound
#

now you have a closed relationship

brazen geyser
#

homewrecker

mortal ingot
#

relationship.seek(0)

sick hound
#
ValueError: I/O operation on closed file.```
marsh void
#

relationship jokes? lol

#

@sick hound yeah, I got what is the problem; generator objects, for example, are not subscriptable

brazen geyser
#

relationships: dict

sick hound
#

they're not subscriptable, and if you iterate them twice you might get different things

brazen geyser
#

relationships[self]

#

KeyError

marsh void
#

Lol

#

relationships.clear()

#

what now?

worthy ridge
#

checking an iterator is a palindrom certainly requires casting it into a list or tuple, as checking it forward will consume it, and you don't know the length in advance, and you can't look forward anyway

sick hound
#
from ctypes import*;pythonapi._Py_Dealloc(py_object(meta))```
#

meta has been deallocated now

#

they don't exist

brazen geyser
#

damn thats cold

#

no memory of me left

marsh void
#

def p(s):a=[*s];return a[::-1]==a

#

So yeah, that’s it

sick hound
#

you can make that one character shorter

#

def p(s):*a,=s;return a[::-1]==a

marsh void
#

oh yeah

#

but that’d be tuple, am I right?

sick hound
#

no

worthy ridge
#

damn, that's abusing the unpackaging syntax 😄

sick hound
#
>>> *a, = range(20)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]```
marsh void
#

@sick hound importing * is a sin apparently, even worse than ; in normal code

brazen geyser
#

def p(s): return (a:=[*s])[::-1]==a

sick hound
#

well it's less characters in this case :P

marsh void
#

yep

worthy ridge
#

@marsh void it's not an import of *, it's using the unpacking syntax

sick hound
#
from ctypes import*``` this is an import of `*`
marsh void
#

@worthy ridge lol I know that; was kinda slow; I replied to ^

worthy ridge
#

ah ok

marsh void
#

sorry for inconvenience okhandbutflipped

marsh void
#

Hey guys, really need your help

#
import itertools
a = [*itertools.product(range(1280), range(720))]
b = [*itertools.product(range(10, 100), range(20, 200))]

is there a fast way to remove all elements in b from a?

#

numpy?

edgy kelp
#

something with sets ought to be faster than list manipulation

#

list(set(a)-set(b))

#

but you lose how it was arranged

marsh void
#

yeah, and actually

c = list(set(a)-set(b))
c.sort()

@edgy kelp why not sort it after operation?

edgy kelp
#

not sure how long sets with sort will take compared to some kind of list comprehension

marsh void
#

yeah, that might take long

edgy kelp
#

almost a second on my pc

marsh void
#

it actually did sort quite fast lol

#
>>> a = [*itertools.product(range(1280), range(720))]
>>> b = [*itertools.product(range(10, 100), range(20, 200))]
>>> c = list(set(a)-set(b))
>>> c.sort()

took around a second, even less probably

edgy kelp
#

well second's a lot but trying list comprehension now is taking horribly long compared to that

#

you can replace the initial lists with sets too if you're not doing anything with them

marsh void
#

set comprehension isn't a thing?

edgy kelp
#

just set(itertools.product(range(1280), range(720)))

#

but there is set comprehension with {} iirc

marsh void
#

yeah, didn't know about setcomp tho

edgy kelp
#

still going for least chars?

brazen geyser
marsh void
#

no, not really @edgy kelp

gilded orchid
#

that is a lot of instructions for a stack based language lmao

snow beacon
#

I've given up on implementing a stack based language I designed with two or three modes for almost all of the punctuation. It's a lot of instructions to implement.

#

But once you get into non-ascii?

#

I had enough trouble reading APL.

marsh void
#

@gilded orchid brainfuck is cool tho

gilded orchid
#

yeah

#

but I started hating it after trying to do anything difficult with it

#

for my 6000 character 12 days of Christmas in Brainfuck, I resorted to using python to generate it for me

#

(after a failed attempt doing it in brainfuck myself)

marsh void
#

the good thing is that you can put other chars in code and the get ignored

#

(at least in online compiler tho)

gilded orchid
#

what compiler do you use for brainfuck?

marsh void
#

@gilded orchid why not write your own tho

#

Dunno, just googled and found one online compiler, don’t remember it’s name

gilded orchid
#

I tried writing my own but got stuck at nested loops

#

i'll have another shot at it sometime though

marsh void
#

@gilded orchid can you send a link of bf instructions here? I forgot one of them >.>

gilded orchid
#
>    Move the pointer to the right
<    Move the pointer to the left
+    Increment the memory cell under the pointer
-    Decrement the memory cell under the pointer
.    Output the character signified by the cell at the pointer
,    Input a character and store it in the cell at the pointer
[    Jump past the matching ] if the cell under the pointer is 0
]    Jump back to the matching [ if the cell under the pointer is nonzero
marsh void
#

@gilded orchid kinda don’t get what , does

worthy ridge
#

let user type a character? like input() in python, but limited to one char

#

i don't get what's interesting about writting brainfuck (or ook or whichever equivalent) code, sure, it's neat to know it's turing complete ande hence you can write any program in it, but why would you? if you want a very constrained env, you can write assembly code, or try to do parallelized code in gpu, or serverless code using distributed erlang code, things where the constraint brings you something

#

at least piet code is nice to look at

gilded orchid
#

Basically brainfuck programmes can have an input buffer, and , takes the ascii value of that input and puts it onto the current cell. Then that input gets removed from the input buffer

#

@worthy ridge because it’s a fun challenge, and it’s a difficult logic puzzle (at least that’s why I like brainfuck)

marsh void
#

@gilded orchid ok in my mind I have implementation of around 40-50 lines of code

marsh void
#

@worthy ridge I would say, esolangs are made for fun, and saying "why would you?" is not a very good question here imo.

worthy ridge
#

probably

#

i mean, there is no shortage of interesting problems, i rarely see a point in making them harder, but that might just be me

marsh void
#

Hey guys, how can I modify variable with exec?

#
def run():
    out = ""
    exec("out += '0'")
    print(out) -> ""
    # I'd like it to be "0" that way
brazen geyser
#
>>> exec('a = 5', globals(), locals())
>>> a
5
>>>
marsh void
#
>>> def run():
...     out = "0"
...     exec("out+='1'", globals(), locals())
...     print(out)
>>> run()
0

@brazen geyser

brazen geyser
#

hmm

#

thought locals would take care of that

candid haven
#

is this cheating? py def run(): out = "0" _locals= locals() exec("out+='1'", globals(), _locals) out = _locals["out"] print(out)

marsh void
#

@brazen geyser lol I was pissed off and have just written a class that holds that variable

marsh void
#

@gilded orchid

NeKitDS $ bf

++++++++++++[-<+++++>]<.
p+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
while arr[p]:
arr[p]-=1
p-=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
p+=1

p-=1
store.output+=chr(arr[p])

Output: '<'

So yeah, it works but it’s kinda bad at indentation

frank hazel
#

@marsh void bf -> python compiler?

frank hazel
#

I made a thing

#
from collections import*
from operator import*
from functools import*
f=defaultdict(int)
def q(n):
 f[n]+=1
 for x in filter(partial(gt,n),[0,1]):q(n-x-1)
 return n
for i in range(q(int(input())),0,-1):print(f[i])
#

I made an esoteric fibonacci

#

and then golfed it, I guess

frank hazel
#

wait I can obfuscate this more

#

boom now it's more unreadable

marsh void
#

@frank hazel yeah, bf -> python compiler

frank hazel
#

nice

#

I think I did one of those a long time ago

marsh void
#
NeKit $ bf
>++++++++[-<++++++>]<+..-.+.
.bf -> .py
p+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
arr[p]+=1
while arr[p]:
    arr[p]-=1
    p-=1
    arr[p]+=1
    arr[p]+=1
    arr[p]+=1
    arr[p]+=1
    arr[p]+=1
    arr[p]+=1
    p+=1
p-=1
arr[p]+=1
store.output+=chr(arr[p])
store.output+=chr(arr[p])
arr[p]-=1
store.output+=chr(arr[p])
arr[p]+=1
store.output+=chr(arr[p])
-----Output-----
1101
frank hazel
#

nice

#

it doesn't just print the output?

marsh void
#

Fixed indentation

#

Wdym print output?

frank hazel
#

you're adding to store.output (which isn't even defined in the code?) instead of printing

#

p and arr aren't defined either

marsh void
#

It is not actual code

#

Lemme send the real one (it’s bad tbh)

frank hazel
#

ye but the outputted code isn't valid

#

what's the point compiling to invalid Python

marsh void
#

Ok so I needa write so people can copy+paste code that was compiled and it can run? @frank hazel

frank hazel
#

I would do that

marsh void
frank hazel
#

nice

#

arr could be a defaultdict so it's infinite

#

defaultdict(int)

marsh void
#

Okay

#
NeKit $ bf test.bf
.bf -> .py
from collections import defaultdict
p = 0
arr = defaultdict(int)
output = ""
... # compiled BF code goes here

@frank hazel okay updated ^

frank hazel
#

nice

marsh void
#

@frank hazel ok some actual program up here ^
also, added new command:
$ - add value of ceil to output
e.g. >+$<$ -> 10

gilded orchid
marsh void
#

Let me see

#

My terminal lagged a bit, I need to make debug: bool thing for it not to print stuff

gilded orchid
#

It's meant to output the lyrics to the song 12 Days of Christmas, but I accidentially used the wrong new line char (I used 13 instead of using 10 lmao)

marsh void
#
On the First day of Christmas
My true love sent to me
A Partridge in a Pear Tree.

On the Second day of Christmas
My true love sent to me
Two Turtle Doves, and
A Partridge in a Pear Tree.

On the Third day of Christmas
My true love sent to me
Three French Hens,
Two Turtle Doves, and
A Partridge in a Pear Tree.

On the Fourth day of Christmas
My true love sent to me
Four Calling Birds,
Three French Hens,
Two Turtle Doves, and
A Partridge in a Pear Tree.
... # discord char limit
On the Twelfth day of Christmas
My true love sent to me
Twelve Drummers Drumming,
Eleven Pipers Piping,
Ten Lords-a-Leaping,
Nine Ladies Dancing,
Eight Maids-a-Milking,
Seven Swans-a-Swimming,
Six Geese-a-Laying,
Five Gold Rings,
Four Calling Birds,
Three French Hens,
Two Turtle Doves, and
A Partridge in a Pear Tree.
gilded orchid
#

wow it actually works lmao

marsh void
#

It did print :)

#

Yeah lol

#

I can give you the interpreter code if you’d like (it’s quite messy rn)

gilded orchid
#

ok

#

If you're wondering how it works, it basically multiplies the number 32 over around 200 different cells, then it goes through all of them and adds/subtracts to make them into the correct number, so the cells are formatted (numbers for string, 0, numbers for other string, 0, etc.)

#

then I spam [.>] and [<] to print them all in order

#

i'm gonna try and golf a brainfuck to python compiler

marsh void
#

@gilded orchid full file, that can be used in terminal ^

gilded orchid
#

ok thanks

marsh void
#

np, have fun :)

marsh void
#

@gilded orchid I’m looking for a way to detect if a brainfuck loop is while True:... any suggestions?

snow beacon
#

That is impossible.

#

Look up the halting problem for info as to why.

gilded orchid
#

I don’t really know how you’d do that

frank hazel
#

it actually is impossible

#

it's the halting problem, exactly

#

@marsh void basically, it comes down to if it were possible to do that it would be possible for any program, including the program that checks if the loop goes forever

#

so you can make a program that checks itself to see if it goes forever

#

if the answer is yes, end the program

#

if the answer is no, loop forever

#

no matter what the answer is wrong

#

so the program that checks if the program loops forever does not exist

snow beacon
#

You can check if the program exactly repeats itself

#

Or simple things like a monotonically increasing cell

#

(That last one would actually be pretty difficult. You'd need to be sure that it doesn't affect other cells.)

#

But for the former you can just store a bit of a history of program states, and if the program repeats itself exactly, break.

marsh void
#

oh

#

okay

gilded orchid
#

although I probably won’t be able to do it

marsh void
#

How the fuck should brainfuck in brainfuck work? @gilded orchid

gilded orchid
#

a couple of them already exist lmao

#

I have an idea of how I'm gonna do everything

#

so basically I'm gonna start of taking input, which will consist of, using , (obviously) and then repeatedly subtracting from it to work out what brainfuck command (if any) it is

#

then I'm gonna split the into into lots of 8 bit chunks, where each bit coreesponds to a command

#

and between each 8 bit chunk there's gonna be an empty gap, which I can put 255 into

#

255 will represent where it is in the program (and you can always jump to it by using +[->+]-)

#

and then I'll have the cells, which will be 2 cells each

#

one of the cells will be that cell's value when running the brainfuck programme, and the other one will be either 0 of 254 (254 represents the position in the cells)

marsh void
#

So you need to have an other Lang interpreter already to execute interpreter of brainfuck

gilded orchid
#

yeah basically lmao

marsh void
#

Lol

#

@gilded orchid +[,] ok how to exit this

gilded orchid
#

wdym?

marsh void
#

lol

#

So, basically, it runs forever until you enter a chr(0)?

gilded orchid
#

depends on what implentation of brainfuck you're using

marsh void
#

hm

gilded orchid
#

wait no i'm dumb

marsh void
#

😂

gilded orchid
#

yeah you would have to enter a null character for that to end

marsh void
#

@gilded orchid I mean, do you take inputs with ,, and then execute them?

gilded orchid
#

no, I'm gonna take all the inputs and then execute after that

#

because executing them straight away wouldn't work for [ or ]

marsh void
#

Okay, then how?

gilded orchid
#

I haven't actually started doing it yet but I've planned it out

#

I think + will be +[->+]->+ because +[->+]- will jump to the current cell and then it'll just add to it

marsh void
#

@gilded orchid I found this (not mine):

>>>,[>++++[-<-------->]+<-[----------[>]>[<+<+>>>>]<<<-[>]>[<+<+>>>>]<<<-[>]>[<+<+>>>>]<<<-[>]>[<-<+++>>>>]<<<--------------[>]>[<++<+>>>>]<<<--[>]>[<-<+++++++>>+>>]<<++++[-<------>]+<+[>]>[<++<+>>>>]<<<--[>]>[<<+>>>>]<<-<[+]<[>]>,>]<]>>[->]>+<<<<-[<]>[-[<<]>[<+[>]>>[<]<<[>>+[<<[<]<<-[>>]<[>>>>[>]>+<<[<]<]<-[>>]<[>>>>[>]>-<<[<]<]<++[->>+<<]>>[>]>]<]<[<]>-<]>-[<<]>[<++[>]>>[<<]>[<<+[<<[<]>[-<<+>>]>--[<<]>[[>]>+<<[<]<]>+[<<]>[[>]>-<<[<]<]>+[>]>]]<<[<]>--<]>-[<<]>[[>]>>.<<<[<]<]>-[<<]>[[>]>>-<<<[<]<]>-[<<]>[[>]>>,<<<[<]<]>-[<<]>[[>]>>+<<<[<]<]>-[<<]>[[>]>>>[>>]>[<<<[<<]<+>>>[>>]>-]>[-]<<+[<[->>+<<]<]<[->>+<<]<[<]<]>-[<<]>[[>]>++[-->[-<<+>>]>]+<<-[++<<]<[->>>[>>]>+<<<[<<]<]<[<]<]<++++++++>>[+<<->>]>]
#

In my implementation raises IndexError if I give it \n

fallow cairn
#

Ooh make a programming language that compiles to brainfuck

#

It would have to be basically brainfuck but readable with comments and ascii as ints, ontop of a "smart array" system that groups stuff together over the virtual 30 something array you have in brainfuck

wind maple
#

you mean like

#

most languages

#

you can transpile e.g. python to brainfuck

marsh void
#

@fallow cairn any ideas how to make this work even if user hits enter?:
input(": ")[0]

wind maple
#

sys.stdin.read()

marsh void
#

Oh yeah

fallow cairn
#

getchar()

marsh void
#

this ain’t python lol

wind maple
#

getchar() isn't a standard function

fallow cairn
#

It is C though

marsh void
#

^

wind maple
#

oh right

#

this is a python guild >:(

marsh void
#

sys.stdout.read() gets one character?

wind maple
#

no it gets the whole junk

#

use read(1) for one byte

fallow cairn
#

I think you mean char?

#

Seeing unicode is 3 bytes

marsh void
#

sys.stdout.read(1)?

#

sys.stdout.read()[0] maybe? @wind maple

wind maple
#

I have no idea what the goal here is

#

, in BF is basically the same as doing os.read(sys.stdin.fileno(), 1)

gilded orchid
#

I find it absurd that Slashes (https://esolangs.org/wiki////) has been proved to be turing-complete despite the fact that it only has string replacement

marsh void
#
NeKitDSS $ bf --debug p.bf
-----Input-----
, # get input
. # print input
[-] # clear cell
.bf -> filter
,.[-]
.bf -> .py
from collections import defaultdict
p = 0
arr = defaultdict(int)
output = ""
def f(k):
    n = input(f"In [#{k}]: ")
    return chr(0) if not n else n[0]
arr[p]=ord(f(p))
output+=chr(arr[p])
while arr[p]:
    arr[p]-=1
print(output)
In [#0]: 2
-----Output-----
2
sick hound
#

@gilded orchid the thing is, you can replace text with more string replacement

fallow cairn
#

👏 @marsh void

#

I want to make that programing language a reality

#

Need some syntax ideas though

#

It will basically be a improved brainfuck that compiles to the original

marsh void
#

@fallow cairn wym compiles to the original?

fallow cairn
#

Transpiles back to brainfuck

#

But I want to add a complicated mechanism so it makes a shit load of brainfuck

marsh void
#

Hm I have ideas how to improve BF, but it won’t be translatable back

fallow cairn
#

Like a function has to be duplicated in brainfuck text over and over whenever compiled

#

Like to make the ir (brainfuck) much larger in source then original

#

Basically make a monstrosity that is nice to work with and makes very, very ugly brainfuck

#

Like py x=0 for i in range(3): add(x) def add(x): x += 1 Would have to have the add function duplicated every time it ran

#

:D

edgy kelp
#

NameError: name 'add' is not defined

marsh void
#

^

#

LOL

fallow cairn
#

Shh

#

"Pseudocode"

marsh void
#

>+++[-<+>]< @fallow cairn monstrosity?

gilded orchid
#

^ why lmao

fallow cairn
#

You know what I mean

#

I gave a bad example

marsh void
#

Yeah I know @fallow cairn

#
a = 3
b = 4
print(a==b)
#

In Bf

fallow cairn
#

Functions that go into other functions and recursion would be fucking annoying

#

And would make the source code massive for something other then like the hello world of bf

#

Well time to learn basic bf!

marsh void
#

@fallow cairn bf I simple, you just need to keep track of what cell are you pointing at

fallow cairn
#

Yep

gilded orchid
#

(and also nested loops can get kind of insane so you need to keep track of that lmao)

marsh void
#

^

gilded orchid
#

even printing out a 3 digit number from a cell is difficult

fallow cairn
#

Or strings

gilded orchid
#

strings are relatively easy compared to printinng out a number from a cell

#

because you need to do division and modulo only using +1 and -1

fallow cairn
#

Right

#

I need to learn language dev

#

Then i'll do it

#

I can't think straight right now, way too tired 😅

gilded orchid
#

just to prove a point

[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]
>>>[>>+<<-]>>>>++++++++++<<
[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>>>>>
++++++[>++++++++<-]>[<<+<+<<<<+>>>>>>>-]
<<<<<<<.>>>>>.<.

this prints a 3 digit number from a cell (assuming you have [number, 0, 100] and your pointer is on the number)

marsh void
#

@gilded orchid I don’t think that you stoled it tbh, just took it lol

gilded orchid
#

yeah I guess

#

I have 0 clue how it works though

wind maple
#

@gilded orchid that was actually kind of a problem in a coding competition I took part in

gilded orchid
#

oh wow

marsh void
#

nice okhandbutflipped

wind maple
#

we had to create a program that would determine whether a string could be constructed by repeating a smaller string n times

#

using only x->y string substitution

#

e.g. k=2 and the string is 1010 would output true

#

but 0110 would output false

marsh void
#
+[,]
# Transpile update: Hitting Enter on input sets the cell to 0
gilded orchid
#

also storing/doing arithmetic number above 255 is a nightmare (assuming you're using an implementation that wraps around)

#

I think you'd either have to store it in binary or store it in base 255

snow beacon
#

All this talk of compiling to brainfuck makes me thing of my original goal for my compiler to Subleq: make really incomprehensible code from much nicer code.

#

It's technically finished, but I'm going to keep adding macros.

silk yew
#

Im afraid of the darkness in the soul of all of you

frank hazel
#

@fallow cairn sounds good, consider checking out other projects that try to do the same thing

#

brain comes to mind

#

also me and two others tried to do this with a language based on C

fallow cairn
#

Dude I still have to learn it :P

frank hazel
#

maybe you can get further than everyone else

fallow cairn
#

¯_(ツ)_/¯

#

Gave myself 2 weeks to learn how to make a very basic language

#

Like very basic

frank hazel
#

how basic

fallow cairn
#

A fancy print statement and maybe vars

#

(Addition/subtraction ofc)

frank hazel
fallow cairn
#

Damn

#

500 lines

#

Ok how the fuck did you make this when you where 12

#

@frank hazel

frank hazel
#

shrug

fallow cairn
#

Chirst

gilded orchid
#

Not really related but how were you able to get your language added to tio.run? @frank hazel

frank hazel
#

@gilded orchid asked the creator, he lets anyone add their lang

#

use the code golf stack exchange chat

gilded orchid
#

You need 20 reputation for that

#

rip me

#

How do you actually get reputation on stack Exchange?

frank hazel
#

get upvoted

#

mainly

#

10 rep a pop

snow beacon
#

Ah, that's what I've been doing wrong.

marsh void
#

@gilded orchid woah that brainfuck in brainfuck actually works with my new transpiler:

In [#3]: +
In [#4]: [
In [#5]: ,
In [#6]: .
In [#7]: ]
In [#8]: 
In [#10]: a
In [#10]: b
In [#10]: c
In [#10]: 
-----Output-----
abc
#

On #8 I hit Enter

#

Also takes exclamation mark as an end of input

frank hazel
#

@marsh void why is the input that way?

marsh void
#

@frank hazel what? You can’t input more than one char per cell

#

It is brainfuck in brainfuck

frank hazel
#

oh I see

#

that can probably be done without having to put them in one at a time

sick hound
#

What if you write a python compiler in brainfuck and a brainfuck compiler in python

gilded orchid
marsh void
#

@sick hound python compiler in brainfuck? Think about this shit first

gilded orchid
#

(I think it was a joke)

marsh void
#

It doesn’t matter honestly lmao

#

According to bf, pi=4

snow beacon
#

You can simulate decimal math. It's Turing complete

marsh void
#

@snow beacon while being Turing complete, it takes hella shit amount of time to calculate something

wind maple
#

why did this channel turn from esoteric python into brainfuck

tropic gulch
#

juanita wasn't there

#

no alpha-alpaca to lead the herd

marsh void
#

@wind maple don’t know honestly

frank hazel
#

somewhere down the line it turned into esolangs

#

iz ok I got it

#
from collections import*
from operator import*
from functools import*
f=defaultdict(int)
def q(n):
 f[n]=-~f[n]
 for x in filter(partial(gt,n),[0,1]):q(~-n-x)
 return n
for i in range(q(int(input())),0,-1):print(f[i])
#

boom new and improved obfuscated-golfed fibonacci thing

brisk zenith
#

i'm back from being away from home, and ava makes a good point. your esolang projects are cool, but i think it's best to get this channel back to being true #esoteric-python. :D

marsh void
#
while not print("Hello", end=" "):
    print("World!")
gilded orchid
#

Would esolang projects be good for the off topic channels? @brisk zenith

marsh void
#

@gilded orchid I’m guessing so :)

brisk zenith
gilded orchid
#

If it’s something we created in an esolang, and not an esolang written in python, would it be ok for #303934982764625920?

brisk zenith
#

not really, no.

grizzled cloak
#

@marsh void that will never exit the loop right?

marsh void
#

@grizzled cloak sorry for long reply, yes.

#

Because bool(None) is False

grizzled cloak
#

yeah

marsh void
#

I’m still not sure if a while True loop will actually run forever

grizzled cloak
#

But it will never exit

marsh void
#

yes

wind maple
#

so if it has no exit condition it will run forever

#

case closed

gilded orchid
#

(unless it increases memory usage each time, meaning it’d eventually run out of memory)

wind maple
#

well

#

in a theoretical world that argument doesn't work

#

computers wouldn't be turing complete if you account for the fact that they have limited memory

#

but we say they are because, well, for all intents and purposes they are

#

so for all intents and purposes a while True loop does indeed go on forever

#

in practice no if you were to do something silly like allocate 10gb of memory each iteration

#

but if you just no-op each time then you will indeed run "forever"

#

until your machine fails

marsh void
#

yep

formal sandal
#

@frank hazel

n,a,b=[],[],[[]]
for i in b*int(input()):n=[n]
while n:print(len(b));a,b,n=b,[*a,*b],n[0]
#

@grizzled cloak
[0, [...]]

fallow cairn
#

Ew

#

Ew

frank hazel
#

@formal sandal thanks, it's even more awful

wind maple
#

have you seen my list comp one

formal sandal
#

@frank hazel python eval('exec("n,a,b=[],[],[[]]\\nfor i in b*int(input()):n=[n]\\nwhile n:print(len(b));a,b,n=b,[*a,*b],n[0]")')

#

It seems i'm good at making terrible and unreadable code.

#

My favorite on is the Brainfuck interpreter

import sys
for p in sys.argv:
 s,a='',[0]*32;j=t=0
 for i in p:s+=' '*t+['j-=1','a[j]+=1','j+=1','a[j]-=1','print(chr(a[j]),end="")','while a[j]:',0,'',0,0][ord(i)%18-6]+'\n';t+=(i>'Z')-2*(i>'[')
 exec(s)
frank hazel
#

good, that sucks

formal sandal
#

It's 204 characters long, and someone figured out how to make it 118 characters long.

#

I feel helpless.

fallow cairn
#

The slowest bf interpreter :D

marsh void
#
++[>+++++[>+++++++>+++>++++++++++<<<-]<-]>>+.>>[>+>+<<-]>>[<<+>>-]<<+.++++++++++.--.>+.<+++++++.--.+++++++.<++.[-]<---.[-]>>>----.<------.[-]>+++++++.[-]
#

Here’s the name of one of my favorite games

formal sandal
#

[+]

marsh void
#

@formal sandal oh shit here we go again

#

also, it doesn’t do anything

#

+[+] is the real deal

formal sandal
#

Right.

marsh void
#

+[-+] this is more sad

brisk zenith
worthy ridge
#

the size of code is really the worst metric one could think of to judge a software on

snow beacon
#

I don't know about that. If your storage capacity is limited, you don't want your code taking up much space.

distant wave
#

Larger code takes longer to read, from a certain point onwards

gilded orchid
#

If it’s really short code then it could become very unreadable

snow beacon
#

Code golf is to programming what poetry is to literature.

#

Poems are useful ways of conveying information when you have limited pages. Golfed code is the same for pages of memory.

formal sandal
#

@distant wave Not really. Well, technically, a shorter piece of code might be faster to literally read, but it might take a lot of time to process it.

#

A poem might be short, but the shorter the poem is for the same amount of meaning, the harder it is to understand.

#

And there are also awful poems.

marsh void
#

And there are awful short codes

snow beacon
#

Seems more and more like a good analogy to me.

formal sandal
#

Many poets die at the age of 27.

#

Likewise, ninja coders die at 27 because their colleague programmers are so pissed off.

marsh void
#

@snow beacon same

#

@formal sandal ninja code yes

#

I’m kinda having a strange feeling when typing help('modules') in IDLE

gilded orchid
#

I challenge you guys to obfuscate the number 0 the best you can

#

I came up with [not[[]]][not[[]]]

#

or, even better, [[[[not[[]]]]]][not[[]]][not[[]]][not[[]]][not[[]]]

marsh void
#

Hm

#

int(bool(print("I can't obfuscate things the best")))

gilded orchid
#
>>> not[]
True
>>> not[[]]
False

🤔

hot crypt
#
def _(__):
    return (lambda _ : _.__code__.co_argcount)(__)

def __():
    return 1
    
_(__)```
polar plover
#
(globals().__setitem__("sys",-1),len(__import__("sys").argv)+sys)[sys]```
marsh void
#
(globals().__setitem__("sys",-1),len(__import__("sys").argv)**0+sys)[sys]```
@polar plover (so it’s going to be always 0, no matter how many args there are)
polar plover
#

hmmmmm,,,,,,, no xD

marsh void
#

Explain

polar plover
#

ohh wait, you changed it

#

thought you meant mine

#

yes yours will always be 0

#

from what I can see

marsh void
#

yup

#

And your won’t always be 0

#

stupid python, thinks that 0**0=1

#

But len(sys.argv) won’t be equal to 0 though

#

Or can it be 0?

#

Kinda interested 🤔

polar plover
#

it's always 1 or more, that's why I have the + (-1)

#

I think

marsh void
#

Yeah

#

But your was good @polar plover

polar plover
#

I knew that it would not always be 0, but never thought of the **0

marsh void
#

Same

#

I was kinda sitting trying to think of how to operate on x to make it equal to 1

polar plover
#

I got another idea: py (<super long code to get any number>) * 0

marsh void
#

Oh yeah **0 is not cool

#

*(1-1)

#

*len([])

hot crypt
#

int(str(ord(str(type(1))[0]))[1]) 🤔

marsh void
#
import sys
from collections import defaultdict
class Container:
    def __init__(self):
        self.output = ""
    def clear(self):
        self.output = ""
store = Container()
def run(code: str):
    p, indent = 0, 0
    arr = defaultdict(int)
    pycode = (
"""def f(k):
    n = input(f"In [#{k}]: ")
    return chr(0) if not n else n[0]
"""
    )
    rdict = {
        "+": "arr[p]+=1",
        "-": "arr[p]-=1",
        ">": "p+=1",
        "<": "p-=1",
        ".": "store.output+=chr(arr[p])",
        ",": "arr[p]=ord(f(p))",
        "?": "print('Array:', list(arr.values()))",
        "[": "while arr[p]:",
        "]": ""
    }
    code = "".join(filter(lambda x: x in rdict.keys(), code))
    for char in code:
        n = check_char(char)
        pycode += " "*(indent*n) + rdict[char] + "\n"*n
        indent += decide_indent(char)
    exec(pycode)
    output = str(store.output)
    store.clear()
    return output

def decide_indent(char):
    if char == '[':
        return 4
    elif char == ']':
        return -4
    else:
        return 0

def check_char(char):
    return (0 if char == ']' else 1)

# actual 0
int(run(">++++++[<++++++++>-]<."))

obfuscated? sorry for my brainfuck reference

scarlet osprey
#

True + True + true

#
  • True + False -True + False
formal sandal
#
(globals().__setitem__("sys",-1),len(__import__("sys").argv)**((globals().__setitem__("sys",-1),len(__import__("sys").argv)**(globals().__setitem__("sys",-1),len(__import__("sys").argv)**((globals().__setitem__("sys",-1),len(__import__("sys").argv)**(globals().__setitem__("sys",-1),len(__import__("sys").argv)**((globals().__setitem__("sys",-1),len(__import__("sys").argv)**0+sys)[sys])+sys)[sys]+sys)[sys])+sys)[sys]+sys)[sys])+sys)[sys]```
marsh void
#

@formal sandal it’s literally a pattern

#

And it has 0 so not cool

#
len(__import__('asyncio').get_event_loop()._scheduled)```
#

I’ve been working on some async stuff so there you go

worthy ridge
#

N ** 0 = 1 is a mathematical truth, for any value of N, so not sure what python could do else

#

we couldn't count to 1 in binary if 1**0 wasn't 1 😆

#

(or in any base, of course)

earnest wing
#

0 ** 0 depends on context, but it too is commonly held as 1.

snow beacon
#
b=b"~"
t=tuple(b)
f=lambda:[*[hash(s[3:2])]*3,3*2,2**2**2**2*2]
function = type(f)
code = type(f.__code__)
def a():
    f.__code__=code(*f(),c.co_code,t+c.co_consts[1:-1]+t,c.co_names,(),s,s,b[-1],b)
s='''if int(False):
    try:
        from ctypes import*
        x=int(input("Enter a single whole number, between 5 and any other number: "))
        assert x!=5
    except:
        x=id(12).bit_length()
    i=input("Now enter another integer: ")
    z=bool(...)if(~x*i*x)else sum(abs(v) for v in(x.imag,i.find(i)))
else:
    f()'''
c=compile(s,s,s[81:-238])
function(c,{"int":bool,"f":a},s,t,())()
zero=max(sum((-f(),*t))**2, z)
print(zero)```
Prompts for some irrelevant input, then prints 0
#

If you can work out the control flow, I commend you.

#

I'm certain Python wasn't designed to do this.

worthy ridge
#

i don't know of any context in which 0 ** 0 is not 1, but i'm no mathematician

#

i'm confused at line 2 already 😆

#

ah, right

wind maple
#

this is only true for the real number line

#

which is why for most practical purposes (i.e. programming languages) it's commonly just defined to be 1

brisk zenith
#

but python has complex numbers builtin yert

worthy ridge
#

well, to be fair 0 is on the real number line

cunning wave
#

thats...not really the point of ava

wind maple
#

lim x->0 of x^x doesn't work anymore in the complex plane

gilded orchid
#

Recently in a code golf, I saw someone use ’@‘<b<‘[‘. How do greater then or less than comparisons work with strings like this?

kind hazel
#

ord("@") == 64
ord("[") == 91

#

its kinda similar to the way strings are sorted

gilded orchid
#

Oh ok, so it's based on their ascii value

#

How do comparisons work with strings that have more then 1 character?

wind maple
#

like tuples

#

first compare index 0

#

then index 1

#

etc

gilded orchid
#

Would it return true if one of them passes the comparison?

wind maple
#

wdym

#

e.g. 'abc' < 'abx' is basically the same as 'a' < 'a' or 'b' < 'b' or 'c' < 'x'

gilded orchid
#

would that return a tuple of booleans?

wind maple
#

no

gilded orchid
#

would it be True if all of them are True, and false otherwise?

wind maple
#

wait oops I meant to use

#

or

#

fixed

gilded orchid
#

Oh ok, that makes sense now, thanks

snow beacon
#

You know when you alphabetise a list of names, you start with "aardvark" then "aargh" and then "alphabet"? It's like that. "aa" < "ab" < "ba" < "bb"

#

That's how I think of it.

hot crypt
#

i just learned about vars(). what other horrid things can you do aside from vars()["a"] = -5?

calm rampart
#

vars() is nerfed in python 3

#

outside of class definitions and modules (where it just returns the normal dictionary), it's just a copy now

gilded orchid
#

isn't locals() also a copy?

#

whilst globals() isn't a copy

sick hound
#
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined
>>> c
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'c' is not defined
>>> locals()['a'] = 5
>>> a
5
>>> globals()['b'] = 5
>>> b
5
>>> vars()['c'] = 5
>>> c
5```
gilded orchid
#

is vars() based on the current scope?

#
>>> vars()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}
>>> def test(x):
    print(vars())

    
>>> test('abc')
{'x': 'abc'}
formal sandal
#

Without an argument, vars() acts like locals(). Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.

#

Hmm...

gilded orchid
#

oh ok, I was just wondering because I was trying to do assignment in a lambda with locals().update a while ago, and it didn't work

#
>>> a=lambda x:(locals().update({'hello':'test'}),print(hello))
>>> a(123)
Traceback (most recent call last):
  File "<pyshell#107>", line 1, in <module>
    a(123)
  File "<pyshell#106>", line 1, in <lambda>
    a=lambda x:(locals().update({'hello':'test'}),print(hello))
NameError: name 'hello' is not defined
formal sandal
#
a=lambda x:(locals().update({'hello':'test'}),print(locals()['hello']))```
#

works, though.

formal sandal
#

I get it.

#

Since hello is not in lambda's args, it is taken from the outer scope.

#

That makes sense.

sick hound
#
>>> [lambda x: i * x for i in range(5)][0](2)
8
>>> [(lambda i: lambda x: i * x)(i) for i in range(5)][0](2)
0```
calm rampart
#

vars() is basically locals(), the only difference is you can also do vars(obj) to get that object's dictionary

#

@formal sandal locals at the top level is just the module dictionary, it works fine in modules and classes.

formal sandal
calm rampart
#
>>> a=lambda x, loc:(loc.update({'hello':'test'}),print(hello))
>>> a(123, locals())
test
(None, None)```
formal sandal
#

Yes, it's because you give the lambda the ability to change the locals of the outer scope, and lambda's locals are its parameters.

#

Do I understand it correctly?

calm rampart
#

well

#

only because the outer scope is the module

#

it still wouldn't work within a function

#

locals isn't very interesting at the module level because it's the same as globals - where it's interesting is in the class initializer

#

because there, it is the dict that is being used to prepare the class (which isn't the same as the class dict - it's copied when the class is constructed, because it has to be read-only for obscure cpython reasons)

sick hound
#

huh, that's interesting

#

it's a mappingproxy ```py

Test.dict
mappingproxy({'module': 'main', 'dict': <attribute 'dict' of 'Test' objects>, 'weakref': <attribute 'weakref' of 'Test' objects>, 'doc': None})```

calm rampart
#

yeah, a mappingproxy is just a wrapper around a dict that doesn't let you set any of its values

#

they added it in, i think python 3.3, someone found a way to make the interpreter crash by overriding magic methods with invalid functions or something

marsh void
#
>>> help(vars)
Help on built-in function vars in module builtins:

vars(...)
    vars([object]) -> dictionary
    
    Without arguments, equivalent to locals().
    With an argument, equivalent to object.__dict__.

so this is what vars() is anyway

gilded orchid
brisk zenith
#

yep absolutely

tepid pulsar
#

what's the challenge 🤔

brisk zenith
#

i was supposed to put one up 5 days ago but i was very busy and stuff

#

i'll do that soon, i promise. :)

tepid pulsar
#

oh neat

brisk zenith
#

yeah some of them are almost a year old by now, but i'll be happy to accept submissions for any challenge from anybody at any time. :)

sick hound
#

random challenge: starting with this, call the function a and exit with an exit code of 19. py from ctypes import* def a():print('you win') py_object.from_address(id(locals())+sizeof(c_ssize_t)).value=int

#

i can do it in 245 characters

marsh void
#

That’s some challenge

brazen geyser
#

are there any other rules/restrictions?

#

just try and make it as jank as possible?

sick hound
#

everything you write has to be after the code

#

no reading stdin, file i/o, sockets, or anything weird like that

#

standard library only

brazen geyser
#

can you explain wtf py_object.from_address(id(locals())+sizeof(c_ssize_t)).value=int is actually doing

sick hound
#

it turns locals() into an int

marsh void
#

which is sad

brazen geyser
#

it turns locals()... into an it?

#

int

#

?

sick hound
#

yes

#

there's one specific internal value in locals() that says "this is a dict"

#

this program overwrites that to make it an int

brazen geyser
#

your evil

marsh void
#

yes

sick hound
#

you need to either get a out without using locals(), or turn it back into an int

#

either way, you can't access the actual values in locals() unless you turn it back, because it's an int

brazen geyser
#

thats disgusting

#

why would you do this

sick hound
#

why not

#

it's meant to be esoteric and hard to do

brazen geyser
#

rhetorical question 😛

sick hound
#

does anyone want to see my solution

brazen geyser
#

yes

sick hound
#

who? :P

brazen geyser
#

someone im sure 😛

sick hound
#
().__class__.__base__.__subclasses__()[69].load_module('builtins').__import__('code').interact('',lambda _:'from ctypes import*;import sys;l=sys._getframe(6).f_locals;py_object.from_address(id(l)+sizeof(c_ssize_t)).value=dict;l["a"]();exit(19)')```
brazen geyser
#

what is wrong with you

#

what the hell is interact

sick hound
#

it creates an interactive python console

brazen geyser
#

oh my god

sick hound
#

but it lets you specify the input function

#

that's what lambda _:'from ctypes import*;import sys;l=sys._getframe(6).f_locals;py_object.from_address(id(l)+sizeof(c_ssize_t)).value=dict;l["a"]();exit(19)' is

#

().__class__.__base__.__subclasses__()[69] is actually the class _frozen_importlib.BuiltinImporter

#

...now that I think about it, I could probably just get the right importer out and tell it directly to load code

marsh void
#

Using l as a variable... Now THAT is wrong

sick hound
#

yep, that worked, 236 characters py ().__class__.__base__.__subclasses__()[82].find_module('code').load_module().interact('',lambda _:'from ctypes import*;import sys;l=sys._getframe(6).f_locals;py_object.from_address(id(l)+sizeof(c_ssize_t)).value=dict;l["a"]();exit(19)')

#

ok, i'll change it