#esoteric-python
1 messages · Page 74 of 1
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
Yeah I thought that's what it was doing. Never went through my notes tho
ya'll remember that random text generator challenge?
No?
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
i found the challenge i wrote in coco; the whole thing was one lambda
and it produced pretty sensible results
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
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
@zealous widget is there a function to get all partitions?
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)]
hmm,
TypeError: can only concatenate list (not "str") to list
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
how do you filter a result by len of array?
l = [l for l in s if all(1<len(r)<5 for r in l)]
s is the list of partitions
ahh
that would filter the partitions to only the ones with no groupings greater than 4 or less than 2
hmm ok and now you just sort with a key that assigns a score to the array if it has x leading zeros?
something like that
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
@zealous widget i kinda want to try to make that return
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
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
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
ah so you make it into a set to remove duplicates?
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
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']
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?
hahah no, i didnt golf it
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
Im surprised itertools doesnt have a function for this
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
now sort it alphabetically and look at the spaces
Hm?
Does sort work recursively?
When sorting nd lists does it sort the higher d lists?
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])
one-lined
one-sec, lemme put the variables in order
i dunno if that makes a difference
i did have fun
Awesome!
hey @zealous widget is it cool if i use your code?
idc, i uploaded it to my golf repository and it uses the unlicense there
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!
"""
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)
"""
ahh
how did you calculate those? lets say its 30 digits instead of 11?
or some number n
yeah but how would i calculate a similar list for n?
dont they just have to add up to n?
and not be the same thing twice?
and be between 2 and 4
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
well. my approach just broke pycharm.
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]]
and pycharm is using 24GB of ram
christ
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
lol
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
I love pycharm freezing up when the python console is stuck on something
force ending the process works but... why?
yeah....
does it run in the gui thread or what 😄
light weight spyder to the rescue
@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
why do we need to order them?
be cau se that is different from bec au se even though they have the same unordered partition 3,2,2
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
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?
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
list(multiset_permutations([3,2,2]))
Out[5]: [[2, 2, 3], [2, 3, 2], [3, 2, 2]]```
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
there was a reasonable solution here if you scroll a bit https://stackoverflow.com/questions/18935813/efficiently-calculating-unique-permutations-in-a-set
sympy is probably got a good implementation though
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 🙂
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
i have no idea, i've never touched php
haha ok
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
yeah, i wouldn't see my self using that a lot though
i'd have used it a few times by now, but not too often
it specifically mentions php loops too
guido shot it down though: https://mail.python.org/pipermail/python-3000/2007-July/008663.html
wait do arrays start at 1 in php???
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
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!
Thanks!
np
_ =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:"+_))
😄
doesn't exec feel cheaty
what if you first split the sting into groups of 4 and then tried to push them around to get rid of leading zeros?
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```
@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 :)
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
Either way works
i thought you would prefer the fewest groupings
i have my golf scored that way
finds fewest leading zeros and then fewest groupings
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
@zealous widget You do that for the bwinf contest?
what's that?
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>]```
A function, f(n), that produces some source code that evaluates to n again. n can be any string, including one with Unicode characters.
⬆ This one was diabolical to debug; all the parts need to fit together perfectly. Don't try to read it without a syntax highlighter.
@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 😬
i wasnt asking for help, i already solved it
i was just posting it for fun
i used a different completely different approach
different from what?
what salt posted
i havent golfed it yet
in theory it should only be 1 loc
mine is 3 lines
if you count the line with the input 4
hmm?
when i tell you, you will change your solution .-.
i doubt it
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? 😂
but thats kind of cheating
why?
aren't imports allowed?
yes but thats not the point
i haven't installed any additional packages
just pure python lib
is the import of packages that already come with python also forbidden?
what
so how did you solve it?
the concept behind the tool i used exists since 1950 ^^
because i like mine
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
i am yes
@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..
0150 701 5061
01 1000 0011 5615 61
it got the first one right but the second one is wrong,
you have 2 blocks starting with a 0.
thats right
oh sry i just split it up slightly differently 🙂
it should be the smallest amout of block starting with 0
all good
and u can't have less than 2 block with 0 as first digit
so howd you do it
sry if im not answering instantly, im playing some games with my little brother
👍
Sad thing modules are not callable
I am 15 though, like really xd
https://github.com/NeKitDS/python_scripts/blob/master/encoder/encoder.py does this count as an obfuscator?
I think it counts. It's simple, but that doesn't have to be a bad thing.
You don't have to do it as crazily as I did.
My decoder contains the encoder inside it, unnecessarily.
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 "
@sick hound did you do any of the other questions form the bwinf?
nope
I know this is not new, but it would be cool to have a language with a few hundred symbols
It actually works.
I guess you could encode some complicated algorithm like this... Would it count as an obfuscation?
https://github.com/NeKitDS/python_scripts/blob/master/encoder/encoder.py can someone help me a bit with obfuscating these three functions? 
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!
not esoteric enough xd
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
Hey, juanita :)
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 :)
👍🏻 using 0 just felt like something that might not be allowed.
1_000_000_000 and 999_999_999 have solutions too btw
31625, 375
it was fast, did not expect that xD
102 should be impossible I think
my program says so.
Yup
24144 -> 515, 491 (265225 - 241081 = 24144)
here it is for the number of members in the server
i have an insanely quick solution but idk how to check if it's impossible
you could set a "limit" or use math (I used math)
mine does 1000000000 in 0.005 seconds
My first touch on esoteric challenges :)
let me just put in timeit real fast
what sort of thing would i check to see if it's impossible though?
Here's my solution's times
@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?
just wait, I messed up when I put in the timeit somehow xD
this is the most useful advice of all time, thank you lmao
how do you try all of them 🤔
You can know m will always be greater than or equal to sqrt(n)
And at most it'll be 2n
oh right okay, i just figured that out right as you said it
0.151 s
Real time: 0.151 s
User time: 0.135 s
Sys. time: 0.014 s
That's crazy fast for all numbers, jeez
I need to see your impl lmao
bc mine should mathematically be the fastest possible method
wait, I just ran it for 10**9 since that's what @brisk zenith said.
Oh
let me run it for all
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
If you get it under 2s you'll have a micro optimization of mine lol
well, I think it's taking longer than that it looks xD
xD
well, it's fast for just 1 number. but your's must be a lot faster then xD
changed the way I loop and it cut it down to 1.7 S xD
rekt 🔥
I looped from math.floor(math.sqrt(n)) to infinity, before, changed to n to -infinity
Linear solutions should be way slower than mine 🤔
well obviously, do you not know the power of lööps bröther?
Well I calculate a solution directly
wait, that can be done?
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)
can't math.floor(math.sqrt(n)) be massively optimised via int(n ** 0.5)?
Not sure how your loop was so fast
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
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
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
use //
Imagine using is for integers lol
idk it might be faster or something
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```
@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
new eso challenge?
@pure dew ignore solutions, look for large post by me
okay
yhe, mine is pretty slow. I somehow messed up trying to make it better. making everything impossible.
that's why it was "fast"
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
idk what I did xD
New tests work fine, yeah
Tho people could use this as cheat sheet for impossibility I guess
But yeah, mine should be fastest
is will be faster than == for the preloaded ints (-5 - 256 in cpython) since it has a lot less to do
Ah it's -5 to 256
ic
But yeah an id check is way faster than checking eq and stuff
Lol clicking that link crashes my discord app
sounds like a you problem :^)
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
oi mart
hm?
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
yea
How does that make sense
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
Ehehe thanks
could prob minimize it a bit
Since you're onelining encoders, how could I shorten the bin functions except stuff like whitespace and car names in here? https://gist.github.com/Numerlor/454b7a1b258e5b984b4b5a433cff940b
@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
''.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.
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
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
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?
I'm tempted to do an encoding only using zalgo characters
Hmm, I made another one with that idea - reverse every steps letters, then encode by shifting ord by a key
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
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?
What would be cool is that we wrap it around 0-256 ord for e.g, so 257 will be 0
because if you have something like hello my name is lvie what is yours?
those right-to-left characters do weird things
might f-up text selection
Oh hey eivl
i don't think all the behavior is predictable
oh you mean those unicode that looks like normal alphabets but looks right to left? lol
@snow beacon just figured out my encoder errors on null bytes, gotta fix that
there's some esoteric unicode things i'm sure i've read about before
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.
@snow beacon thanks that's certainly beyond what I could come up with :D
lol
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?
Interesting challenge. Do eleborate.
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"
I was just about to say.
n = 8 has a solution for example
And the thing to optimise for was speed rather than code size?
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)
is there a limit to m and k in the previous case?
simple task, but compressing might get tough :P
@crystal mica I mean there's an easy solution but it's guaranteed to be possible within those limits
Does s=input();print(s[1:]+s[:1]) work?
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
lol
1 char
h,*e,y=input();print(h+e+e+y) is another way
lol
Thanks
screw smaller solutions that one's just great
alright lemme find an actually interesting task
(In the meantime I am researching the difference of squares task.)
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
@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
Wonder how the encoding solutions compare in speed
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
I mean some may require moving half but it cant ever be more
are these graphs always planar or something?
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
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
whats the input? some array of numbers?
input will be the same as shown
another example:
3 4 # rooms, corridors
1 2
2 3
3 1
3 2
output:
2
3 1
3 2
yeah, i don't know what that means
wdym
i don't know how to get a network from those numbers
I just give you all connections in a graph/network
where?
those are edges, ok
2 3 is a connection from 2 to 3
why didn't you say so
I did
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.
first the number of rooms and corridors, then all corridors
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
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)
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
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()]:
interested in seeing a solution that doesn't take that long tbh
i mean, i assume you actually want a golfed spanning tree algorithm and not piggyback off of another module
kinda :P
I guess a DFS is all you really need, once you find a node you've seen before just remove the edge
yep, just add edges until all nodes are accounted for
@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
And with that, I should probably get to bed.
@tropic night imma post the challenge here, feels like a better fit.
yes thanks.. i have to put on my moderator hat now.. hold on
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```
you could improve the score by switching red and pink
Which one of the reds?
oh, nevermind, cyan and blue
But blue+red gives 1 point more than cyan+blue
no, i mean the colors you specified were cyan and blue and not what i was thinking
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
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
the second flower, does it not have 6 as a neighbor?
6 is on the opposite side though
It doesnt loop around
Salt, grid-graph sounds fancy, what does it do?
it's a graph thats connected like a grid
so these are not the neighbors for the flower 1?
6 isnt no
The way I wrote it it looks like a square turned 45° but its more elongated vertically
nx.draw_spectral(G)
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
you can just add those two edges manually, i guess
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
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
graph drawing isn't the friendliest thing
i think pi/2 radians actually
thats a 90 degree turn
Hahah
are 1 and 2 connected?
Awesome!
how do the user tell what different combinations are worth?
"blue red 3"
Means blue next to red is 3 points
And number of different colors is just a number
so if thats the only input, your suppose to find the optimal solution that gives most points?
Yes
if one blue is next to two red, does it count points double?
Yes
I think it is. Not sure though
one blue next to one red, the rest other colours, how many points? 3 or 6?
3
then order matters..
Wait
lets see.. do i have enough to go on.
trying to get networkx to draw this is a pain
yeah. but i like that you use networkx, is my favorite pip package
it's the reason i started using python
well.. there you go 😄
Hey eivl :)
hey 😄
raise Oops('An error has occured!')
For the pic I sent, the preferences are:
Red blue 3
Red cyan 2
and the score is 2+3+2=7
i can get networkx to draw the nodes the colors of the plants to without much work at all
But I dont think its the optimal score. Its just for that pic
Oh man im messing this up
well.. i ask when i do not understand something. think we have gotten to the bottom of this..
Nice!
now i have a doctors appointment before i travel to the US for two weeks 😄
ill solve this when i get back.
Lol
!remind 18 d do 136174338633105408 flowerbed puzzle
Your reminder has been created successfully!
@tropic night are you like, actually coding in ST3 for 14 hours, or just have it opened? xd
today that having it opened. but i normally work 10-12 hour days
i like coding in pythong 😄
i like girls that wear pythongs
Lol
thats strangely erotic and off-topic.
lmao
Hahaha
are python turn-ons' just called pyth-ons
Lol
i'll stop now
is there a clever way to solve this without trying all combinations
There is, hence the question. Can you do better the brute Force?
i just know the brute-force method isn't much code
Haha
but it's terribly inefficient
^
Yeah. You can and should solve it smartly. But I just have fun doing it inefficiently
So do I :D
When in doubt brute force
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
@zealous widget if you aren't too tired, could you explain networkx
it's a package for working with graphs
the combinatorial graph, not a plot
might be best to just read their docs https://networkx.github.io/
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
they have a massive number of algorithms implemented, and they seem to add more with each new version: https://networkx.github.io/documentation/latest/reference/algorithms/index.html
@grizzled cloak
Oooh looks nice
@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
num & 1 ^ 1 is basically not int % 2 == 0
Also it's not a golfy way, it's probably the most efficient way there is
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
^ is an XOR in all languages I am aware of
not in spoken unfortunately
The only case I know where XOR is not written as ^ is in math where usually latex's \oplus is used
Yeah I see that symbol in more mathematical contexts
i think ~n&1 might be a little bit faster
All hail the oplus
>>> 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
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
i havent gotten anything below 0.095 with 'a & 1 ^ 1' yet
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
>>> 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
>>>
Should be an issue with how python actually implements the shit then
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?
you just have to output the integer I guess
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!
Do not recommend putting a - there 😄
The function is actually quite simple if you break in down
i bet it's just doing %10 and then recursing with //10 and then reversing it at the end
Yes, pretty much.
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.
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?
Yeah
I would assume the custom objects are functions as well.
You would think, but no
To allow for variables in the anonymous function, I had to use a custom class for more control
Well, whether could be a combination of (condition, statements_then, statements_else)
whether takes two parameters
well 3
condition, functions to call if it succeeds, and the variable list (auto filled in tho using the manipulation)
Is it curried?
Maybe you can also do lazy condition evaluation.
I don't know what curried is in programming.
Like whether(lambda: x > 0)
I'd rather not, that's lower readability to me
Turning f(1,2,3) into f(1)(2)(3)
I was looking at whether and it's called on a condition then on an anony object.
But they're in separate brackets.
Whether can actually be called on any boolean too
It can be called on a boolean, or an anony function object
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
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
# 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!
well
in that case, anonymous function is trying to leave the esoteric python garden lol
Well, functions are anonymous too...
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>
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]
Well, that's a difficult question (what counts as a cheat?)
an if x where x is always True
and an always 1-length iterable iteration
and a while loop which breaks
after its done
Well...
condition = ...
if condition:
some_code
if not condition:
that_same code
Maybe we shouldn't make it a formal challenge, just make it an artistic contest.
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?
!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)
@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
Even better (= worse): the program should only consist of function (or generator) definitions, one of which is main, and main will be run.
The whole point of this is being tricky!
Exactly
@formal sandal Disallow imports, too
That makes it even more tricky if you can't import
Well, it will be impossible to import if it's just function definitions.
Unless you use __import__, of course.
Can't you import inside functions?
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.
exec is a function.
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.
@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.
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 🙂
Lol
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)
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
lol
>>> 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)
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
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
what did you use to generate that chart @pure dew
also what's STag
cant find any hits googling
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
cheers
Basically python lambdas in lisp syntax with some haskell features
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()
well no reason just thougth about doing it
@plucky meteor How about...
class A:
def hi(self):
print("hello")
globals()["B"] = globals().pop("A")
s = B()
s.hi()```
Pycharm is not the only one :D
>>> class A:
... def hi(self):
... print('hello')
...
>>> B = A
>>> s = B()
>>>
>>> s.hi()
hello
>>>``` @hollow patrol why not this
del A lol
@gilded orchid it's useful for kwargs in subclasses
Anyways I'm working on a pylike to asm transpiler atm
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
Is there a way to get the <class 'coroutine'> without importing asyncio or defining a coro?
!e ```python
print(object.subclasses()[53])
@sick hound Your eval job has completed with return code 0.
<class 'coroutine'>
@marsh void
>>> [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
Lol yeah
I had used very funky way to get a coroutine class here
https://gist.github.com/NeKitDS/f4fdc00d529510c565baf75c06229575
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 🤔
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')``
Haha, yeah
>>> 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
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
https://gist.github.com/NeKitDS/f4fdc00d529510c565baf75c06229575 I’ve just updated this thing; made some more functionality and stuff
@wind maple if you remember it lmk pls
ye
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)```
"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
Oh. But I thought the number next to (100) was the amount of bytes it is saved as?
1 is the actual number in the argument of the instruction
Are there any resources on learning about bytecode more? Ibe clearly missed a lot 😅
Oh I see
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
where are co_contants stored in the binary?
the best resources ive seen so far are: https://docs.python.org/3/library/dis.html#python-bytecode-instructions and this huge switch statement implementing them all: https://github.com/python/cpython/blob/master/Python/ceval.c#L1319
@brazen geyser thanks, those look really useful :) do you know what the layout of pyc files are? thats what im struggling with most :p
i believe it's just marshalled code objects
marshal being this: https://docs.python.org/3/library/marshal.html
@grave rover would be the one to ask bout it more, he's working on a whole project for parsing PYC's iirc
yeah ive had a look into marshal
Yo
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
Pyc format isn't that hard
other than compiling it to a codeobject them using marshal.dumps
oh i cant seem to find any resources on it at all
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
compiled frame?
hm ok. is there any documetation on those?