#esoteric-python

1 messages · Page 74 of 1

sick hound
#

@rugged sparrow @wild cairn that actually changes the type of a to None instead of doing anything at all with a subclass ._.

wind maple
#

subclassing None makes no sense since it's a singleton 🤔

#

just like subclassing true or false doesn't make sense

#

but none is different in the sense that where true and false are just types of booleans, none is not

rugged sparrow
#

Yeah I thought that's what it was doing. Never went through my notes tho

snow beacon
#

Is it possible with a metaclass, perhaps?

#

Nevermind. Brain not working.

pure dew
#

ya'll remember that random text generator challenge?

snow beacon
#

No?

distant wave
#

The one for the code jam?

#

I (ab)used the secrets module for that one

sick hound
#

There was a random text generator challenge for this channel once was there not

#

I think Shawn posted it

#

Yeah it was the second challenge we had, after the reverse Polish notation one

pure dew
#

i found the challenge i wrote in coco; the whole thing was one lambda

#

and it produced pretty sensible results

grizzled cloak
#

fun little challenge:

you are trying to remember phone numbers but cant remember the long number! in order to fix this you have decided to split the phone number into smaller numbers. however its hard to remember numbers that start with a leading zero. so you split them into groups of 2-4 digits with as few blocks having leading zeros as possible.

e.g.
01365400606 >> 0136 5400 606```
#

doesn't matter how many groupings just that as few of them start with a zero as possible.

#

i had quite a hard time coming up with a way to solve this but it was fun

zealous widget
#

i have a golfed partition function saved

#

i think it makes that problem trivial though

#

not promising it's an efficient solution though

#

theres 678570 partitions of an 11-digit number

#

but only 556711 of those partitions have no groupings greater than 4

#

oh, partitions consider every order though, we can reduce more

grizzled cloak
#

@zealous widget is there a function to get all partitions?

zealous widget
#
def partition(collection):
    if len(collection) == 1:
        yield [collection]
        return

    first = collection[0]
    for smaller in partition(collection[1:]):
        # insert `first` in each of the subpartition's subsets
        for n, subset in enumerate(smaller):
            yield smaller[:n] + [[first] + subset] + smaller[n+1:]
        # put `first` in its own subset
        yield [[first]] + smaller

this is ungolfed version

#

that yields all partitions

#

this is golfed, but doesn't accept arbitrary iterables and it prints instead of returns:

def f(n,i=1,l=[]):n or print(l);i>n or[f(n-i,i,[i]+l),f(n,i+1,l)]
grizzled cloak
#

hmm,
TypeError: can only concatenate list (not "str") to list

zealous widget
#

do list(your_string) instead

#

it needs to be mutable

grizzled cloak
#

ah

#

hmm could you somehow also make them be longer than 2 with that function?

zealous widget
#

you could just filter the result

#

it's not efficient, but it's short

#

you could probably program a short version of stars and bars though

#

probably be better

grizzled cloak
#

how do you filter a result by len of array?

zealous widget
#
l = [l for l in s if all(1<len(r)<5 for r in l)]
grizzled cloak
#

you mean s?

#

not r?

#

or what is s?

zealous widget
#

s is the list of partitions

grizzled cloak
#

ahh

zealous widget
#

that would filter the partitions to only the ones with no groupings greater than 4 or less than 2

grizzled cloak
#

hmm ok and now you just sort with a key that assigns a score to the array if it has x leading zeros?

zealous widget
#

something like that

grizzled cloak
#

Wow. That is way better than mine, I mean I did something similar where I generated all the partitions but it was a huge function with a bunch of wierd ifs

rugged sparrow
#

@zealous widget i kinda want to try to make that return

zealous widget
#

once i filtered the partitions by the right size and by correct order i only ended up with 52 unique partitions of 11-digits

#
In [20]: s = partition2(list(map(int,"12340006432")))
In [43]: l = [l for l in s if all(1<len(r)<5 for r in l)]

In [44]: len(l)
Out[44]: 73150

In [45]: t = [r for r in l if ("".join(str(j) for k in r for j in k) == "12340006432")]

In [46]: len(t)
Out[46]: 52
rugged sparrow
#
def f(n,i=1,l=[],r=[]):n or r.append(l);i>n or[f(n-i,i,[i]+l),f(n,i+1,l)];return(r)``` @zealous widget this returns
#

gonna golf it more tho

zealous widget
#

i tried something similar earlier

#

the partitions it returns are un-ordered

#

but, filtering f for invalid partitions would be more performant

#
In [2]: s = f(11)

In [5]: r = [l for l in s if all(1<n<5 for n in l)]

In [6]: r
Out[6]: [[3, 2, 2, 2, 2], [4, 3, 2, 2], [3, 3, 3, 2], [4, 4, 3]]

these are the unique un-ordered partitions of 11 things with no groupings greater than 4 or less than 2

#
In [13]: for l in r:
    ...:     print({*permutations(l)})
    ...:     
{(2, 3, 2, 2, 2), (2, 2, 2, 2, 3), (3, 2, 2, 2, 2), (2, 2, 3, 2, 2), (2, 2, 2, 3, 2)}
{(4, 3, 2, 2), (4, 2, 3, 2), (2, 3, 4, 2), (2, 2, 4, 3), (3, 2, 2, 4), (2, 4, 3, 2), (2, 3, 2, 4), (2, 2, 3, 4), (3, 4, 2, 2), (2, 4, 2, 3), (3, 2, 4, 2), (4, 2, 2, 3)}
{(3, 3, 2, 3), (2, 3, 3, 3), (3, 3, 3, 2), (3, 2, 3, 3)}
{(4, 3, 4), (3, 4, 4), (4, 4, 3)}
#

so that's all the ways you can slice up the 11-digit number

grizzled cloak
#

ah so you make it into a set to remove duplicates?

zealous widget
#

yeah

#

this is the start to a golf:

from itertools import*
s=[j for r in[[3,2,2,2,2],[4,3,2,2],[3,3,3,2],[4,4,3]] for j in{*permutations(r)}]
#

then you need to slice for each thing in s

zealous widget
#
In [53]: from itertools import*
    ...: def f(n):
    ...:     s=[[0]+[*accumulate(j)]
    ...:        for r in [[3,2,2,2,2],[4,3,2,2],[3,3,3,2],[4,4,3]]
    ...:        for j in{*permutations(r)}]
    ...:     return [" ".join(n[v:k] for v,k in zip(t[:-1],t[1:])) for t in s]
    ...:     

In [54]: f("12345678901")
Out[54]: 
['12 345 67 89 01',
 '12 34 56 78 901',
 '123 45 67 89 01',
 '12 34 567 89 01',
 '12 34 56 789 01',
 '1234 567 89 01',
 '1234 56 789 01',
 '12 345 6789 01',
 '12 34 5678 901',
 '123 45 67 8901',
 '12 3456 789 01',
 '12 345 67 8901',
 '12 34 567 8901',
 '123 4567 89 01',
 '12 3456 78 901',
 '123 45 6789 01',
 '1234 56 78 901',
 '123 456 78 901',
 '12 345 678 901',
 '123 456 789 01',
 '123 45 678 901',
 '1234 567 8901',
 '123 4567 8901',
 '1234 5678 901']
zealous widget
#
from itertools import*
def f(n):
    m=e=6
    for k in[[n[v:k] for v,k in zip(t[:-1],t[1:])]
              for t in[[0]+[*accumulate(j)]
                        for r in[[3,2,2,2,2],[4,3,2,2],[3,3,3,2],[4,4,3]]
                        for j in{*permutations(r)}]]:
        a=sum(not int(l[0])for l in k);b=len(k)
        if(a==m and b<e)or a<m:e=b;m=a;p=k
    return" ".join(p)

In [74]: f("12345678901")
Out[74]: '1234 567 8901'

In [75]: f("02000780901")
Out[75]: '0200 0780 901'
#

is this what your function looked like?

grizzled cloak
#

hahah no, i didnt golf it

zealous widget
#

that for statement is really long if i don't split it up

#
for k in[[n[v:k]for v,k in zip(t[:-1],t[1:])]for t in[[0]+[*accumulate(j)]for r in[[3,2,2,2,2],[4,3,2,2],[3,3,3,2],[4,4,3]]for j in{*permutations(r)}]]:
#

looking at it, i feel like this is a poor golf

#

maybe the other method with filtering all the partitions is shorter after all

#

maybe not

grizzled cloak
#

Im surprised itertools doesnt have a function for this

zealous widget
#

i'm surprised partitions aren't included in itertools

#

there's a way to get them with combinations permutations though, but i don't remember

pure dew
#

now sort it alphabetically and look at the spaces

grizzled cloak
#

Hm?

#

Does sort work recursively?

#

When sorting nd lists does it sort the higher d lists?

zealous widget
#

ummm you could sort tuples in a comprehension instead of the for loop maybe

#

that would add another nest into the large comprehension

#
from itertools import*;p=lambda h:" ".join(sorted((sum(not int(f[0])for f in g),len(g),g)for g in[[h[d:e]for d,e in zip(c[:-1],c[1:])]for c in[[0]+[*accumulate(b)]for a in[[3,2,2,2,2],[4,3,2,2],[3,3,3,2],[4,4,3]]for b in{*permutations(a)}]])[0][2])
zealous widget
#

one-lined

grizzled cloak
#

Nice

#

Hope you had fun

zealous widget
#

one-sec, lemme put the variables in order

#

i dunno if that makes a difference

#

i did have fun

grizzled cloak
#

Awesome!

grizzled cloak
#

hey @zealous widget is it cool if i use your code?

zealous widget
#

idc, i uploaded it to my golf repository and it uses the unlicense there

grizzled cloak
#

could you explain what the for a in[[3,2,2,2,2],[4,3,2,2],[3,3,3,2],[4,4,3]] part does?

#
from itertools import*
def f(n):
    m=e=6
    for k in[[n[v:k] for v,k in zip(t[:-1],t[1:])]
              for t in[[0]+[*accumulate(j)]
                        for r in[[3,2,2,2,2],[4,3,2,2],[3,3,3,2],[4,4,3]]
                        for j in{*permutations(r)}]]:
        a=sum(not int(l[0])for l in k);b=len(k)
        if(a==m and b<e)or a<m:e=b;m=a;p=k
    return" ".join(p)```
#

easier to read on the ungolfed version

#

thx for posting that too, makes it so much easier to read!

zealous widget
#
"""
My golf attempt uses the knowledge that all the un-ordered legal partitions of
an 11-digit number are [[3,2,2,2,2],[4,3,2,2],[3,3,3,2],[4,4,3]].

Overview:
#import -- we'll need accumulate and permutations
from itertools import*

unordered_partitions = [[3,2,2,2,2],[4,3,2,2],[3,3,3,2],[4,4,3]]

#we don't need to take the set.union in the golf as we iterate over each element
ordered_partitions = set.union(*({*permutations(unordered_partition)}
                                for unordered_partition in unordered_partitions))

#we use accumulate to give our start and end indices for each grouping
slicings_for_partition = [[0]+[accumulate(partition)]
                          for partition in ordered_partitions]

#all the possible groupings of the phone_number
possible_groupings = [phone_number[i:j]
                      for i,j in zip(slicings_for_partition[:-1],
                                     slicings_for_partition[1:])]

#count the number of leading zeros in each grouping
number_of_leading_zeros = sum(not int(group[0]) for group in possible_groupings)

#sort by leading_zeros and then by length of list
best_grouping = sorted((number_of_leading_zeros, len(grouping), grouping)
                        for grouping in possible_groupings)[0][2]

#add spaces between the groups
Then we return " ".join(best_grouping)
"""
grizzled cloak
#

ahh

#

how did you calculate those? lets say its 30 digits instead of 11?

#

or some number n

zealous widget
#

this only works for 11 digit numbers

#

specifically

grizzled cloak
#

yeah but how would i calculate a similar list for n?

zealous widget
#

you'd have to calculate unordered partitions

#

one sec

grizzled cloak
#

dont they just have to add up to n?

#

and not be the same thing twice?

#

and be between 2 and 4

zealous widget
#
def partitions(n,i=1,l=[],r=[]):n or r.append(l);i>n or[partitions(n-i,i,[i]+l),partitions(n,i+1,l)];return r
def filtered_partitions(n):return [partition for partition in partitions(n) if all(1 < n < 5 for n in partition)]
#

try filtered_partitions(30)

#

oops, fixed

#

no it isn't, sec,

#

that's what i get for renaming things on-the-fly

grizzled cloak
#

well. my approach just broke pycharm.

zealous widget
#
In [4]: filtered_partitions(30)
Out[4]: 
[[2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
 [4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
 [3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
 [4, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
 [4, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
 [3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2],
 [4, 4, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2],
 [4, 4, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2],
 [4, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2],
 [4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2],
 [3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2],
 [4, 4, 4, 3, 3, 2, 2, 2, 2, 2, 2],
 [4, 4, 3, 3, 3, 3, 2, 2, 2, 2, 2],
 [4, 4, 4, 4, 4, 2, 2, 2, 2, 2],
 [4, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2],
 [4, 4, 4, 4, 3, 3, 2, 2, 2, 2],
 [3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2],
 [4, 4, 4, 3, 3, 3, 3, 2, 2, 2],
 [4, 4, 4, 4, 4, 4, 2, 2, 2],
 [4, 4, 3, 3, 3, 3, 3, 3, 2, 2],
 [4, 4, 4, 4, 4, 3, 3, 2, 2],
 [4, 3, 3, 3, 3, 3, 3, 3, 3, 2],
 [4, 4, 4, 4, 3, 3, 3, 3, 2],
 [4, 4, 4, 4, 4, 4, 4, 2],
 [3, 3, 3, 3, 3, 3, 3, 3, 3, 3],
 [4, 4, 4, 3, 3, 3, 3, 3, 3],
 [4, 4, 4, 4, 4, 4, 3, 3]]
grizzled cloak
#

and pycharm is using 24GB of ram

zealous widget
#

christ

grizzled cloak
#

haha i have 32 total so im at 97% ram now

#

yikes

#

i killed pycharm and that freed up another 5Gb of ram or so. the python process took it all hah

#

guess my way was to inefficient

marsh void
#

lol

grizzled cloak
#
part = lambda n: list(permutations([2,3,4]*(n//2))```
#

it was something like that

#

since worst case is that its a bunch of 2 and it still has to add up to n

#

pretty bad.

#

it gets pretty slow for large nums but thats fine i guess

#

aaaand i crashed pycharm again

edgy kelp
#

I love pycharm freezing up when the python console is stuck on something

grizzled cloak
#

yup

#

youd think thats in some entirely different process.

edgy kelp
#

force ending the process works but... why?

grizzled cloak
#

yeah....

edgy kelp
#

does it run in the gui thread or what 😄

zealous widget
#

light weight spyder to the rescue

grizzled cloak
#

@zealous widget looks like this:

ordered_partitions = set.union(*({*permutations(unordered_partition)}
                                for unordered_partition in unordered_partitions))```
#

is one of the most time consuming parts

zealous widget
#

yep, permutations is unforgiving

#

combinatorial explosion is real

grizzled cloak
#

why do we need to order them?

zealous widget
#

be cau se that is different from bec au se even though they have the same unordered partition 3,2,2

grizzled cloak
#

but why do we have to generate all the permutations, i mean even for something like 3,2,2 it returns this:

>>> list(permutations([3,2,2]))
[(3, 2, 2), (3, 2, 2), (2, 3, 2), (2, 2, 3), (2, 3, 2), (2, 2, 3)]```
#

and then you make a set out of it anyways and remove them

zealous widget
#

remove the duplicates

#

we only need the unique orderings

grizzled cloak
#

yeah but why do we generate them in the first place?

#

why not use sympys multiset_permuations or does that do the same thing under the hood?

zealous widget
#

we need to consider all possible grouping of the number is why

#

if we do just the un-ordered partition 3,2,2 we'd only get one grouping 111 11 11

grizzled cloak
#
list(multiset_permutations([3,2,2]))
Out[5]: [[2, 2, 3], [2, 3, 2], [3, 2, 2]]```
zealous widget
#

we permute it to get all the groupings 11 11 111, 11 111 11, 111 11 11

#

you could use that, but i'm guessing it's more bytes

#

too bad they named it multiset_permutations

#

and not mp

#

sympy is probably got a good implementation though

grizzled cloak
#

nah its just as slow

#

or well its so slow i didnt let it finish

#

nah its just as slow

#

you mean this one?

function &permuteUnique($items) {
    sort($items);
    $size = count($items);
    $return = [];
    while (true) {
        $return[] = $items;
        $invAt = $size - 2;
        for (;;$invAt--) {
            if ($invAt < 0) {
                break 2;
            }
            if ($items[$invAt] < $items[$invAt + 1]) {
                break;
            }
        }
        $swap1Num = $items[$invAt];
        $inv2At = $size - 1;
        while ($swap1Num >= $items[$inv2At]) {
            $inv2At--;
        }
        $items[$invAt] = $items[$inv2At];
        $items[$inv2At] = $swap1Num;
        $reverse1 = $invAt + 1;
        $reverse2 = $size - 1;
        while ($reverse1 < $reverse2) {
            $temp = $items[$reverse1];
            $items[$reverse1] = $items[$reverse2];
            $items[$reverse2] = $temp;
            $reverse1++;
            $reverse2--;
        }
    }
    return $return;
}```
#

they say its 500x faster

#

im gonna try it 🙂

zealous widget
#

it's not that much faster, 3-5x faster from the comments

#

but that's 3-5x faster than a solution above it

#

the solution above it was like 10000X faster than naive solution

#

this heavily depends on how many non-unique items are in the multiset

grizzled cloak
#

ah ok

#

its been like 2 years since i touched php, what does break 2 mean?

zealous widget
#

i have no idea, i've never touched php

grizzled cloak
#

haha ok

zealous widget
#

i think it means break out of a loop in the next scope out

#

i read a PEP proposal where someone wanted to add that functionality into python

#

so you didn't have to toggle boolean flags

grizzled cloak
#

yeah, i wouldn't see my self using that a lot though

zealous widget
#

i'd have used it a few times by now, but not too often

#

it specifically mentions php loops too

grizzled cloak
#

wait do arrays start at 1 in php???

zealous widget
#

i don't know, but if they do---gross

#

looks like they do

#

...or not, two different pages indexed them differently

#

probably one was associative and they used 1 to index first element just to be extra confusing

grizzled cloak
#

hmm, looks like they are all slow...

#

if you use a len of 11 its fine, but then i tried 15 and its taking for ever...

#

oh well ill work on it more tomorrow...

#

but thanks for explaining it!

zealous widget
#

np

#

for reference if you need it

grizzled cloak
#

Thanks!

zealous widget
#

np

sick hound
#
_                   =r"""A(W/2,*M(3*G
               *G*V(2*J%P),G,J,G)+((M((J-T
            )*V((G-S)%P),S,T,G)if(S@(G,J))if(
         W%2@(S,T)))if(W@(S,T);H=2**256;import&h
       ashlib&as&h,os,re,bi    nascii&as&k;J$:int(
     k.b2a_hex(W),16);C$:C    (W/    58)+[W%58]if(W@
    [];X=h.new("rip           em    d160");Y$:h.sha25
   6(W).digest();I$                 d=32:I(W/256,d-1)+
  chr(W%256)if(d>0@"";                  U$:J(k.a2b_base
 64(W));f=J(os.urando       m(64))        %(H-U("AUVRIxl
Qt1/EQC2hcy/JvsA="))+      1;M$Q,R,G       :((W*W-Q-G)%P,
(W*(G+2*Q-W*W)-R)%P)       ;P=H-2**       32-977;V$Q=P,L=
1,O=0:V(Q%W,W,O-Q/W*                      L,L)if(W@O%P;S,
T=A(f,U("eb5mfvncu6                    xVoGKVzocLBwKb/Nst
zijZWfKBWxb4F5g="),      U("SDra         dyajxGVdpPv8DhEI
qP0XtEimhVQZnEfQj/       sQ1Lg="),        0,0);F$:"1"+F(W
 [1:])if(W[:1           ]=="\0"@""        .join(map(B,C(
  J(W))));K$:               F(W          +Y(Y(W))[:4]);
   X.update(Y("\4"+                     I(S)+I(T)));B$
    :re.sub("[0OIl    _]|            [^\\w]","","".jo
     in(map(chr,ra    nge    (123))))[W];print"Addre
       ss:",K("\0"+X.dig    est())+"\nPrivkey:",K(
         "\x80"+I(f))""";exec(reduce(lambda W,X:
            W.replace(*X),zip(" \n&$@",["","",
               " ","=lambda W,",")else "])
                    ,"A$G,J,S,T:"+_))
#

😄

zealous widget
#

doesn't exec feel cheaty

grizzled cloak
#

what if you first split the sting into groups of 4 and then tried to push them around to get rid of leading zeros?

grizzled cloak
#

i might be onto something! python has a bunch of optimization tools so i can use a function such as this to evaluate a certain option:

def evaluate_solution(solution):
    num_leading_zero = 0
    for item in solution:
        num_leading_zero += len(item) - len(str(int(item)))
    return num_leading_zero / 4```
grizzled cloak
#

@zealous widget ok, I got it working!

#

Ended up doing some recursive searching upping the block size. If it cant find a solution with 0 leading 0 it allows one and then repeat :)

zealous widget
#

do you start with the biggest block size and then move down

#

like, 4 4 4 4 4

#

then 4 4 4 3 3 2

grizzled cloak
#

Either way works

zealous widget
#

i thought you would prefer the fewest groupings

#

i have my golf scored that way

#

finds fewest leading zeros and then fewest groupings

grizzled cloak
#

Yea

#

Its a forloop that tries the different sizes so it just depends on what direction it goes

#

Either 1-4 or use -1 as a stepsize

grizzled cloak
#

Theres a little bug left but then ill golf ut

#

It

sick hound
#

@zealous widget You do that for the bwinf contest?

zealous widget
#

what's that?

sick hound
#

nvm

#

sry i mean @grizzled cloak
You do that for the bwinf contest?

rugged sparrow
#
c = lambda c:[x for x in object.__subclasses__()if x.__name__==c][0] # gets 99% of builtin/classes imported at runtime from a string name
print(c('function')) # <class 'function'>
i = lambda c:[i for i in __import__('gc').get_objects()if type(i)==c] # gets all instances of a class
class A:pass
b = A()
print(i(A)) # [<__main__.A object at 0x7b1a381a4e10>]```
grizzled cloak
#

@sick hound yes! Try not to copy it please

#

Are you taking part aswell?

stray needleBOT
snow beacon
#

⬆ This one was diabolical to debug; all the parts need to fit together perfectly. Don't try to read it without a syntax highlighter.

sick hound
#

@grizzled cloak no, i do not participate on this, but isn't kinda unfair when u ask here for help?

#

btw. i solved this problem 😬

grizzled cloak
#

i wasnt asking for help, i already solved it

#

i was just posting it for fun

#

i used a different completely different approach

sick hound
#

different from what?

grizzled cloak
#

what salt posted

sick hound
#

how long is your solution?

#

loc?

grizzled cloak
#

i havent golfed it yet

sick hound
#

in theory it should only be 1 loc

#

mine is 3 lines

#

if you count the line with the input 4

grizzled cloak
#

how did you solve it>

#

brute force?

sick hound
#

nope

#

i solved it with my favourite tool

grizzled cloak
#

hmm?

sick hound
#

when i tell you, you will change your solution .-.

grizzled cloak
#

i doubt it

sick hound
#

i have no fancy loops, if-statements just an import statement some variable containing something i need just for readability and an print with an join inside

#

is a space separated list the correct output? 😂

grizzled cloak
#

but thats kind of cheating

sick hound
#

why?

grizzled cloak
#
solution(problem)```
#

meh

sick hound
#

aren't imports allowed?

grizzled cloak
#

yes but thats not the point

sick hound
#

i haven't installed any additional packages

#

just pure python lib

#

is the import of packages that already come with python also forbidden?

grizzled cloak
#

no

#

but you are suposed to solve it and show you know how

#

not just import it

sick hound
#

what

grizzled cloak
#

so how did you solve it?

sick hound
#

the concept behind the tool i used exists since 1950 ^^

grizzled cloak
#

ok

#

still doenst answer the question hahah

sick hound
#

it's a great tool

#

i know

#

but i can't know that u submit my solution .-.

#

or not

grizzled cloak
#

because i like mine

sick hound
#

mmh

#

i like mine too 😂

#

how about you both submit it to me and I can act as an independent 3rd party who most definitely wouldn't submit both of them

#

🤔

#

ur from germany?

#

@grizzled cloak i will tell u the first and last character of each word from the tool

#

Rr En

grizzled cloak
#

i am yes

sick hound
#

i know that u are, i asked Modelmat

#

maybe i should have tagged him .-.

grizzled cloak
#

@sick hound the only lib that matches that in the stdlibs is re

#

and could you tell me what your programm outputs for :
01507015061

#

or for something like: 0110000011561561

#

because id be surprised if re can do those correctly..

sick hound
#
0150 701 5061
01 1000 0011 5615 61
grizzled cloak
#

it got the first one right but the second one is wrong,
you have 2 blocks starting with a 0.

sick hound
#

thats right

grizzled cloak
#

oh sry i just split it up slightly differently 🙂

sick hound
#

it should be the smallest amout of block starting with 0

grizzled cloak
#

all good

sick hound
#

and u can't have less than 2 block with 0 as first digit

grizzled cloak
#

so howd you do it

sick hound
#

mmh 😂

#

can i ask u how old u are?

grizzled cloak
#

sure im 17

#

you?

#

why did you ask?

sick hound
#

i just was interested

#

im already too old for that 😫

grizzled cloak
#

sry if im not answering instantly, im playing some games with my little brother

sick hound
#

👍

marsh void
#

Sad thing modules are not callable

#

I am 15 though, like really xd

snow beacon
#

I think it counts. It's simple, but that doesn't have to be a bad thing.

marsh void
#

haha, let me one-line it then

#

and bundle the functions in the result, I think

snow beacon
#

You don't have to do it as crazily as I did.

#

My decoder contains the encoder inside it, unnecessarily.

marsh void
#

true tho

#

I find it pretty cool that some understandable text turns into this: "9\n\x1dR\nd+<'K_\x02\x0ch\x15^\x1d\x04\x03\x1dT\x052=U \x10\x10\x11bg\x08F&:<.7\x1eF\x0c\x14L(\x1cL90\x16]\x14\x0c&?D*H\x1bF)\\\x08-<a\r]\n\x1b\x05\x1e\x1c\t "

grizzled cloak
#

@sick hound did you do any of the other questions form the bwinf?

sick hound
#

nope

formal sandal
#

I know this is not new, but it would be cool to have a language with a few hundred symbols

#

I guess you could encode some complicated algorithm like this... Would it count as an obfuscation?

marsh void
grave rover
#

Esoteric challenge time!
( @brisk zenith pin this if you want ig)
Floorplans
A company that builds public swimming pools has hired you for quite the odd task;
They have a set amount of 1m by 1m floor tiles, and you need to find how large the building and pool have to be.
The catch? Both the building size and the pool size have to be squares of full numbers.

in short: Given integer n, find integers m and k so that n=m^2-k^2, or return "impossible" if this is impossible

input
1 <= n <= 10^9

output
if possible: integers m and k
if impossible: the string "impossible"

Winning conditions

  • The output must be correct in all cases
  • We're not quite looking for the most esoteric solution, but the fastest one! Try to optimize your code as much as possible
  • evalling more optimized bytecode than is possible with writing code normally is NOT allowed!
marsh void
#

not esoteric enough xd

gilded orchid
#

I feel like optimization isn't really esoteric

#

also I feel like that'd be a really good thing to do with a recursive function

marsh void
#

Hey, juanita :)

brisk zenith
#

hiya!

#

yeah that challenge is not really esoteric at all, code optimisation is a very common and useful challenge in the real world. i'm not gonna stop anybody from posting solutions for it though, but i don't think it's pin-worthy :)

polar plover
#

I think I got a working script, give me some numbers to test.

#

@grave rover

grave rover
#

uh

#

5 works
10 doesnt
uhh

#

I dont remember that many

polar plover
#

5 -> 3, 2

#

10 -> impossible

#

😄

#

@grave rover does 4 -> 2, 0 (4 - 0 = 4) count?

grave rover
#

Wdym @polar plover

#

2 and 0 is fine, yeah

polar plover
#

👍🏻 using 0 just felt like something that might not be allowed.

grave rover
#

1_000_000_000 and 999_999_999 have solutions too btw

polar plover
#

31625, 375

grave rover
#

Yup

#

Interested in the impl ngl

polar plover
#

it was fast, did not expect that xD

grave rover
#

102 should be impossible I think

polar plover
#

my program says so.

grave rover
#

Nice

#

What about 4798

polar plover
#

okay, lets see.

#

4798 -> impossible

grave rover
#

Yup

polar plover
#

24144 -> 515, 491 (265225 - 241081 = 24144)
here it is for the number of members in the server

brisk zenith
#

i have an insanely quick solution but idk how to check if it's impossible

polar plover
#

you could set a "limit" or use math (I used math)

brisk zenith
#

mine does 1000000000 in 0.005 seconds

stray needleBOT
polar plover
#

let me just put in timeit real fast

brisk zenith
#

what sort of thing would i check to see if it's impossible though?

grave rover
#

@brisk zenith if you can't possibly do it then it's impossible

#

ez

#

For example, there's no way to do 10 as the difference of two squares

#

@polar plover what's your time?

polar plover
#

just wait, I messed up when I put in the timeit somehow xD

grave rover
#

Just use the tio link I sent

#

All hosts are the same so timings should be equal

brisk zenith
grave rover
#

I mean

#

You can try all of them I guess

brisk zenith
#

how do you try all of them 🤔

grave rover
#

You can know m will always be greater than or equal to sqrt(n)

#

And at most it'll be 2n

brisk zenith
#

oh right okay, i just figured that out right as you said it

polar plover
#

0.151 s

grave rover
#

But even then you can't get this speed boye

#

@polar plover on tio?

polar plover
#

Real time: 0.151 s
User time: 0.135 s
Sys. time: 0.014 s

grave rover
#

That's crazy fast for all numbers, jeez

#

I need to see your impl lmao

#

bc mine should mathematically be the fastest possible method

polar plover
#

wait, I just ran it for 10**9 since that's what @brisk zenith said.

grave rover
#

Oh

polar plover
#

let me run it for all

grave rover
#

Yeah the tio link I gave tests for all numbers 1-1M

#

Just use the link so we know the conditions are exactly the same @polar plover

polar plover
#

👍🏻

#

then, we wait xD

grave rover
#

If you get it under 2s you'll have a micro optimization of mine lol

polar plover
#

well, I think it's taking longer than that it looks xD

#

well, it's fast for just 1 number. but your's must be a lot faster then xD

grave rover
#

Sub 2 bois

polar plover
#

changed the way I loop and it cut it down to 1.7 S xD

brisk zenith
#

rekt 🔥

polar plover
grave rover
#

Damn

#

You can get that speed by looping?

polar plover
#

I looped from math.floor(math.sqrt(n)) to infinity, before, changed to n to -infinity

grave rover
#

Linear solutions should be way slower than mine 🤔

brisk zenith
#

well obviously, do you not know the power of lööps bröther?

grave rover
#

Well I calculate a solution directly

polar plover
#

wait, that can be done?

grave rover
#
def values(n):
    mod = n % 4
    if mod is 1 or mod is 3:
        # odd number -> (k+1)^2 - k^2 = 2k+1
        k = int((n-1)/2)
        return (k+1, k)
    if mod is 2:
        # divisible by 2 but not 4 -> impossible
        return "impossible"
    # divisible by 4 -> (k+2)^2 - k^2 = 4k+4
    k = int((n-4)/4)
    return (k+2, k)
brisk zenith
#

can't math.floor(math.sqrt(n)) be massively optimised via int(n ** 0.5)?

grave rover
#

Not sure how your loop was so fast

polar plover
#
def find(n):
    i = n
    while 1:
        if i ** 2 - (i - 1) ** 2 > n:
            return "impossible"
        for j in range(i - 1, -1, -1):
            m, k = i ** 2, j ** 2
            if m - k == n:
                return i, j
        n -= 1
brisk zenith
#

you could probably make that faster by doing if i ** 2 - j ** 2 == n directly

#

as then you're not constantly making tuples

#

although realistically, mart's loopless solution looks like it should be much faster

grave rover
#

Mine is only slow because of the int()

#

If the division didn't return a float I could've removed that int() call and it gets a consistent 1s

brisk zenith
#

use //

marsh void
#

Imagine using is for integers lol

brisk zenith
#

idk it might be faster or something

polar plover
#

I think mine is broken somehow xD what did I do 😦

#
1 -> 1, 0 (1 - 0 = 1)
2 -> impossible
3 -> impossible
4 -> impossible
5 -> impossible
6 -> impossible
7 -> impossible
8 -> impossible
9 -> impossible
10 -> impossible```
grave rover
#

@brisk zenith // still returns a float fyi

#

It's bs tbh

#

@marsh void is is faster for ints that are in range 0-511 iirc

pure dew
#

new eso challenge?

grave rover
#

@pure dew ignore solutions, look for large post by me

marsh void
#

okay

polar plover
#

yhe, mine is pretty slow. I somehow messed up trying to make it better. making everything impossible.

#

that's why it was "fast"

grave rover
#

Tldr:
Take integer n
Return integers m and k so m^2 - k^2 = n
If impossible return "impossible"

#

Ah

#

That explains a lot lol

polar plover
#

idk what I did xD

grave rover
#

New tests work fine, yeah

#

Tho people could use this as cheat sheet for impossibility I guess

#

But yeah, mine should be fastest

edgy kelp
#

is will be faster than == for the preloaded ints (-5 - 256 in cpython) since it has a lot less to do

grave rover
#

Ah it's -5 to 256

#

ic

#

But yeah an id check is way faster than checking eq and stuff

sick hound
#

Lol clicking that link crashes my discord app

brisk zenith
#

sounds like a you problem :^)

grave rover
#

For some reason n % 4 is faster than n & 3 even though the latter should in theory be faster

#

I guess n % p is really just n xnor (p-1)

#

And xnor is slightly faster than and

pure dew
#

oi mart

grave rover
#

hm?

pure dew
#

im gonna try and write a solution that i didnt come up with entirely on my own if thats cool

#

cus i thought you might've done it, but you didn't

grave rover
#

Sure

#

x/2 is faster than x>>1

#

tf

pure dew
#

yea

grave rover
#

How does that make sense

rugged sparrow
#
encoder = lambda s,d=0:''.join([chr(sum(map(ord,c))) for c in [s[i:i+2] for i in range(0,len(s),2)]]if d else[(lambda x:chr(x)+chr(ord(c)-x))(__import__('random').randrange(0, ord(c))) for c in s])``` @marsh void its onelined
marsh void
#

Ehehe thanks

rugged sparrow
#

encoder('test') - > 'encrypted'

#

encoder('encrypted',1) -> 'test'

marsh void
#

yep, got it

#

Ok lemme replace xd

rugged sparrow
#

could prob minimize it a bit

edgy kelp
pure dew
#

@grave rover well nvm it doesn't work in python due to the way they handle ints

#

i'll see if i remember C well enough to scratch it out

snow beacon
#
''.join('\u200b\u200c'[bit>'0']for char in string for bit in f"{ord(char):08b}")```
#

There's your obfuscate function

#

At least, excluding the lambda bit.

snow beacon
#
int(''.join(str(ord(char)&1^1)for char in bytestring),2).to_bytes(len(bytestring)//8,'big').decode()```And here's for the deobfuscation
#
int(''.join(str(ord(char)&1 ^ 1) for char in bytestring), 2).to_bytes(len(bytestring)//8, 'big').decode()```if you want whitespace
crystal mica
#
string = 'the weather is great!'
key = 777

encoded = ''.join(map(chr, map(lambda s: (ord(s) ^ key) * 2, string)))
decoded = ''.join(map(chr, map(lambda s: (ord(s) // 2) ^ key, encoded)))```for the fun, but idt it's esoteric-level
#

decoded is obv 'the weather is great!'

#

encoded is ۺۂْۘۼۘېۺۂۘ۶ْۀ۴ْۜ۶ۘېۺِ which is funny

tropic night
#

i find this not esoteric enough, what you need is to use characters that are encoded right-to-left like in the middle, or something like that.. should be possible 😄 i think.... probably not...

#

is it possible?

gilded orchid
#

I'm tempted to do an encoding only using zalgo characters

crystal mica
#

Hmm, I made another one with that idea - reverse every steps letters, then encode by shifting ord by a key

snow beacon
#

I ran into some unicode problems when I tried to blindly shift bytes and convert them back to characters. That's why I use base64 as the intermediate step

tropic night
#

maybe it is dependant on the editor that you use to look at it? does right-to-left characters render on the right margin or can you insert them anywhere in the text?

crystal mica
#

What would be cool is that we wrap it around 0-256 ord for e.g, so 257 will be 0

tropic night
#

because if you have something like hello my name is lvie what is yours?

zealous widget
#

those right-to-left characters do weird things

tropic night
#

might f-up text selection

marsh void
#

Oh hey eivl

zealous widget
#

i don't think all the behavior is predictable

crystal mica
#

oh you mean those unicode that looks like normal alphabets but looks right to left? lol

marsh void
#

@snow beacon just figured out my encoder errors on null bytes, gotta fix that

zealous widget
#

there's some esoteric unicode things i'm sure i've read about before

snow beacon
#

My code uses modulo 256 on my byte values, the hard part is turning the result into a printable character that doesn't break anything and can be converted back losslessly. I doubt anyone wants to poke around in my code, but if you replace the base64 conversion with a simple .encode() everything breaks.

#

To be honest, it'll probably break whatever you change.

edgy kelp
#

@snow beacon thanks that's certainly beyond what I could come up with :D

marsh void
#

lol

snow beacon
#

It can be pretty daunting to see a lot of complicated things all at once, but if you invent it step by step it's all very logical. Are there any individual parts of the code you don't understand?

#

Or is it more that you just wouldn't have thought of it?

grave rover
#

I have a new challenge idea

#

yeet

snow beacon
#

Interesting challenge. Do eleborate.

grave rover
#

also col I'd like to see you try the one I mentioned yesterday

#

given integer n find integers m and k so that m^2 - k^2 = n
if impossible, return "impossible"

snow beacon
#

The Pythagorean triples one?

#

Right.

grave rover
#

not quite triples

#

cause n doesnt have to be a square

snow beacon
#

I was just about to say.

grave rover
#

n = 8 has a solution for example

snow beacon
#

And the thing to optimise for was speed rather than code size?

grave rover
#

n = 10 doesnt

#

yea

#

I think mine is the fastest atm

#

given n:
sqrt(n) <= m <= 2n
0 <= k <= (n-1)/2 (I think?)

#

Challenge time bois
EEEEEEEEE
These days it's common to see chats like this:

> heey
< heeeey
``` Your task? Given input `/he+y/`, return the same with double the amount of 'e's, as short as possible.

Rules:
- Must be read from stdin
- Must be output to stdout
- Allowed to have a trailing newline, no trailing spaces
- input may be assumed to always follow `/he+y/`
#

(cc @brisk zenith)

crystal mica
#

is there a limit to m and k in the previous case?

grave rover
#

simple task, but compressing might get tough :P

crystal mica
#

It seems like m and k can go on forever

#

actually hmm im dumb

grave rover
#

@crystal mica I mean there's an easy solution but it's guaranteed to be possible within those limits

snow beacon
#

Does s=input();print(s[1:]+s[:1]) work?

grave rover
#

I calculate my m and k but there's linear solutions, yeah

#

@snow beacon that works

#

print(f"h{input()[1:-1]*2}y") is the shortest I can do I think

#

ah shit thats longer than yours

marsh void
#

lol

grave rover
#

1 char

marsh void
#

Your is the shortest

#

No esotericness tho

snow beacon
#

h,*e,y=input();print(h+e+e+y) is another way

grave rover
#

lmao

#

good one

marsh void
#

lol

crystal mica
#

damn

#

that is good

snow beacon
#

Thanks

grave rover
#

screw smaller solutions that one's just great

marsh void
#

n o t e s o t e r i c

grave rover
#

alright lemme find an actually interesting task

snow beacon
#

(In the meantime I am researching the difference of squares task.)

crystal mica
#

hmm im running into error running it

#

but nah it's too beautiful to change

marsh void
#

Lol

#

Because e is a list

#

b a d

grave rover
#

given is that there are n nodes, and y corridors. give the list of all corridors required to be removed to make sure there's no cyclic connections

Example input:

# comments are not part of input
2 2  # rooms corridors
1 2  # 1-indexed
2 1

Example output:

1    # remove 1
2 1  # specific corridor

Rules:

  • You may remove at most half of all corridors
  • If there's multiple solutions, just give one
  • Read from stdin, write to stdout
edgy kelp
#

@snow beacon wouldn't have thought of it mainly, will look at it properly but certainly wouldn't have thought of the bit operators as I never work with them so haven't even cared to learn which is which

grave rover
edgy kelp
#

Wonder how the encoding solutions compare in speed

marsh void
#

h,*e,y=input();print(h,*e*2,y,sep='')

#

Bad

#

Longer

zealous widget
#

oh finding spanning trees

#

i tackled something similar a month or so ago with a maze-generator

#
- You may remove at most half of all corridors

that's a weird requirement though

#

a large complete graph wouldn't be solvable

grave rover
#

I mean some may require moving half but it cant ever be more

zealous widget
#

are these graphs always planar or something?

grave rover
#

and I need to limit it otherwise people can always just remove any amount

#

you can assume no two corridors cross

#

so a complete graph with 4 or more rooms won't be presented

zealous widget
#

i still don't know that will allow all planar graphs to be solved, but it might

#

i'd be interested in the theorem that states it

grave rover
#

that half is rounded up btw

#

in case of odd amount of corridors

zealous widget
#

whats the input? some array of numbers?

grave rover
#

input will be the same as shown

zealous widget
#

can you give a larger example

#

it's too small

grave rover
#

another example:

3 4  # rooms, corridors
1 2
2 3
3 1
3 2

output:

2
3 1
3 2
zealous widget
#

yeah, i don't know what that means

grave rover
#

wdym

zealous widget
#

i don't know how to get a network from those numbers

grave rover
#

I just give you all connections in a graph/network

zealous widget
#

where?

grave rover
#

well

#

1 2 is a connection from 1 to 2

zealous widget
#

those are edges, ok

grave rover
#

2 3 is a connection from 2 to 3

zealous widget
#

why didn't you say so

grave rover
#

I did

snow beacon
#

In order to create a cycle between two nodes, you need at least three connections, unless connections can cross/overlap. That means you can always solve it if it's just the cycle. However, you can add extra nodes and link them, but each one always requires another two connections in order to add an extra node to the cycle. Therefore the number of connections is always at least double the amount of cycles between two specific points, so you can sever the connections. I conjecture something similar applies if you add more pairs of nodes with cycles, but I don't know how to prove it.

grave rover
#

first the number of rooms and corridors, then all corridors

zealous widget
#

it's so obfuscated, just state it plainly: i give the number of nodes and edges and then list all the edges

#

should note, that the edges is sufficient to construct the graph

#

unless the graph isn't connected, but then how would you find a spanning tree

grave rover
#

some might not be connected, others might

#

the numbers on the first line are just there so you know how many more lines come from stdin

#

also; corridors are not directional, but if there's two corridors between the same rooms it will be written the other way (e.g. 3 2 and 2 3 rather than 2 3 and 2 3)

zealous widget
#

ungolfed with networkx is cheeky though:

import networkx as nx
G = nx.Graph()
for _ in range(int(input("N_nodes, N_edges: ").split()[-1])):
    G.add_edge(*input("edge: ").split())
T = nx.minimum_spanning_tree(G)
print(G.size() - T.size())
for start, end in T.edges():
    print(start, end)

output:

N_nodes, N_edges: 5 4

edge: 1 2

edge: 1 3

edge: 3 4

edge: 2 4
1
1 2
1 3
2 4
#

i don't use number of nodes, so it's an incorrect number

#

most of the code is just dealing with input

grave rover
#

🤔

#

how does it say 1 but output 3 lines

zealous widget
#

oh i printed all the lines in the tree, forgot you wanted the edges that were removed

#

easy to fix

#

for start, end in [edge for edge in G.edges() if edge not in T.edges()]:

grave rover
#

interested in seeing a solution that doesn't take that long tbh

zealous widget
#

i mean, i assume you actually want a golfed spanning tree algorithm and not piggyback off of another module

grave rover
#

kinda :P

#

I guess a DFS is all you really need, once you find a node you've seen before just remove the edge

zealous widget
#

yep, just add edges until all nodes are accounted for

snow beacon
#

For the difference of squares puzzle.

grave rover
#

@snow beacon wdym

#

oh your score

#

its decent

#

but uh

#

lets just say TIO isnt very accurate lol

#

DM code and I'll test it on the same thing I tested mine and vivax's on

#

looks pretty solid tho

snow beacon
#

And with that, I should probably get to bed.

grizzled cloak
#

@tropic night imma post the challenge here, feels like a better fit.

tropic night
#

yes thanks.. i have to put on my moderator hat now.. hold on

grizzled cloak
#

maybe someone else can have a go at it aswell 🙂

#

haha have fun!

#

you have a flowerbed in this shape containing 9 flowers:

     0
   1   2
 3   4   5
   6   7
     8

there are 7 differnt colors of flowers you can plant in the flowerbed:

color_names = ['blue', 'yellow', 'green', 'orange', 'pink', 'red', 'cyan']

the user specifies how many different colors should be in the flowerbed and gives you some info on what they like. they will tell you what colors they would like next to each other and how important that is to them. the goal is to calculate the highest ranking flowerbed based on their preferences.
i might be missing something here so just ask if something is unclear
also to save you some time these are the neighbors for each flower:

neighbors = [(1, 2), (0, 2, 3, 4), (0, 1, 4, 6), (1, 4, 6), (1, 2, 3, 5, 6, 7), (2, 4, 7), (3, 4, 7, 8), (4, 5, 7, 8),
             (6, 7)]```
0th element corresponds to flower 0
#

so a example would be that they say:
i want 7 differnt colors.
also i really like red flowers next to blue flowers. (3 points)
and i like red ones next to cyan ones too. (2 points)

#

my programm generates this for the example above: not sure if its correct myself, do tell me if you get something else:

         y
       b   r
     r   r   g
       c   o
         p```
zealous widget
#

you could improve the score by switching red and pink

grizzled cloak
#

Which one of the reds?

zealous widget
#

oh, nevermind, cyan and blue

grizzled cloak
#

But blue+red gives 1 point more than cyan+blue

zealous widget
#

no, i mean the colors you specified were cyan and blue and not what i was thinking

tropic night
#

i do not get how neighbors work

#

(1, 2) what does this mean?

grizzled cloak
#

Well the flowerbed isnt a square so the neighbors are different.

#

Oh

#

The 0th flower has the 1. And 2. Flower and neighbors

#

You could write it as a dict as well but they keys would just be 0-8

zealous widget
#

In [36]: G = nx.grid_graph([3, 3])
    ...: G = nx.relabel_nodes(G, {(0, 0): 0,
    ...:                          (0, 1): 2,
    ...:                          (0, 2): 5,
    ...:                          (1, 0): 1,
    ...:                          (1, 1): 4,
    ...:                          (1, 2): 7,
    ...:                          (2, 0): 3,
    ...:                          (2, 1): 6,
    ...:                          (2, 2): 8})

In [37]: G[0]
Out[37]: AtlasView({1: {}, 2: {}})

In [38]: G[1]
Out[38]: AtlasView({0: {}, 3: {}, 4: {}})

i just represent it as a grid-graph

tropic night
#

the second flower, does it not have 6 as a neighbor?

grizzled cloak
#

6 is on the opposite side though

#

It doesnt loop around

#

Salt, grid-graph sounds fancy, what does it do?

tropic night
zealous widget
#

it's a graph thats connected like a grid

tropic night
#

so these are not the neighbors for the flower 1?

grizzled cloak
#

6 isnt no

#

The way I wrote it it looks like a square turned 45° but its more elongated vertically

zealous widget
grizzled cloak
#

I think the center one should have the left and right of it as well.

#

It doesnt really matter as long as we all use the same

zealous widget
#

you can just add those two edges manually, i guess

tropic night
#

then i have a question more

#

why is index 1 neighbor with 2 ?

#

its the same distance to 6

#

and its not neighbor to 6

grizzled cloak
#

Yeah the drawing from salt isnt quite right. Its more of a kite shape

#

Let me google the term for it

#

Ah

#

A diamond shape

zealous widget
#

it turned it around, but i think that's right

grizzled cloak
#

Yes! That turned 45

#

Exactly

zealous widget
#

graph drawing isn't the friendliest thing

grizzled cloak
#

I think

#

It doesnt matter. Lets just all use what salt posted :)

tropic night
#

but still.. why is flower 1 neighbor with 2

#

oh.. sure..

#

oriented what way?

grizzled cloak
#

45° turn

#

So its a diamond

zealous widget
#

i think pi/2 radians actually

grizzled cloak
tropic night
#

thats a 90 degree turn

grizzled cloak
#

Thats the original pic from the question

#

That is 90... dont know why I said 45

zealous widget
#

or pi/2 radians

#

why using degree, it's weird

grizzled cloak
#

Hahah

tropic night
#

so a double tri-force diagram

zealous widget
#

are 1 and 2 connected?

grizzled cloak
#

Yes

#

Like eivl's drawing

tropic night
#

now your rules makes sense to me

grizzled cloak
#

Awesome!

tropic night
#

how do the user tell what different combinations are worth?

grizzled cloak
#

"blue red 3"

#

Means blue next to red is 3 points

#

And number of different colors is just a number

tropic night
#

so if thats the only input, your suppose to find the optimal solution that gives most points?

grizzled cloak
#

Yes

tropic night
#

are default points just one?

#

or zero?

grizzled cloak
#

0

#

All other arrangements dont yield points

tropic night
#

if one blue is next to two red, does it count points double?

grizzled cloak
#

Yes

tropic night
#

meaning  blue red 3 is equal to red blue 3

#

or ... hmmm.. maybe not

grizzled cloak
#

I think it is. Not sure though

tropic night
#

one blue next to one red, the rest other colours, how many points? 3 or 6?

grizzled cloak
#

3

tropic night
#

then order matters..

grizzled cloak
#

Wait

tropic night
#

lets see.. do i have enough to go on.

zealous widget
tropic night
#

yeah. but i like that you use networkx, is my favorite pip package

zealous widget
#

it's the reason i started using python

tropic night
#

well.. there you go 😄

marsh void
#

Hey eivl :)

tropic night
#

hey 😄

marsh void
#

raise Oops('An error has occured!')

grizzled cloak
#

For the pic I sent, the preferences are:
Red blue 3
Red cyan 2

#

and the score is 2+3+2=7

zealous widget
#

i can get networkx to draw the nodes the colors of the plants to without much work at all

grizzled cloak
#

But I dont think its the optimal score. Its just for that pic

tropic night
#

15?

#

thats not right is it?

grizzled cloak
#

Ahahha

#

7

tropic night
#

yes.. 7

#

i agree

grizzled cloak
#

Oh man im messing this up

tropic night
#

well.. i ask when i do not understand something. think we have gotten to the bottom of this..

grizzled cloak
#

Nice!

tropic night
#

now i have a doctors appointment before i travel to the US for two weeks 😄

#

ill solve this when i get back.

grizzled cloak
#

Cool!

#

From the us or doctor hahaha

marsh void
#

Lol

tropic night
#

!remind 18 d do 136174338633105408 flowerbed puzzle

night quarryBOT
#
Affirmative!

Your reminder has been created successfully!

marsh void
#

@tropic night are you like, actually coding in ST3 for 14 hours, or just have it opened? xd

tropic night
#

today that having it opened. but i normally work 10-12 hour days

marsh void
#

Wow, that’s a lot

#

I mainly code for ~5 hours a day

tropic night
#

i like coding in pythong 😄

zealous widget
#

i like girls that wear pythongs

marsh void
#

Lol

tropic night
#

thats strangely erotic and off-topic.

marsh void
#

lmao

grizzled cloak
#

Hahaha

zealous widget
#

are python turn-ons' just called pyth-ons

marsh void
#

Lol

zealous widget
#

i'll stop now

#

is there a clever way to solve this without trying all combinations

tropic night
#

There is, hence the question. Can you do better the brute Force?

zealous widget
#

i just know the brute-force method isn't much code

marsh void
#

Haha

zealous widget
#

but it's terribly inefficient

marsh void
#

^

grizzled cloak
#

Yeah. You can and should solve it smartly. But I just have fun doing it inefficiently

marsh void
#

So do I :D

tropic night
#

When in doubt brute force

zealous widget
#

i mean this is just multiset combinations and then weight edges on the graph according to scores, and return the graph with the max sum of weights

#

we could not try combinations that were just rotations of combinations we've already tried, but that's probably extra code

#

having a hard time trying to say what i mean to say, probably time for bed soon

grizzled cloak
#

@zealous widget if you aren't too tired, could you explain networkx

zealous widget
#

it's a package for working with graphs

#

the combinatorial graph, not a plot

#

the tldr though, graphs in networkx are represented by a dict of dicts instead of maybe the more usual dict-way of representing a graph, but the dict of dicts allows one to save arbitrary node and edge data

#

i often try to translate problems into a problem on a graph though, since then i can piggy back off of graph algorithms already implemented in networkx

#

@grizzled cloak

grizzled cloak
#

Oooh looks nice

edgy kelp
#

@snow beacon the deobfuscate is quite clever, is num & 1 ^ 1 just some golfy way of getting if it's even or odd? And one more thing, the obfuscate requires a byte array because of the multi byte chars in utf-8, do you think there would be a shorter way that wouldn't use the bytearray itself?

#

I'm mad at the multiplied spaces being so fast even when their length is around 100 times more than the bytes

wind maple
#

num & 1 ^ 1 is basically not int % 2 == 0

cunning wave
#

Also it's not a golfy way, it's probably the most efficient way there is

edgy kelp
#

Not really up to date on my logical operators in python 😛 assume & is gonna be an and but no idea about the ^

#

guessing xor from the context here

cunning wave
#

^ is an XOR in all languages I am aware of

edgy kelp
#

not in spoken unfortunately

cunning wave
#

The only case I know where XOR is not written as ^ is in math where usually latex's \oplus is used

whole kiln
#

Yeah I see that symbol in more mathematical contexts

brazen geyser
#

i think ~n&1 might be a little bit faster

cunning wave
brazen geyser
#
>>> timeit('a & 1 ^ 1', globals={'a':2})
0.11904819999995198
>>> timeit('a & 1 ^ 1', globals={'a':2})
0.09850280000000566
>>> timeit('a & 1 ^ 1', globals={'a':2})
0.0982885000000806
>>> timeit('a & 1 ^ 1', globals={'a':2})
0.1534560000000056
>>> timeit('a & 1 ^ 1', globals={'a':2})
0.10074779999990824
>>> timeit('~a & 1', globals={'a':2})
0.10472330000015972
>>> timeit('~a & 1', globals={'a':2})
0.0987999999999829
>>> timeit('~a & 1', globals={'a':2})
0.0871998000000076
>>> timeit('~a & 1', globals={'a':2})
0.08496199999990495
>>> timeit('~a & 1', globals={'a':2})
0.08559029999992163
#
>>> timeit('~a & 1', globals={'a':2})
0.10865340000009382
>>> timeit('~a & 1', globals={'a':2})
0.09060550000003786
>>> timeit('~a & 1', globals={'a':2})
0.10017100000004575
>>> timeit('~a & 1', globals={'a':2})
0.10466139999994084
>>> timeit('~a & 1', globals={'a':2})
0.08186840000007578
>>> 
#

next few seem to be the same though

#

idk

cunning wave
#

Considering how much it fluctuates, especially on the first of your method test I think this depends on what else your machine is doing atm

brazen geyser
#

i havent gotten anything below 0.095 with 'a & 1 ^ 1' yet

cunning wave
#

The amount of logical operations is equal though so apart from loading 1 more integer from ram, which you shouldn't be able to measure that precisely using python (and is also influenced by caches etc) I don't see a reason why the speed should differ

brazen geyser
#
>>> timeit('a & 1 ^ 1', globals={'a':2}, number=10000000)
1.1928426000001764
>>> timeit('a & 1 ^ 1', globals={'a':2}, number=10000000)
1.0634661999999935
>>> timeit('a & 1 ^ 1', globals={'a':2}, number=10000000)
1.1656500999999935
>>> timeit('a & 1 ^ 1', globals={'a':2}, number=10000000)
1.1747745000000123
>>> timeit('a & 1 ^ 1', globals={'a':2}, number=10000000)
1.0864994999999453
>>> timeit('a & 1 ^ 1', globals={'a':2}, number=10000000)
1.06694379999999
>>> timeit('~a & 1', globals={'a':2}, number=10000000)
0.9139800000000378
>>> timeit('~a & 1', globals={'a':2}, number=10000000)
0.9485522999998466
>>> timeit('~a & 1', globals={'a':2}, number=10000000)
0.9740888000001178
>>> timeit('~a & 1', globals={'a':2}, number=10000000)
0.9637909000000491
>>> 
cunning wave
#

Should be an issue with how python actually implements the shit then

formal sandal
#

wtf

#

I was playing clash of code, and I got a problem with this statement: "You are given an integer. Output that integer + 0".

#

How is this a real problem?

marsh void
#

lol

#

maybe like, int0

#

I dunno lel

sick hound
#

you just have to output the integer I guess

marsh void
#

print(input())

#

hard lol

#

or like, maybe it checks the code?

#

print(int(input())+0)

formal sandal
#

Nope, print(input()) works.

#
lambda n:(lambda r:(''.join(reversed(["0123456789"[i%10]for i in r(r)((10).__rfloordiv__,n)]))))(lambda y:(lambda f,x:[x]if f(x)==0else [x]+y(y)(f, f(x))))```
#

Convert a positive integer to a string!

edgy kelp
#

Do not recommend putting a - there 😄

formal sandal
#

The function is actually quite simple if you break in down

sick hound
#

i bet it's just doing %10 and then recursing with //10 and then reversing it at the end

formal sandal
#

Yes, pretty much.

hollow patrol
#

ANONY!
Have you ever wanted to make an anonymous function without a 2000 character single lined lambda? Anony is for you!

my_func = function (
    whether (True) (
        anony.print(1),
        anony.print(2),
        whether (True) (
            anony.print(3)
        ), whether (not True) ( 
            anony.print(4)
        )
    ),
    whether (not True) (
        anony.print(5),
        anony.print(6),
        whether (True) (
            anony.print(7)
        ), whether (not True) ( 
            anony.print(8)
        )
    )
)

my_func()
>>> 1
>>> 2
>>> 3
``` This is valid anony code! (Well, it's just another thing I made though)
#

It's sarcasm by the way

#

I made it out of boredom, but I think it fits into estoric python because of how unpythonic and weird it is.

formal sandal
#

Well, you can make a multiline lambda.

#
lambda n: # the main function
    (lambda r:( # the recursion engine
            ''.join( 
                reversed(
                    ["0123456789"[i%10] # digit -> string
                        for i in
                        r(r)((10).__rfloordiv__,n)
                        # 142 -> [142, 14, 1]
                    ]
                )
            )
        )
    )
    (lambda y:
        (lambda f, x: # the `nreduce` function
                      # x -> [x, f(x), f(f(x)), ...] until f^n(x) == 0
            [x] if f(x)==0
            else 
            [x]+y(y)(f, f(x))
        )
    )
#

@hollow patrol so function takes some custom objects and returns a callable object?

hollow patrol
#

Yeah

snow beacon
#

I would assume the custom objects are functions as well.

hollow patrol
#

You would think, but no

#

To allow for variables in the anonymous function, I had to use a custom class for more control

formal sandal
#

Well, whether could be a combination of (condition, statements_then, statements_else)

hollow patrol
#

whether takes two parameters

#

well 3

#

condition, functions to call if it succeeds, and the variable list (auto filled in tho using the manipulation)

snow beacon
#

Is it curried?

formal sandal
#

Maybe you can also do lazy condition evaluation.

hollow patrol
#

I don't know what curried is in programming.

formal sandal
#

Like whether(lambda: x > 0)

hollow patrol
#

I'd rather not, that's lower readability to me

snow beacon
#

Turning f(1,2,3) into f(1)(2)(3)

hollow patrol
#

No

#

It turns f(1, 2, 3) into f(1, 2, 3)()

snow beacon
#

I was looking at whether and it's called on a condition then on an anony object.

#

But they're in separate brackets.

hollow patrol
#

Whether can actually be called on any boolean too

#

It can be called on a boolean, or an anony function object

formal sandal
#

I'd rather not, that's lower readability to me
But it means that the condition will only be evaluated once, on the definition of my_func.

#

Oh, it can be called on a function.

#

Then it's ok

hollow patrol
#

Yep

#

Not regular functions though

#

But anony variables work as functions (it's a bit complicated)

#

Essentially, you can call it on a variable, which is evaluated each time it runs

#

whether(var('var_name')) is perfectly fine

#

Speaking of variables, using some instance manipulation, I got those to work

formal sandal
#
# The Zen of Esoteric Python
0 = Ugly is beautiful
1 = Complicated is better than complex
2 = Complex is better than simple
3 = Implicit is better than explicit
4 = Implementation-dependent is better than just implicit
5 = There should be one-- and preferably only one --line
6 = Anonymous function are one honking great idea -- let's do more of those!
hollow patrol
#

well

#

in that case, anonymous function is trying to leave the esoteric python garden lol

formal sandal
#

Well, functions are anonymous too...

hollow patrol
#

Also

#

the function ( ) output is actually wrapped around another function

#

def anonymous_function(): pass this function

#

is what it functools.wraps around

#

so when you print a function ( ) object

#

you get

#

<function anonymous_function at STUFF>

formal sandal
#

I have an idea for an esoteric challenge.

#

Russian poet Mayakovsky used to write poems in a special style where the lines would go in a 'ladder' like this:

#

Maybe it would be cool to make a program that would look like this:

something:
    something:
        something
something:
    something:
        something
...
#

But without cheats like if True or for i in [1]

hollow patrol
#

v_gz

#

how are we supposed to do it without cheats though?

formal sandal
#

Well, that's a difficult question (what counts as a cheat?)

hollow patrol
#

an if x where x is always True

#

and an always 1-length iterable iteration

#

and a while loop which breaks

#

after its done

formal sandal
#

Well...

condition = ...
if condition:
    some_code
if not condition:
    that_same code
hollow patrol
#

true

#

or

#
if x:
    pass
else:
    pass```
formal sandal
#

Maybe we shouldn't make it a formal challenge, just make it an artistic contest.

hollow patrol
#

Wait...

#

How about you don't limit it to cheats

#

But make it a competition

#

Shortest answer 🙂

#

and make all answers have to run the same lines maybe?

formal sandal
#

!e

for i in "ab":
    for x in locals, globals:
        x()[i] = 1
for i in range(10000):
    if a < 1000:
        a, b, _ = b, a+b, print(a)
night quarryBOT
#

@formal sandal Your eval job has completed with return code 0.

001 | 1
002 | 1
003 | 2
004 | 3
005 | 5
006 | 8
007 | 13
008 | 21
009 | 34
010 | 55
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/irumusatan

formal sandal
#

Even better (= worse): the program should only consist of function (or generator) definitions, one of which is main, and main will be run.

hollow patrol
#

Might be really easy (= tricky)

#

For people

formal sandal
#

The whole point of this is being tricky!

hollow patrol
#

Exactly

#

@formal sandal Disallow imports, too

#

That makes it even more tricky if you can't import

formal sandal
#

Well, it will be impossible to import if it's just function definitions.

#

Unless you use __import__, of course.

snow beacon
#

Can't you import inside functions?

formal sandal
#

You can. But you won't be able to do that with the three-line ladder structure.

#

Well, you will be able to import...

#

hmm

#

Well, you can put statements separated by ;

#

Maybe this should be banned as well.

snow beacon
#

exec is a function.

formal sandal
#

Oh, exactly.

#

There are probably going to be a lot of things to be banned.

snow beacon
#

You could compile an import, assign it to the __code__ of a function, then call the function.

#

You could write the bytecode by hand, even.

snow beacon
#

@Numerlor#9066 Regarding using bytearray to support Unicode sequences: bytes and bytearray are mostly equivalent, right? If you want the deobfuscate function to return bytes you can remove the .decode() at the end, and for it to accept bytes as parameters remove the ord. For obfuscate to return bytes, put a b before the first two string literals. For it to read in bytes rather than strings, remove that ord as well. I haven't tested any of this, but it should work.

rugged sparrow
#
encoder = lambda s,d=0,o=ord,c=chr:''.join([[(lambda x:c(x)+c(o(C)-x))(__import__('random').randrange(o(C)))for C in s],[c(sum(map(o,C)))for C in zip(s[0::2],s[1::2])]][d])
``` @marsh void  shorter now
#

gonna make it worse now 🙂

marsh void
#

Lol

rugged sparrow
#
encoder = lambda s,d=0:''.join(map(lambda C:chr(sum(map(ord,C)))if d else(lambda x:chr(x)+chr(ord(C)-x))(__import__('random').randrange(ord(C))),[s,zip(s[0::2],s[1::2])][d]))``` @marsh void 174 (its longer but more confusing)
rugged sparrow
#
encoder = lambda s,d=0:''.join(map(lambda C:[(lambda x:chr(x)+chr(ord(C)-x))(__import__('random').randrange(ord(C))),C][d],map(lambda C:chr(sum(map(ord,C))),[s,zip(s[0::2],s[1::2])][d])))``` also longer but even worse
marsh void
#

lol

rugged sparrow
#
>>> class A:pass
... 
>>> class B(A):pass
... 
>>> c('B')
<class 'object'>
>>> c('B',c('A'))
<class '__main__.B'>
>>> c('B',A)
<class '__main__.B'>``` i made an interesting utility function
#

it uses *.__subclasses__ to get a subclass from a string. by default it does object.__subclasses__()

#
c = lambda s,o=object:{c.__name__:c for c in o.__subclasses__()}.get(s,o)
hollow patrol
#

An update on how my anonymous function creator works

#

I have a custom anony func class

#

You can call func() to get its value

#

You can do func + 5 to get another function

#

(func + 5)() = func() + 5 using anony

#

And a bunch of other stuff

#

All for code that looks like this

#
this = function ('a4') (
    when(False) (
        anony.print(1),
    ),
    owhen(False) (
        anony.print(2)
    ),
    owhen(False) (
        anony.print(3)
    ),
    otherwise (
        anony.print(4),
    )
)
this(5)
>>> 4```
#

So much complicated code, just for stuff like that to exist in Python

pure dew
#

LADS

#

look at this shit

#

STag: {((str! x): x * 2) for x in {..100@4} when x % 2 == 0}
Python translation: {str(x): x * 2 for x in range(101, 4) if x % 2 == 0}

Reduced AST:

_simple_stmt
  dict
    dict_comp
      dict_comp_for
        fun_call str                 <-- this is the key for the dict
          fun_args x
        mul_expr                     <-- this is the value for the dict
          x
          <built-in function mul>    <-- `x * 2`
          2
        comp_ident x                 <-- this is the dict comprehension variable
        range                        <-- this is the object we're iterating over
          range_comp
            end_idx     100          <-- this is inclusive, unlike `range`
            range_step  4
        comp_expr                    <-- this is the `when`
          eq_expr                    <-- `== 0`
            mul_expr                 <-- `x % 2`
              x
              <built-in function mod>
              2
            <built-in function eq>
            0
#

This isn't a python transpiler, I just typed out the python bit so it's easier to grok

brazen geyser
#

what did you use to generate that chart @pure dew

#

also what's STag

#

cant find any hits googling

pure dew
#

I used pydot

#

and STag is a little lispy DSL I'm making for my bot

#

a python vm language, more or less

#

@brazen geyser

brazen geyser
#

cheers

pure dew
#

Basically python lambdas in lisp syntax with some haskell features

plucky meteor
#

can something similar be done (that actually works my example doesn't work obviously)

class A:
    def hi(self):
        print("hello")


A.__name__ = "B"

s = B()
s.hi()

pure dew
#

you could probably just manipulate globals

#

why tho

plucky meteor
#

well no reason just thougth about doing it

hollow patrol
#

@plucky meteor How about...

#
class A:
    def hi(self):
        print("hello")
globals()["B"] = globals().pop("A")

s = B()
s.hi()```
plucky meteor
#

nice

#

pycharm hates it but who cares. thanks

edgy kelp
#

Pycharm is not the only one :D

gilded orchid
#

oh wow that's bad

#

never knew you could pop from a dict

rugged sparrow
#
>>> class A:
...     def hi(self):
...             print('hello')
...
>>> B = A
>>> s = B()
>>>
>>> s.hi()
hello
>>>``` @hollow patrol why not this
hollow patrol
#

or that

#

but that doesn't delete A

rugged sparrow
#

del A lol

grave rover
#

@gilded orchid it's useful for kwargs in subclasses

#

Anyways I'm working on a pylike to asm transpiler atm

pure dew
#

@grave rover yo long time no see

#

hows pycss coming?

pure dew
#

So I got literal inlining done

#
>>> p("(3 ^ 5) / 2")
Tree(stmt_list, [3.0])
stmt_list       3.0

#
>>> p("(3 ^ 5) / a")
Tree(stmt_list, [Tree(mul_expr, [6, <built-in function truediv>, Tree(ident, ['a'])])])
stmt_list
  mul_expr
    6
    <built-in function truediv>
    ident       a

``` here's where it can't
#

At this point its functional as a glorified literal expression parser

marsh void
#

Is there a way to get the <class 'coroutine'> without importing asyncio or defining a coro?

sick hound
#

!e ```python
print(object.subclasses()[53])

night quarryBOT
#

@sick hound Your eval job has completed with return code 0.

<class 'coroutine'>
sick hound
#

@marsh void

distant wave
#
>>> [i for i in object.__subclasses__() if i.__name__ == "coroutine"]
[<class 'coroutine'>]
#

You'd probably also want to filter on .__module__ == 'builtins' to make sure nobody's.. 'special' code breaks that

marsh void
#

Lol yeah

marsh void
#

Ok I changed it to the better version, thanks everyone for suggestions :)

#
import coro_writer  # noqa
import gd
client = gd.Client()
client.get_user(71).run()

I think this can actually be useful 🤔

rugged sparrow
#
c = lambda s,o=object:{c.__name__:c for c in o.__subclasses__()}.get(s,o)
``` @marsh void this would work. just call it like ``c('coroutine')``
marsh void
#

Haha, yeah

brazen geyser
#
>>> class Test:
    items = set()
    def __and__(self, other):
        return self.items & other

    
>>> timeit('a&b', globals={'a': Test(), 'b':set()})
0.2259137999935774
>>> timeit('a&b', globals={'a': Test(), 'b':set()})
0.22531330000492744
>>> timeit('a&b', globals={'a': Test(), 'b':set()})
0.2604912999959197
>>> timeit('a&b', globals={'a': Test().items, 'b':set()})
0.08967529999790713
>>> timeit('a&b', globals={'a': Test().items, 'b':set()})
0.09064000000944361
>>> timeit('a&b', globals={'a': Test().items, 'b':set()})
0.09115980000933632
>>> 
#

kinda surprised by this

#

is there some hacky way to speed this up? maybe with __slots__ or ctypes magic?

#

i mean i was expecting a slow down but not by this much

wind maple
#

You're doing the timeit wrong

#

wait no

#

I'm actually not sure how globals works 🤔

#

I know there's some thing to make this slightly faster but I can't remember what it is

marsh void
brazen geyser
#

@wind maple if you remember it lmk pls

wind maple
#

ye

gentle pagoda
#

question about bytecode. values are saved as an int8, int32, etc, depending on their value. but now does the vm know when to read the next instruction if the argument can be arbitrarily long? ```
28 0 LOAD_CONST 1 (100)
2 STORE_FAST 0 (a)

29 4 LOAD_CONST 2 (1000)
6 STORE_FAST 1 (b)```

sick hound
#

"values are saved as an int8, int32, etc, depending on their value." well this is wrong

#

number values in bytecode are (probably) saved internally as python int objects

#

and the argument to LOAD_CONST is identified by an index, it's not just the actual value

#

specifically, it's an index into the co_consts tuple which is stored on the code object

gentle pagoda
#

Oh. But I thought the number next to (100) was the amount of bytes it is saved as?

sick hound
#

1 is the actual number in the argument of the instruction

gentle pagoda
#

Are there any resources on learning about bytecode more? Ibe clearly missed a lot 😅

#

Oh I see

sick hound
#

64 01 7d 00 64 02 7d 01 here's the raw bytecode of the instructions you posted up there, in hex because it's easier to read

#

64 is just the number for LOAD_CONST

#

01 is the 1 in the 1 (100) part

#

the (100) is from checking the second (first but arrays start from 0) element of the co_consts on the code object

#

7d is STORE_FAST

#

00 is the 0 in the 0 (a) part

#

the (a) is from co_varnames

#

and then 64 02 7d 01 is the same stuff but with different numbers

#

co_consts[2] is 1000 and co_varnames[1] is b

gentle pagoda
#

where are co_contants stored in the binary?

brazen geyser
gentle pagoda
#

@brazen geyser thanks, those look really useful :) do you know what the layout of pyc files are? thats what im struggling with most :p

brazen geyser
#

i believe it's just marshalled code objects

gentle pagoda
#

yeah ive had a look into marshal

grave rover
#

Yo

gentle pagoda
#

and i get the basic structure of co_code, co_consts etc. just not sure how to go about ordering it in a pyc file

grave rover
#

Pyc format isn't that hard

gentle pagoda
#

other than compiling it to a codeobject them using marshal.dumps

#

oh i cant seem to find any resources on it at all

grave rover
#

Pyc Header:
version (unsigned short), then a CRLF, 4 null bytes, timestamp (int), size (int), 16 null bytes

#

The body is really just a compiled frame

gentle pagoda
#

compiled frame?

grave rover
#

uh

#

Hard to explain

#

It's kinda similar to a code object

gentle pagoda
#

hm ok. is there any documetation on those?

grave rover
#

Nope

#

But assuming it's a code object works fine for parsing

#

Aside from identifier they have exactly the same structure