#esoteric-python
1 messages ยท Page 62 of 1
@frosty wyvern Your eval job has completed.
24
Sorry, but you may only use this command within #bot-commands.
wat
>>> sys.getsizeof(x)
66
>>> object.__sizeof__(x)
32
>>> x.__sizeof__()
42``` wat
(x is a special object that overrides __sizeof__, but sys.getsizeof and object.__sizeof__ are entirely untouched)
hmm.. how is sys.getsizeof different to object.__sizeof__()?
from the docs:
getsizeof() calls the objectโs sizeof method and adds an additional garbage collector overhead if the object is managed by the garbage collector.
oh hmm i see
apparently garbage collector need more space than object itself, lol
fair enough
that doesn't make sense though
sys.getsizeof("hi") < object.__sizeof__("hi")```
from what i can see, sys.getsizeof(obj) just calls obj.__sizeof__()
yes
it makes sense because you are calling object.__sizeof__
while you should call here str.__sizeof__
>>> sys.getsizeof("hi") < str.__sizeof__("hi")
False
yup
>>> sys.getsizeof(x)
1000000023```
i've written some functions to make memory manipulation a bit easier btw ```py
mem_replace(1, 0)
print(1 == 0) # prints True
mem_switch("hello world!", "goodbye world.")
print("hello world!") # prints 'goodbye world.'
stuff = mem_read_object("hello world!")
print(stuff) # prints the memory content of "goodbye world."
not sure if i should keep working on it (more after the jam)
could you share a code snippet to see how this is implemented?
that's all of it for now
oh i missed the import ctypes at the top
there you go
it's quite simple, but makes stuff easier
ok through the ctypes I see
yeah
I just was wondering how did you access the memory, since I haven't seen any python functions to manipulate memory tables.
ctypes is pretty useful, but it's segfaults for days. i promise that using the above code will result in segfaults and interpreter crashes :D but that usually happens when the program is finished.
Yeah I've used it a lot when working with .dlls through the python
i've never worked with .dlls
that is pretty straight forward with the ctypes, you just load that dll file and then manipulate with it using ctypes data structures
@brisk zenith you can literally override literal values???
yeah
@pure dew that happens because of string are quite expensive and are immutable. So what happens is that python creates a memory table where it stores all the strings. Then when you create a new string, it will try to find same string in the table, if there is such a string, then it will just bound your new string var to existing memory pointer instead of creating a new one in the memory
hm?
cus cpython caching
mem_switch(1001, 1002)
print(1002) # prints 1001
oh
it's funky.
it doesn't work for singletons of course though
oh hey i found a little bug
or no, i didn't i don't think
yes i did
btw does not work for me ๐
In [5]: mem_switch(10004, 10005)
In [6]: print(10005)
10005
it doesn't work properly in a REPL
which python?
well, i've tested it on 3.7
hm, does not work for me on 3.6
well it works in 2.7.15 for me
ยฏ_(ใ)_/ยฏ
just not in a REPL
mem_switch("hello", "hi")
print "hello" # prints "hi"```
with the strings it should work
it should not work with the numbers
I think the reasons is that repl is running in optimized mode
yeah, probably.
because in repl
a = 10000000004
b = 10000000004
print(a is b)
results in True
while if you will run the same thing in the python shell it will be False
yep
makes sense.
so, i was trying to think of ways that i could handle segfaults and whatnot, but that seems to cause a lot of issues
like, have a function which enables segfault handling so you can do something like try: ... except Segfault: ...
but it seems like a segfault handling function causes python to hang when the SIGSEGV signal is sent.
which is understandable.
not sure.
>>> print("hello")
[1] 27254 bus error (core dumped) python3 -i testing.py
well this is new.
oh holy shit this is an interesting error
sys.excepthook is missing
object : NameError("name 'print' is not defined")
type : NameError
refcount: 1
address : 0x7f1087d455c8
lost sys.stderr
Failed calling sys.__interactivehook__
sys.excepthook is missing
object : AttributeError("module has no attribute '_find_and_load'")
type : AttributeError
refcount: 1
address : 0x7f1087d455c8
lost sys.stderr
[1] 31280 segmentation fault (core dumped) python3 -i testing.py
@vague gust was it you who said that python's errors weren't low-level enough? ๐
probably but I don't remember it
i see.
@brisk zenith what did you do
overwrote dict in memory
mem_replace(dict, object)
print()
(where mem_replace is a function of the memory utils i made)
yup
but it does give a lovely error.
i wonder what else could be added to my memory utils.
oh you can use the mem_replace function i made to assign to ...
>>> mem_replace(..., "hello world!")
>>> print(...)
hello world!
>>>
>>> import sys
>>> sys.stdout
<_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf-8'>```
what
big brain code 
@sick hound what are you showing me
big brain code
Juan is a massive golf-head
you have to let it break you, then it will give its knowledge
That's why you take alpacas for playing golf https://s-media-cache-ak0.pinimg.com/originals/28/c3/a7/28c3a7e2f9e98490ca4a90c5186f56d3.jpg (well, technically that one's probably a llama, but who cares)
#JuanCares
"you have to let it break you, then it will give its knowledge" - God 2k18
:D
>>> class Lol:
... def __del__(self):
... while True: pass
...
>>> Lol()
<__main__.Lol object at 0x000001396F38EF60>
>>> 1 + 1
Exception ignored in: <bound method Lol.__del__ of <__main__.Lol object at 0x000001396F38EF60>>
Traceback (most recent call last):
File "<stdin>", line 3, in __del__
KeyboardInterrupt
2
>>>```
doof
Global variables... why should we have them? or does it really matter?
i don't really think they're necessary at all in well-designed code.
i've never encountered a situation in my own projects that needs globals.
i mean of course, i use them when throwing together a script for a little bit of half-arsed automation or something
Global variable can be mutated by other functions making it difficult to track changes to the state.
We are considering using Class instance variables in replace of the single global variable
not sure if thats the best approach or even worth the time.
well, the first thing you'd have to ask yourself is, would that change make it easier to improve and maintain the program later?
so then you should think about how you could restructure your program, perhaps. are global variables really needed, or are you using them as a consequence of lazy planning beforehand?
definitely laziness and ignorance.
should threads be executed with a for loop or outside?
for article in all_articles:
thread = threading.Thread(target=self.make_html, args=(article))
thread.start()
#self.make_html( article )
all_articles is a generator containing a class object representing the article
instead of rendering each article one at a time I wanted to experiment with threading by rendering them concurrently
you'd probably be better off asking in one of the actual help channels c:
none of the code in here should ever touch a production machine
this is an elsoteric library
@sand coral Does play only play the "pure" tone or does it also generate the harmonic overtones? Looks awesome btw
im doing a challenge (just for fun) and i have to make a function that returns a palindrome of length n and using all characters in string c at least once, and no other characters. it also has to be under 55 characters. this is what ive got so far (62 characters):```python
def palindrome(n,c):return c+c[-1:]*(n-len(c+c)+1)+c[::-1][1:]
function name cant change```
i dont want to be told the answer, but some tips on what i can change would be good
c[-1:] is just c[-1]
also using a lambda here would save some characters
def palindrome(n,c):return c+c[-1:]*(n-len(c+c)+1)+c[::-1][1:]
def palindrome(n,c):return c+c[-1]*(n-len(c+c)+1)+c[::-1][1:]
palindrome=lambda n,c:c+c[-1]*(n-len(c+c)+1)+c[::-1][1:]
####################################################### 55 characters```
hmm, i havent looked into lambda, how does that work?
def function(x): return y
function=lambda x: y```
a lambda is an anonymous function
you remove the return but the lambda has to return an expression
and the lambda itself is an expression
the function is actually called <lambda> but it doesn't really matter here
ok :p
you can also make that double slice a bit shorter
is there a way of doing it without that possibly? the challenge starts you with python def palindrome(n, c): return "" so i want to do it like that if possible
you can but it will be longer
also you can make [::-1][1:] a bit shorter
[-2::-1]
palindrome=lambda n,c:c+c[-1]*(n-len(c+c)+1)+c[::-1][1:]
palindrome=lambda n,c:c+c[-1]*(n-len(c+c)+1)+c[-2::-1]
####################################################### 55 characters```
[-2::-1] starts at the second-to-last and goes backwards
which is the same as starting at the last, going backwards, and then taking off the first character of that which was originally the last
def palidrome(n,c):return c + c[1::-1] why doesnt this work?
i feel like im missing something
the palindrome has to be of length n
Ah ok, I tried combining those slices but I couldn't work it out. Thanks :D
oh duh
hmm, thats 59 characters. better, but how can i lose 4 chars ๐ค python def palindrome(n,c):return c+c[-1]*(n-len(c+c)+1)+c[-2::-1]
without using lambda if possible
interesting feedback
PyTheory looks like it will really help me wrap my head around scales, thanks!
@gentle pagoda It doesn't look like you need the +1 there...?
nevermind
that gives you the wrong length
yea
:p
i submitted it using lambda, but id still like to see a solution thats small enough to use def palindrome(n,c):return "" if its possible :p
actually
c+c[-1]*(n-len(c+c))+c[-1::-1]
def palindrome(n,c):return c+c[-1]*(n-len(c+c)+1)+c[-2::-1]
def palindrome(n,c):return c+c[-1]*(n-len(c+c))+c[-1::-1]
#######################################################
actually actually
def palindrome(n,c):return c+c[-1]*(n-len(c+c)+1)+c[-2::-1]
def palindrome(n,c):return c+c[-1]*(n-len(c+c))+c[-1::-1]
def palindrome(n,c):return c+c[-1]*(n-len(c+c))+c[::-1]
#######################################################```
does that count or does it have to be less than 55 characters
@gentle pagoda
less than :c
:c
but thats really impressive, how did you cut it down so much
just playing around in the python repl with things that are similar but shorter until something works
rip, that one doesnt quit work ```python
def palindrome(n,c):return c+c[-1]*(n-len(c+c))+c[::-1]
palindrome(5, "abc")
'abccba'
almost
oh
...i'm confused
well the way i construct the string is n=5 c="abc" ab + (c * n - len("ab" + "ab")) + ba so it eliminates the double c when length is less than 2*c
c+c[-1]*(n-len(c+c)+1)+c[-2::-1]
c+c[-1]*(n-len(c+c))+c[-1]+c[-2::-1]
c+c[-1]*(n-len(c+c))+c[-1::-1]```
c[-1]+c[-2::-1] is the same as c[-1::-1]
>>> def palindrome(n,c):return c+c[-1]*(n-len(c+c))+c[-1::-1]
>>> palindrome(5, "abc")
'abccba'
>>> ```
its really close, but breaks on those edge cases :c
yea :p i think my approach is flawed because i just cant get it any shorter. but im not sure how else i could go about it
'c'*-1==''
@sick hound heres the best solution :p python palindrome=lambda n,s:(s+s[-1-n%2::-1]).center(n,s[0])
im not sure how it works but maybe you can figure it out
i see how that works
-1-n%2 is -1 if n is even and -2 if n is odd
-1 just reverses the string, -2 skips the last character
if n is odd, then abc -> abcba, if n is even then abc -> abccba
ah clever. how does the .center work?
then you call .center on the string with the first character, which centers the string to have a length of n using s[0] to "pad" both ends
because of the -1-n%2 cleverness you will always add the same number of characters to both ends which makes it a palindrome
i wouldn't have got that either
where is that challenge from?
def palindrome(x): return len(x) < 2 or x[0] == x[-1] and palindrome(x[1:-1])
on a never ending quest to make everything recursive
>>> def next_one(x):
... b = itertools.permutations((1,2,3))
... for i in b:
... if i == x:
... try:
... print(b.__next__())
... except:
... print((1,2,3))
...
>>> next_one((3,2,1))
(1, 2, 3)
>>> next_one((1,2,3))
(1, 3, 2)
>>> next_one((1,3,2))
(2, 1, 3)```
how do I install or upgrade the latest python on my linux machine?
that is horrifying @worthy pollen
(I do have to wonder if there's a way to calculate the next permutation without doing it, if you know the relationship of the current permutation to the original order of the list)
If the only criterium is generating the next permuation in terms of lexographical order, then, yes, there's an algorithm for that that. I've linked it when someone asked that question, although the code on that page was in c++. I've looked at it and it should be pretty straightforward to translate the code to python and adjust so it modifies a list in place.
if __name__ == "__main__":
class MyFlags(FlagEnum):
FIRST = 0x01
SECOND = 0x02
THIRD = 0x04
FOURTH = 0x08
flags = MyFlags(0x01 | 0x04)
# is the exact same as doing
flags = MyFlags(
MyFlags.FIRST | MyFlags.THIRD
)
# but is also the same as
flags = MyFlags.FIRST | MyFlags.THIRD
print(flags.FIRST) # True
print(flags.SECOND) # False
print(flags.THIRD) # True
print(flags.FOURTH) # False
this is very hacky behind the scenes, but it's pretty convenient when you need to deal with this sort of thing haha
example usage ```py
class FilePermission(FlagEnum):
EXECUTE = 0x01
WRITE = 0x02
READ = 0x04
let's go for a chmod of 640
others = FilePermission(0x00)
group = others | FilePermission.READ
owner = group | FilePermission.WRITE
print(owner.EXECUTE) # false
print(owner.WRITE) # true
print(owner.READ) # true
what's so esoteric about this?
the way it works is kind of "nani the fuck" i suppose.
well then talk more about the implementation ๐
i shall, i'm just refining it :D
I already knew what it does on the surface
I guess it's unassuming then cause I thought nothing of it
class FilePermission(FlagEnum):
EXECUTE = 0x01
WRITE = 0x02
READ = 0x04
read_write = FilePermission.READ | FilePermission.WRITE
print(read_write) # FilePermission(int_flags=6)
# but wait, FilePermission.READ and .WRITE are integers... so read_write should be too... right?
but they aren't integers
they would be if you did .value
maybe that is what you were getting at, and the existence of the int enum types
the actual class attributes are integers
like 0x01 and 0x02
well, they are when they're defined. but they don't stay that way for long :P
Oh sorry, I guess you're right that it's unintuitive. I just don't see it that way since I already know they're still enum objects
oh, this is a custom class, it's got nothing to do with the enum module.
๐ค
it just happens to work like an Enum
ok that wasnt clear
from another server (re permutation algorithm)
def nextPermutation(a):
# find largest index where a[k] < a[l]
isEnd = True
for k in range(len(a)-2, -1, -1):
if a[k] < a[k+1]:
isEnd = False
break
if isEnd: # if such index does not exist
return None # this is the last permutation
# find largest index > k such that a[k] < a[l]
for l in range(len(a)-1, k, -1):
if a[k] < a[l]:
break
# swap
a[k], a[l] = a[l], a[k]
# reverse sequence from k+1 forward
left = a[:k+1]
rrev = a[:k:-1]
return left + rrev
someone asked me to code this in one line :
import time
duree = int(input("How long in seconds would u want to active the crono"))
temps = 0
while (temps < duree):
temps = temps + 1
print(temps, "secondes")
time.sleep(1)
and so.... (sorry for your bleeding eyes guys)
i = [0 if not print(i if not __import__('time').sleep(1) else '') else 0 for i in range(int(input("How long in seconds would u want to active the crono")))]
[(print(i,"secondes"),__import__('time').sleep(1))for i in range(1,int(input("How long in seconds would u want to active the crono")))]```
this is more accurate
@sick hound what's with your scott nick?
maybe pastebin is his name. are you making assumptions now? 
sorry, i'll stop memeing and go to bed.
@sick hound just a random thing I decided to do
not quite esoteric, but```py
Python 3.6.6 (v3.6.6:4cf1f54eb7, Jun 27 2018, 03:37:03) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
class A:
... def del(self):
... print('del!')
...
a = A()
li = [a]
del a
li.remove(li[0])
exit()
del!
C:\Users\Me>
spooky uncollected reference
๐ป
spooky
huh
There are no uncollected references, __del__ is called when instance is going to be destroyed but not the reference. So when you call del obj it's not executing __del__
__del__ is only going to be executed when garbage collector is about to delete the instance itself.
@wise ingot what is that monospace script font in your screenshot called?
Ouch. Yes it is.
Hella pretty tho
I'm not a huge fan of it
I like fira code
Kenneth Reitz of Requests fame over there uses it for everything, including documentation
Yeah I was looking at that one too. Hm.
What is esoteric python?
If you have a look at the channel description on top: "Golfing, Python VM languages, obfuscation, code gore and other general Python weirdness "
like
>>> a,b = {},{}
>>> a[True], b[1] = 1, 1
>>> a[1] , b[True] = 42, 42
>>> a, b
({True:42}, {1:42})```
id(1) != id(True)
hash(1) == hash(True)
anyone open for a recursion question?
I want to create a pass phrase generator recursively. For instance, the list [apple, orange, pear] should print
apple appleorange applepear orange orangeapple orangepear pear pearapple pearorange
where the length of pass phrase is an input parameter. ie,:
passphraseGenerator(lst, k):
here's where i'm at:
= ['apple', 'orange','pear']
def passPhraseGenerator(lst, k):
newlst = []
if len(lst) == 1:
print(lst[0])
return lst[0]
for i in range(len(lst)):
lst.pop(i)
passPhraseGenerator(lst,k)
lst.insert(i, lst[i])
newlst.append(lst[i])
if len(newlst) <= k:
for i in range (len(newlst)):
print(newlst[i], end="")
passPhraseGenerator(r, 2)
>>> import itertools
>>> l = ["apple", "orange", "pear", ""]
>>> ["".join(words) for words in itertools.permutations(l, 2)]
['appleorange', 'applepear', 'apple', 'orangeapple', 'orangepear', 'orange', 'pearapple', 'pearorange', 'pear', 'apple', 'orange', 'pear']
like this?
wait, now the single words are duplicated...
yeah
is there a recursive way? I'm trying to learn recursion and this seemed like a good problem.
could use a set then to deduplicate
>>> {"".join(words) for words in itertools.permutations(l, 2)}
{'orangepear', 'pear', 'appleorange', 'pearapple', 'orangeapple', 'apple', 'orange', 'applepear', 'pearorange'}
oh, okay
๐
well, to write something recursive, you need to identify the recursive case and the stop case
yeah: I think my recursive case is having the list be length 1, and the recursive case modify list until it is
you could pass the remaining needed number of words as function parameter and decrement it with each recursive call, then that number == 0 would be the stop case
sorry. *base case
whatever the correct terms are ๐
haha. right. :-)
so in your function, you check if that number is 0 and return an empty list (or 1 and you return the plain fruit list)
and if the number is not 0 (or 1), you have to loop over the fruit list, make a recursive call with the decremented number, and append each of the results to each fruit item....
kinda, probably
๐
guys, what is the shortest method to remove whitespaces from a string?
str.replace(" ", "")
Please tell me, how you beat this, if possible
for code golf? other than the obvious space between the arguments and using a single character variable name?
I doubt there's anything shorter than s.replace(" ","")
I need more very short snippets for https://www.codingame.com/multiplayer/clashofcode
for example, just found out that reverse can be written as [::-1]
so that saves some chars
.reversed()
[::-1]
have a look at this https://codegolf.stackexchange.com/q/54/36188
Thanks!
@frosty wyvern you might even pin that link maybe...
''.join(s.split()) is one char longer but gets all whitespace
there's .reversed() ?

I don't think so
there's e.g. list.reverse() and there is the built-in function reversed()
built in function for what? lists?
everything iterable
wait, not everything iterable
it must have either a __reversed__ method or support indexing, i.e. have a __len__ and __getitem__
cool. didint know that
@frosty wyvern so now where the code jam ended, are the challeneges gonna come back?
Soon, yes. I was waiting for the new repositories to be ready though I reckon I could post a new challenge before the fact
I welcome any suggestion for the next challenge
Suggestion: Build a chunks iterator which works on lists, tuples, and generators
make a program that creates another program when it's own code is input
without checking
everything iterable
wait, not everything iterable
it's called sized type
this is the first time I hear "sized type". Got any documentation for that?
ah sorry not sized but sequence
you start to know better python types/abc modules when you are using mypy and type hints
well yes, but you automatically get default reversed if you have len and getitem defined
true, I didn't deny that
pretty much the same behaviour with being able to iterate over object if it got those two defined
there is also reversable abc type of collections, but I never used it so far in the typing ๐
I've done something bad. I'm sorry. python class O: def __call__(self): return O() o = O()()()()()()()()()()()()()()
it recurses the number of times that you keep giving it ()
each object that is returned is also callable to produce another one, so you just keep tacking on () to call the last one
Hrm, and each call creates a new instance?
yes
>>> class O:
... def __init__(self):
... print('init')
... def __call__(self):
... print('call')
... return O()
...
>>> o = O()()()
init
call
init
call
init
Clever~
class O:
def __call__(self):
print(self)
return O()
o = O()()()()()()()()()()()()()()```
<main.O object at 0x000001FCE9600160>
<main.O object at 0x000001FCE96002B0>
<main.O object at 0x000001FCE9600198>
<main.O object at 0x000001FCE9600160>
<main.O object at 0x000001FCE96002B0>
<main.O object at 0x000001FCE9600198>
<main.O object at 0x000001FCE9600160>
<main.O object at 0x000001FCE96002B0>
<main.O object at 0x000001FCE9600198>
<main.O object at 0x000001FCE9600160>
<main.O object at 0x000001FCE96002B0>
<main.O object at 0x000001FCE9600198>
<main.O object at 0x000001FCE9600160>```
I just thought it would be very evil to see ()()()() in code
It's evil enough having to do ()(). Never done three or more.
What if I want to make the gc very, very sad
wow, that first line is really cursed
I'm surprised it works.
because the right hand side of any assignment is supposed to be fully evaluated before the left side, yet that simply doesn't work without the far left-hand assignment
"When foo = foo[0] = [0] is executed, the list [0] is first assigned to foo and then an alias of the same list is assigned to foo[0]"
what
i always assumed it was the other way arond
i guess that's just because how it works in c/c++ is that a=b=c means "b=c returns the new value, and that is assigned to a"
whereas in python ```py
dis.dis('a=b=c=d')
1 0 LOAD_NAME 0 (d)
2 DUP_TOP
4 STORE_NAME 1 (a)
6 DUP_TOP
8 STORE_NAME 2 (b)
10 STORE_NAME 3 (c)
12 LOAD_CONST 0 (None)
14 RETURN_VALUE```
if we ever need to know this in production code that we actually wrote, it is we who are the true criminals
if the new assignment expression pep gets in it'll be possible to change it by adding parentheses
foo[0] = (foo = [0])
maybe := on the right, i forget the pep
wdym :=
wait what do you want (foo = [0]) to do i don't get it
also := is pascal tho right?
wait this is really cool when does 3.8 come out
next year
will it be available in 3.6
I've made a challenge that requires you to enter an input and depending on your UserID, you must enter a certain input to output the flag
unfortunately, part of the challenge is that you don't get to see the whole thing
this is the only part you get to see
def main(u):
#fc = flag constant - get this number!
#dc = just a string. To all members of this company - do not worry about this.
a,l,t,i,p=input("Password: "),len(u),0,int,print
m=len(a)
r=fStr(u,m)
for j,c in enumerate(r):
if c!=" ":t+=i(c)*ord(a[j])
else:t*=2
if t==fc:handleFlag(u)
else:p(f"{dc}{fc%t}\n{t}")
def fStr(a,b):
return (a*(b//len(a)+1))[:b]
if your input when converted is equal to fc, then handleFlag() is called
is this code obfuscated enough or can i do better
a = f"{'%s' % '{}'.format('hey')}"
>>> uns
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>>> uns.sort()
>>> uns
[2, 29, 1, 33, 16, 47, 45, 46, 27, 34, 24, 21, 28, 35, 8, 53, 11, 38, 37, 65, 70, 67, 22, 7, 17, 18, 77, 52, 14, 57, 20, 49, 0, 60, 39, 54, 42, 93, 90, 41, 97, 26, 40, 31, 79, 10, 64, 3, 98, 58, 44, 63, 89, 72, 80, 4, 86, 56, 94, 95, 99, 15, 87, 30, 32, 19, 51, 55, 5, 78, 36, 25, 43, 12, 69, 81, 85, 62, 68, 88, 9, 96, 83, 59, 66, 48, 75, 23, 73, 6, 74, 76, 50, 84, 82, 91, 92, 61, 71, 13]
>>> uns.sort()
>>> uns
[14, 16, 46, 71, 60, 39, 13, 7, 18, 42, 33, 90, 85, 50, 20, 53, 92, 38, 86, 15, 99, 95, 48, 4, 32, 89, 54, 55, 72, 10, 9, 79, 78, 40, 34, 97, 91, 30, 29, 0, 61, 58, 25, 69, 73, 41, 27, 26, 98, 57, 74, 5, 49, 56, 67, 28, 11, 43, 6, 8, 24, 37, 64, 52, 31, 19, 2, 23, 12, 62, 47, 76, 45, 75, 59, 3, 84, 70, 35, 63, 88, 65, 36, 21, 96, 44, 77, 81, 93, 1, 66, 22, 51, 17, 68, 80, 83, 87, 82, 94]
>>> uns.sort()
>>> uns
[31, 14, 37, 65, 10, 57, 41, 79, 26, 86, 25, 94, 56, 85, 90, 1, 62, 74, 30, 45, 99, 2, 44, 96, 83, 32, 6, 89, 91, 80, 16, 69, 42, 63, 22, 60, 95, 19, 34, 67, 18, 7, 20, 97, 58, 36, 46, 72, 70, 71, 47, 66, 29, 51, 93, 98, 11, 64, 28, 38, 39, 15, 75, 52, 77, 23, 43, 88, 3, 5, 24, 12, 4, 0, 73, 59, 35, 76, 13, 49, 55, 87, 17, 8, 68, 82, 84, 92, 78, 33, 50, 21, 48, 81, 27, 61, 53, 54, 9, 40]```
Yeah, I looked at that and just kinda noped
Holy crud wait
Could you simulate rule 110 or some other cellular automaton by doing repeated sort() calls on a list of objects with __lt__() overridden
Well "some other CA" definitely lol but how about an interesting one
...you probably couldn't because I don't think sorting can take both neighbors into account (just 1) and I don't think the order is predictable but hm
May be easier with a simpler sorting algorithm than timsort in any case
ok actually dead-easy -- if you disregard that the point of sorting is to move things around rather than let them stay in place + modify their own state
RULE = 110
class Cell:
lookup = {((i>>2) % 2, (i>>1) % 2, i % 2): (RULE >> i) % 2 for i in range(8)}
def __init__(self, state=False):
self.state = state
self._left = False
def __repr__(self):
return '#' if self.state else '_'
def __lt__(self, other):
self._left = other.state
other.change(self.state)
# Stay where I am in the list
return False
@classmethod
def new_universe(cls, size, pop_func=None):
if pop_func is None:
# By default, fill in the rightmost cell only
pop_func = (size - 1).__eq__
# The list's final element isn't advanced during simulation,
# so add a dead Cell(False) -- this will now be the one that isn't advanced,
# leaving all the requested cells to behave as intended
return [cls(bool(pop_func(pos))) for pos in range(size)] + [cls(False)]
def change(self, right):
self.state = self.lookup[self._left, self.state, right]
>>> li = Cell.new_universe(10)
>>> while not li[0].state:
... print(li)
... li.sort()
...
[_, _, _, _, _, _, _, _, _, #, _]
[_, _, _, _, _, _, _, _, #, #, _]
[_, _, _, _, _, _, _, #, #, #, _]
[_, _, _, _, _, _, #, #, _, #, _]
[_, _, _, _, _, #, #, #, #, #, _]
[_, _, _, _, #, #, _, _, _, #, _]
[_, _, _, #, #, #, _, _, #, #, _]
[_, _, #, #, _, #, _, #, #, #, _]
[_, #, #, #, #, #, #, #, _, #, _]
made a quick snippet for rotating a matrix? 2-d list?
m=[list(r)[::-1]for r in zip(*m)] thats the rightward direction
clockwise
m=[list(r)for r in zip(*m)][::-1] is counter clockwise
its still kinda amazing to me how cool the zip function is
yo that's pretty fucking neat
fwiw that trick's neat but not new, zip is just transposition
when you use it on a 2d list
yeah i used it to get columns
and then reverse
whats fwiw stand for
i forgot to turn my code in for that clash tho so :/
oh i was talking about the rule 110 thing
i didn't even read yours
i'll decide if your thing is neat later
my weird sort is using normal list.sort on objects that return True or False randomly for __lt__
n = int(input("Enter number: "))
print("Prime") if True not in [(n % x) == 0 for x in range(2, int(n ** 0.5) + 1)] else print("Not Prime")
wrote this very short code to check if a number is prime but I see it is inefficient because it doesn't stop after it's found a factor, how could I change this with minimal additional lines
Are you familiar with Euclid's gcd algo?
can't say that i am
nvm then.
def is_prime(n):
return not any(n%x==0 for x in range(2, int(n**0.5)+1))
You can use any to shorten it a bit
def is_prime(n):
return all(n%x for x in range(2, int(n**0.5)+1), 2)
Even better
pssst, @crisp pendant, I think you messed up some brackets ๐
def is_prime(n):
return all(n%x for x in range(2, int(n**0.5)+1, 2))```
wups
๐ฎ
how come sometimes u don't need square brackets tho?
like sum(blah blah blah)
works without
itโs like if you had extra ()
(----- for -----) is a genrator expression
so youโd have sum((blah blah)) but youโre allowed to not put the second ()
oh
-- and a generator expression is like a list comprehension, except it waits to "generate" the next value until needed
rather than making the entire list up front
so you can do, say, (i * 2 for i in itertools.count()) but not [i * 2 for i in itertools.count()]
bc count() returns a generator that counts up forever, starting from 0; the list comprehension will try to make its entire list right then & there, but it'll end up hanging because of the part about count() going forever
on the other hand, the generator comprehension just gives you the next value when you request it (storing nothing ahead of time) so it can be used without issue
(count() is just there as an example of something that goes forever but it could be anything)
yupyup
>>> .... __class__
<class 'ellipsis'>```
(... is an ellipses object, ....__class__ gets the __class__ attribute from it)
the parentheses aren't part of the generator expression itself, they're just needed when it's next to something that might otherwise be part of a different expression
same with tuples, tuples [except the empty tuple] are created with comma alone
though python is very restrictive about where you can put them without parentheses
not esoteric enough
try this
from ctypes import *
print(cast(pointer(ARRAY(2, c_longlong)(8031924123371070792, 6581362)), POINTER(ARRAY(16, c_char)))[0][:11].decode())
you can obfuscate the print by doing
import __hello__```
joseph's one reminds me of that crazy lambda one
not obfuscated enough
I like this one
import os
from ctypes import *
__builtins__.__getattribute__(os.sys.__class__.__module__.__getitem__.__name__.__class__("".join([chr(x) for x in [112, 114, 105, 110, 116]])))(cast(pointer(ARRAY(2, c_longlong)(8031924123371070792, 6581362)), POINTER(ARRAY(16, c_char)))[0][:11].decode())
in fact that might not be obfuscated enough
I think this is the max I can go
import os
from ctypes import *
__builtins__.__getattribute__(os.sys.__class__.__module__.__getitem__.__name__.__class__(cast(pointer(ARRAY(1, c_longlong)(500068610672)), POINTER(ARRAY(8, c_char)))[0][:5].decode()))(cast(pointer(ARRAY(2, c_longlong)(8031924123371070792, 6581362)), POINTER(ARRAY(16, c_char)))[0][:11].decode())
if anyone else wants to try obfuscate it more please amuse me
i think that is a suitable number of numbers
considering that they are being fucked with by ctypes and not just like an ord/chr thing
Maybe you could change all the numbers to hex or binary?
hmm I like the sound of huge binary numbers :^)
import praw;supportedimagetype=('.jpg','.png','.jpeg');posturls=[post.url for post in list(praw.Reddit('username234','pass234','useragent1234kthx').subreddit('shittingbirdswitharms').hot(limit=200)) if post.url.endswith(supportedimagetypes)]
not much
globals().update(__import__('ctypes').__dict__)
__builtins__.__getitem__(__import__('sys').modules['os'].sys.__class__.__module__.__getitem__.__name__.__class__("".join([chr(x) for x in [112, 114, 105, 110, 116]])))(cast(pointer(ARRAY(2, c_longlong)(8031924123371070792, 6581362)), POINTER(ARRAY(16, c_char)))[0][:11].decode())```
is this obfuscated enough? :)
oh you're the guy who taught me that ctypes stuff aren't you
My eyes, it hurts.
import re
import numpy as np
matrix = np.zeros((1000, 1000))
pattern = re.compile(r"(\d{1,3}),(\d{1,3}): (\d{1,3})x(\d{1,3})")
raw = open("input.txt").readlines()
coords = [[int(y) for y in pattern.search(x).groups()] for x in raw]
for coord_set in coords:
y_start = coord_set[1]
x_start = coord_set[0]
width = coord_set[2]
height = coord_set[3]
for i in range(height):
for j in range(width):
matrix[i + y_start, j + x_start] += 1
def part1():
return np.count_nonzero(matrix > 1)
def part2():
for i, coord_set in enumerate(coords):
y_start = coord_set[1]
x_start = coord_set[0]
width = coord_set[2]
height = coord_set[3]
if np.all(
[
square == 1
for square in matrix[
y_start : y_start + height, x_start : x_start + width
]
]
):
return raw[i]
print(part1())
print(part2())
does that count
you need to remove the spaces inbetween everything
import re
import numpy as np
matrix = np.zeros((1000, 1000))
pattern = re.compile(r"(\d{1,3}),(\d{1,3}): (\d{1,3})x(\d{1,3})")
raw = open("input.txt").readlines()
coords = [[int(y) for y in pattern.search(x).groups()] for x in raw]
for coord_set in coords:
y_start = coord_set[1]
x_start = coord_set[0]
width = coord_set[2]
height = coord_set[3]
for i in range(height):
for j in range(width):
matrix[i + y_start, j + x_start] += 1
def part1():
return np.count_nonzero(matrix > 1)
def part2():
for i, coord_set in enumerate(coords):
y_start = coord_set[1]
x_start = coord_set[0]
width = coord_set[2]
height = coord_set[3]
if np.all(
[
square == 1
for square in matrix[
y_start : y_start + height, x_start : x_start + width
]
]
):
return raw[i]
print(part1())
print(part2())```
much better
hi guys, i was doing a python reversing CTF challenge.
this is the original code
`# -- coding: rot13 --
vzcbeg arj
vzcbeg znefuny
vzcbeg onfr64
qrs trg_cnffjbeq():
tybonyf().hcqngr({"enaqbz".qrpbqr("rot13"): [p sbe p va ().pynff.onfr.fhopynffrf()
vs p.anzr == 'pngpu_jneavatf'.qrpbqr('rot13') ]0
.zbqhyr.ohvygvaf'gebczv'.qrpbqr('rot13')[::-1]
.qvpg['zbqane'.qrpbqr('rot13')[::-1]].qvpg'zbqanE'.qrpbqr('rot13')[::-1]})
erghea "Abcr!".qrpbqr("rot13")
olgrpbqr="LjNNNNNNNNNNOjNNNRNNNNOm9tNNNTDNNTDONTjNNSbNNTHONTHPNTHQNTbQNVZNNTDPNOFQNDPQNDOn"
"ONOaNNOyODOxNjOyOtOyONPQNDOxONPQNjORKE0NJtpNMDVNMDDNMDpNMDpNMNDNSlTQNDOrNtOkDDOn"
"PNOxNjOnPDOxODOnPtOxOtOnPjOyPjOxOjN3JtfNMDfNMNtNA1bYNUuTNTHYNTbZNVZNNREqBNOnQDOy"
"PtOyQtOyNtOyQDOxPDOxPtPQNDSyPNOyPDOxPjNJTHTQNDN3JtbNMDxNMNjNA1bWNUTKNSqyNNOdQjOy"
"PtPQNDOnRNOxQDOyRNOdRDPQNNNJJtbNMNRNHltBNNNNns////9BnDQu9DIcNNNNNTxPNNNNqNNNNNOm"
"TNNNNQIyVQD0VQSvVQZ2VQH1VQSxVQH5VQSuVUZLNNNNA2HtZJLtAQVtZJRtAmxtZJLtAQxtZmptpkDN"
"NNNmBFN1BPN3AFNlZlN2AvNkBPN0MUDRNNNNLzSmMJxDNNNNnDDNNNOcNDNNNUZVNNNNExkOE3fyp30b"
"RtNNNUDUNNNNnTSmnTkcLaDQNNNNp3ElqNZNNNOcoaE0OtNNNUWuozEioKDRNNNNp2IyMUDSNNNNpzSh"
"M2I0NjNNNTkyoaDONNNNnKDTNNNNp2IwpzI0qNHNNNOcozEyrUDRNNNNMzkuM3DRNNNNExkOE3DSNNNN"
"p3OfnKE0NDNNNTM0NjNNNTAbpaDRNNNNp2uuZKDONNNNnUDWNNNNnTI4MTyaMKA0XNNNNNNbNNNNNPtN"
"NNNNpj4NNNOmMKEfLJ5aqJSaMF5jrKDVNNNNCT1iMUIfMG4ONNNNpktNNNNZNujOCNRTNDLOOtRXNDbP"
"RjRbND4PQjR="
vs anzr == "znva".qrpbqr("rot13"):
synt = trg_cnffjbeq()
pbqrbow = znefuny.ybnqf(onfr64.o64qrpbqr(olgrpbqr.qrpbqr("rot13")))
trg_cnffjbeq = arj.shapgvba(pbqrbow, tybonyf(), fge("trg_cnffjbeq".qrpbqr("rot13")), Abar, Abar)
trg_cnffjbeq()`
i used rot13 in order to make the code readable
and now it looks like this
#!/usr/bin/env python
# -*- pbqvat: ebg13 -*-
import new
import marshal
import base64
def get_password():
globals().update({"random".decode("ebg13"): [c for c in ().__class__.__base__.__subclasses__()
if c.__name__ == 'catch_warnings'.decode('ebg13') ][0]()
._module.__builtins__['__tropmi__'.decode('ebg13')[::-1]]("modnar".decode('ebg13')[::-1])
.__dict__['modnar_'.decode('ebg13')[::-1]].__dict__['modnaR'.decode('ebg13')[::-1]](326)})
return "Nope!".decode("ebg13")
bytecode="YwAAAAAAAAAABwAAAEAAAABz9gAAAGQAAGQBAGwAAFoAAGUBAGUCAGUDAGoDAIMAAGQCABSDAQCDAQBa" \
"BABnAABlBQBkAwBlBgBlBACDAQBkBACDAwBEXR0AWgcAZQIAZQQAZQcAZQcAZAQAFyGDAQBeAgBxQQBa" \
"CABkAwBaCQBkBQBaCgBkBgBaCwBlCwBkBwA3WgsAZQsAZAgAN1oLAHhGAGULAGoMAIMAAERdOABaDQBl" \
"CgBlDgBlAgBlDQBkCQBkCgCDAQFlCABlCQBkCwAWGUGDAQA3WgoAZQkAZAwAN1oJAHGXAFdlAABqDwBl" \
"CgCDAQBaEABkDQBlEABqEQCDAAAWWgoAZAEAUygOAAAAaf////9OaQDh9QVpAAAAAGkCAAAAdAAAAABz" \
"GAAAADVlIDQ0IDFiIDM2IDU1IDFkIDU5IDFhIHMYAAAAN2UgMWYgNDIgMWEgNzkgMWYgNDkgMzcgcxQA" \
"AAAzOSA1OCA3NSAyMyA2NiAxOCA0ZHQEAAAAYmFzZWkQAAAAaQQAAABpAQAAAHMIAAAARkxBR3slc30o" \
"EgAAAHQHAAAAaGFzaGxpYnQDAAAAc3RydAMAAABpbnR0BgAAAHJhbmRvbXQEAAAAc2VlZHQFAAAAcmFu" \
"Z2V0AwAAAGxlbnQBAAAAaXQGAAAAc2VjcmV0dAUAAABpbmRleHQEAAAAZmxhZ3QEAAAARkxBR3QFAAAA" \
"c3BsaXR0AQAAAGZ0AwAAAGNocnQEAAAAc2hhMXQBAAAAaHQJAAAAaGV4ZGlnZXN0KAAAAAAoAAAAACgA" \
"AAAAcw4AAABzZXRsYW5ndWFnZS5weXQIAAAAPG1vZHVsZT4BAAAAcxgAAAAMAhwBPAEGAQYBBgEKAQoC" \
"EwEoAQ4CDwE="
if __name__ == "__main__".decode("ebg13"):
flag = get_password()
codeobj = marshal.loads(base64.b64decode(bytecode.decode("ebg13")))
get_password = new.function(codeobj, globals(), str("get_password".decode("ebg13")), None, None)
get_password()
so more or less the code decodes the string in base64
so the decoded code is
c@sddlZeeejdZgedeedD]Zeeeed!^qAZdZ dZ
dZed7Zed7ZxFejD]8Z
e
eee
d d
ee dA7Z
e d7Z qWeje
Zd
ejZ
dS(iNiiits5e 44 1b 36 55 1d 59 1a s7e 1f 42 1a 79 1f 49 37 s39 58 75 23 66 18 4dtbaseiiisFLAG{%s}(thashlibtstrtinttrandomtseedtrangetlentitsecrettindextflagtFLAGtsplittftchrtsha1tht hexdigest(((ssetlanguage.pyt<module>s<
(
and i think its pyc so i tried to decompile it but i get a magic number error
so i used https://nedbatchelder.com/blog/200804/the_structure_of_pyc_files.html
and this https://stackoverflow.com/questions/514371/whats-the-bad-magic-number-error to edit the hex value of the first 4 bytes but then i get invalid pyc error
any idea on how to resolve this challenge ?
How were you trying to "decompile" the pyc?
What you can do is disassemble it after the base64 decoded string is loaded
import dis
codeobj = marshal.loads(base64.b64decode(bytecode))
dis.dis(codeobj)
I don't think that it's a pyc file anyway. It's just a code object that was serialised by marshal and is now getting deserialised
i used easy python decompiler and uncompyle2 but both of them aren't working
i'll try this and let you know
whats the new module out of curiosity
some python 2 thing
#!/usr/bin/env python
import dis
import new
import marshal
import base64
bytecode="YwAAAAAAAAAABwAAAEAAAABz9gAAAGQAAGQBAGwAAFoAAGUBAGUCAGUDAGoDAIMAAGQCABSDAQCDAQBa" \
"BABnAABlBQBkAwBlBgBlBACDAQBkBACDAwBEXR0AWgcAZQIAZQQAZQcAZQcAZAQAFyGDAQBeAgBxQQBa" \
"CABkAwBaCQBkBQBaCgBkBgBaCwBlCwBkBwA3WgsAZQsAZAgAN1oLAHhGAGULAGoMAIMAAERdOABaDQBl" \
"CgBlDgBlAgBlDQBkCQBkCgCDAQFlCABlCQBkCwAWGUGDAQA3WgoAZQkAZAwAN1oJAHGXAFdlAABqDwBl" \
"CgCDAQBaEABkDQBlEABqEQCDAAAWWgoAZAEAUygOAAAAaf////9OaQDh9QVpAAAAAGkCAAAAdAAAAABz" \
"GAAAADVlIDQ0IDFiIDM2IDU1IDFkIDU5IDFhIHMYAAAAN2UgMWYgNDIgMWEgNzkgMWYgNDkgMzcgcxQA" \
"AAAzOSA1OCA3NSAyMyA2NiAxOCA0ZHQEAAAAYmFzZWkQAAAAaQQAAABpAQAAAHMIAAAARkxBR3slc30o" \
"EgAAAHQHAAAAaGFzaGxpYnQDAAAAc3RydAMAAABpbnR0BgAAAHJhbmRvbXQEAAAAc2VlZHQFAAAAcmFu" \
"Z2V0AwAAAGxlbnQBAAAAaXQGAAAAc2VjcmV0dAUAAABpbmRleHQEAAAAZmxhZ3QEAAAARkxBR3QFAAAA" \
"c3BsaXR0AQAAAGZ0AwAAAGNocnQEAAAAc2hhMXQBAAAAaHQJAAAAaGV4ZGlnZXN0KAAAAAAoAAAAACgA" \
"AAAAcw4AAABzZXRsYW5ndWFnZS5weXQIAAAAPG1vZHVsZT4BAAAAcxgAAAAMAhwBPAEGAQYBBgEKAQoC" \
"EwEoAQ4CDwE="
codeobj = marshal.loads(base64.b64decode(bytecode))
dis.dis(codeobj)
i just ran this
3 LOAD_CONST 1 (None)
6 IMPORT_NAME 0 (hashlib)
9 STORE_NAME 0 (hashlib)
3 12 LOAD_NAME 1 (str)
15 LOAD_NAME 2 (int)
18 LOAD_NAME 3 (random)
21 LOAD_ATTR 3 (random)
24 CALL_FUNCTION 0
27 LOAD_CONST 2 (100000000)
30 BINARY_MULTIPLY
31 CALL_FUNCTION 1
34 CALL_FUNCTION 1
37 STORE_NAME 4 (seed)
4 40 BUILD_LIST 0
43 LOAD_NAME 5 (range)
46 LOAD_CONST 3 (0)
49 LOAD_NAME 6 (len)
52 LOAD_NAME 4 (seed)
55 CALL_FUNCTION 1
58 LOAD_CONST 4 (2)
61 CALL_FUNCTION 3
64 GET_ITER
>> 65 FOR_ITER 29 (to 97)
68 STORE_NAME 7 (i)
71 LOAD_NAME 2 (int)
74 LOAD_NAME 4 (seed)
77 LOAD_NAME 7 (i)
80 LOAD_NAME 7 (i)
83 LOAD_CONST 4 (2)
86 BINARY_ADD
87 SLICE+3
88 CALL_FUNCTION 1
91 LIST_APPEND 2
94 JUMP_ABSOLUTE 65
>> 97 STORE_NAME 8 (secret)
5 100 LOAD_CONST 3 (0)
103 STORE_NAME 9 (index)
109 STORE_NAME 10 (flag)
7 112 LOAD_CONST 6 ('5e 44 1b 36 55 1d 59 1a ')
115 STORE_NAME 11 (FLAG)
8 118 LOAD_NAME 11 (FLAG)
121 LOAD_CONST 7 ('7e 1f 42 1a 79 1f 49 37 ')
124 INPLACE_ADD
125 STORE_NAME 11 (FLAG)
9 128 LOAD_NAME 11 (FLAG)
131 LOAD_CONST 8 ('39 58 75 23 66 18 4d')
134 INPLACE_ADD
135 STORE_NAME 11 (FLAG)
11 138 SETUP_LOOP 70 (to 211)
141 LOAD_NAME 11 (FLAG)
144 LOAD_ATTR 12 (split)
147 CALL_FUNCTION 0
150 GET_ITER
>> 151 FOR_ITER 56 (to 210)
154 STORE_NAME 13 (f)
160 LOAD_NAME 14 (chr)
163 LOAD_NAME 2 (int)
166 LOAD_NAME 13 (f)
169 LOAD_CONST 9 ('base')
172 LOAD_CONST 10 (16)
175 CALL_FUNCTION 257
178 LOAD_NAME 8 (secret)
181 LOAD_NAME 9 (index)
184 LOAD_CONST 11 (4)
187 BINARY_MODULO
188 BINARY_SUBSCR
189 BINARY_XOR
190 CALL_FUNCTION 1
193 INPLACE_ADD
194 STORE_NAME 10 (flag)
13 197 LOAD_NAME 9 (index)
200 LOAD_CONST 12 (1)
203 INPLACE_ADD
204 STORE_NAME 9 (index)
207 JUMP_ABSOLUTE 151
>> 210 POP_BLOCK
15 >> 211 LOAD_NAME 0 (hashlib)
214 LOAD_ATTR 15 (sha1)
217 LOAD_NAME 10 (flag)
220 CALL_FUNCTION 1
223 STORE_NAME 16 (h)
16 226 LOAD_CONST 13 ('FLAG{%s}')
229 LOAD_NAME 16 (h)
232 LOAD_ATTR 17 (hexdigest)
235 CALL_FUNCTION 0
238 BINARY_MODULO
239 STORE_NAME 10 (flag)
242 LOAD_CONST 1 (None)
245 RETURN_VALUE
this is the output
Right. I looked into how to use uncompyle6 but after skimming through it, it didn't seem to support decompiling code objects; it only works with pyc files is my impression
So I would just manually reverse engineer this bytecode
As I said, there's not a lot there
maybe make a BytesIO out of the code object to make it work with uncompyle?
anyone else annoyed by this behavior? ```py
๐ t = ([1,2,3],)
๐ t[0] += [1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
๐ t[0]
[1, 2, 3, 1]
the reason is, when you do t[0] += [1] it does t[0] = t[0].__iadd__([1]) which is dumb
it could just do t[0].__iadd__([1]) and leave out the assignment
because, why should in place add be an expression?
meanwhile list.__iadd__ just does the mutation and returns self because of this dumb behavior
(if you dont like it file an issue or PR it into cpython)
no, i'm p sure this is a python language thing
cause there's an FAQ entry about it
It's also because of consistency, I believe
Otherwise, this would not work:
i = 1
i += 1
but there's no int.__iadd__() so that has to be handled differently regardless
Well, but it still calls INPLACE_ADD
๐ค I don't get it. If you don't want assignment then why are you using an inplace add?
Just do normal addition
Oh, I see. It's a list within a tuple
I'm doing some golfing, and I'm trying to replace a list L with a range(0,len(L)) equivalent in as few characters as possible. Anyone know something shorter than that?
[*range(len(L))]
you can just do L[:] = range(len(L))
True, but that's the same number of characters. I'll stick with what I have for now.
why the L[:]?
Makes it a list rather than a range generator object
As it happens, I managed to restructure the program to accept the range itself rather than the list.
Are mutable strings possible in python?
Strings themselves are immutable, but you can make mutable equivalents, for example out of a list of characters.
If you make your own class or alter the string class, you could even make it support the same operations as a string.
I wonder, are mutable integers possible...
*L,=range(len(L))
Yes, one character down.
1512 to go.
:/
(My code is very much a work in progress.)
(It still includes comments, meaningful identifiers and whitespace. It also doesn't work.)
new method for obfuscation of integers:
int('เญงเงฌ๐เผฃ')
will evaluate to 1613
these are just numbers that mean 1,6,1,3 correspondingly I assume?
yes
although idk in whihc language
wikipedia lists it under or but i dont know whihc country or is so ยฏ_(ใ)_/ยฏ
python
only
to see all the things going on
must be made in python
all about control
of your whitespace
are you okay over there
You should probably close Discord until you sober up
def f(n):
return n and('fizz'if n%3==0else'')+('buzz'if n%5==0else'')or n
'fizz'*(n%3<1)
```is generally how golfers do it iirc (assumes `n` will always be an integer, however)
f=lambda n:(n%3<1)*"fizz"+(n%5<1)*"buzz"or n```
Man, the file I was working in looks like a graveyard python #f=lambda n:n and"fbiuzzzz"[::] #f=lambda n:n and"".join(i for i in["fizz","buzz"]) #f=lambda n:n and''.join(f"fbiuzzzz{n}"[x-1::2]for x in(bool(n%2),bool(n%5*2))) #f=lambda n:exec("*y,=()")and x #f=lambda n:n and"fizzbuzz"[[slice(i)for i in((0,))]] f=lambda n:(n%3<1)*"fizz"+(n%5<1)*"buzz"or n for i in range(100): print(f"{i}: {f(i)}")
Niice
i believe there's a much shorter one that i saw but idk if it works with py 2 and 3
dang should f(0) return fizzbuzz or 0
0
print(*((lambda n:(n%3<1)*"fizz"+(n%5<1)*"buzz"or n)(i) for i in range(100)), sep='\n')
oh f returns fizzbuzz dang it
print(*((lambda n:n and(n%3<1)*"fizz"+(n%5<1)*"buzz"or n)(i) for i in range(100)), sep='\n')
would fix it
5 chars though
ye
for n in range(100):print(n and(n%3<1)*"fizz"+(n%5<1)*"buzz"or n)```
in case of py3 you need to a bit change the print execution
why not just ```py
print(n and(n%3<1)"fizz"+(n%5<1)"buzz"or n for n in range(100))
because it's longer?
its not
it is
u shouldn't use exec though
that's cheating
using : is cheating too
trust me, i often reduce 50 line long functions into 1 only
man, whole code golfing is about cheating
lel
the rules of true code wrapping are :
1 : no semicolon
2 : no colon
3 : no exec or eval
4 : no sys call
5 : no import
and all is done in 1 line using ternary, call on void, formatting code, code objects, etc
remember u can always use void functions in ur ternaries
that's ugly though :')
There are no rules to golfing usually
You make your code as short as you can, however you can
yeah, you came up with rules from a specific contests or specific platform, but in fact there are no rules
you can do whatever you want
xD
it's my rules
i don't consider golfing as it if these rules aren't used
like transforming this : ```py
import time
duree = int(input("How long in seconds would u want to active the crono"))
temps = 0
while (temps < duree):
temps = temps + 1
print(temps, "seconds")
time.sleep(1)
```py
i = [0 if not print(i if not __import__('time').sleep(1) else '') else 0 for i in range(int(input("How long in seconds would u want to active the crono")))]
golfing means as short as possible. your rules suck
reminds me of that really bad golfing challenge that had some really strange rules
๐ who's down for 9 holes today
lel
why my rules suck :')
that's true golfing channel
u can make everything really easily into one line without those rules
it's a challenge with them
that's all
i don't care ๐คท๐ฟ
much more challenging, so much more interesting
not using your fingers also makes it more challenging
To be honest, I also have an arbitrary rule for golfing python that increases my character count. I don't use Python 2.
@slim pecan
from functools import reduce
def chunks(r, word):
if len(f'{r[-1]} {word}') <= 40:
r[-1] += f' {word}'
return r
return r+[word]
my_str = "I still don't get it, could you show the example of input-output?"
words = my_str.split()
print(reduce(chunks, words[1:], [words[0]]))
Not bad
!eval ```py
from functools import reduce
def chunks(r, word):
if len(f'{r[-1]} {word}') <= 40:
r[-1] += f' {word}'
return r
return r+[word]
my_str = "I still don't get it, could you show the example of input-output?"
words = my_str.split()
print(reduce(chunks, words[1:], [words[0]]))
@slim pecan Your eval job has completed.
["I still don't get it, could you show the", 'example of input-output?']
๐
i imagine this point of this is to not use textwrap? it's a pretty interesting solution.
Pretty cool, i didn't understand the need
@brisk zenith not efficient tbh, but tiny.
quite cool example. That is why I love this channel.
@austere aurora do you want to abuse python in your code even more?
yes pls sensei
pls dont tell me that eval(dir[0]) thing I hate that
I try to solve it in as few lines as possible
the actual logic that is
thats what I get off on
so its a mixture of golfing tricks and mnemonic variable names lol
ok so here is your code just so we have it here
from math import gcd
from functools import reduce
def fromNb2Str(n, m):
if not all(True if gcd(m[i],m[j])==1 else False for i in range(len(m)-1) for j in range(i+1,len(m))) or reduce(lambda x,y: x*y, m)<=n:
return 'Not applicable'
return '-'+'--'.join(str(n % x) for x in m)+'-'
lets first clean it a bit
from math import gcd
from functools import reduce
def fromNb2Str(n, m):
if not all(gcd(m[i],m[j])==1 for i in range(len(m)-1) for j in range(i+1,len(m))) or reduce(lambda x,y: x*y, m)<=n:
return 'Not applicable'
return '-'+'--'.join(str(n % x) for x in m)+'-'
what is happening here all(gcd(m[i],m[j])==1 for i in range(len(m)-1) for j in range(i+1,len(m))) is that your are doing all the possible combinations of 2 ints from your list and checking that gdc==1 right?
there is combinations function in python
yes ๐
ok use that here and show me
from math import gcd
from itertools import combinations
from functools import reduce
def fromNb2Str(n, m):
if not all(gcd(i,j)==1 for i,j in combinations(m, 2)) or reduce(lambda x,y: x*y, m)<=n:
return 'Not applicable'
return '-'+'--'.join(str(n % x) for x in m)+'-'
nice!!
oh kk makes more sense ๐
map where?
if not all(map(lambda (x,y): gcd(x,y), combinations(m, 2))
they removed argument unpacking in lambda in py3
damn
so its if not all(map(lambda pair: gcd(pair[0],pair[1]), combinations(m, 2)) instead
in python2 you could unpack elements in lambdas, so you could do lambda (x,y): x+y
you still can tho
and that would mean that lambda expects a tuple of 2 elements and unpack it into arguments x,y
I do lambda x,y: x+y all the time
yeah just do *pair
yup
n = int(input().strip())
a = list(map(int, input().rstrip().split()))
print(max(map(len,max([([a[i]]+[a[j] for j in range(len(a)) if i != j and 0 <= a[i]-a[j] <= 1],[a[i]]+[a[j] for j in range(len(a)) if i != j and 0 <= a[j]-a[i] <= 1]) for i in range(len(a))], key = lambda x: max([len(x[0]),len(x[1])])))))
I forgot what it does
but this is in my golf of shame
its 3 lines lol
its a hackerrank problem iirc
oh shit
GL figuring that out lol
i don't really get it, it build 2 exactly the same lists and doing max there for some reason
I might be missing something
no, one is if 0 <= a[i] - a[j] <=1 and the other is 0 <= a[j] - a[i] <= 1
is there any way to access __import__ via a chain of getattrs on builtin objects? without accessing __builtins__ or __import__ directly)
wait, nvm. i was trying to break codingbat (first by using a generator to return a hardcoded value each time my function was called, but next is forbidden so i started exploring other stuff) but it turns out they don't allow getattr() OR dunders so nope
&```py
STUFF=(i for i in (6, 2, 6, 4, 3, 0, 0, 0, 0, 0, 14, 5, 0, 0))
def sum13(nums):
for i in STUFF:
return i
no underscore-initial attribute names, no exec or eval, and I didn't check if compile was allowed but I don't think you can do anything with it besides exec right
they've got it locked down pretty well :(
if you're allowed types.FunctionType and compile you can make a function and then call it immediately
types.FunctionType(compile('42', '', 'eval'), globals())() # 42```
or instead of types.FunctionType you can use type(lambda:0)
WOW they don't even allow type() (or compile(), rip, & still no imports)
definitely clever though gg
10 votes and 9 comments so far on Reddit
Oh we have a special project just for that
It's called snekbox
We don't really disallow anything, we just place limits on the container like how much resources it can use or how much time it can run for
!eval ```py
import platform
print(platform.node())
@vague gust Your eval job has completed.
NSJAIL
it's pretty cool
I was meaning the comment that talks about how to import stuff without using import blah
You could instead use a bunch of getattr()
Rather than underscore properties.
tuple_cls = getattr((),"__class__")
object_cls = getattr(tuple_cls, "__base__")
all_clses = getattr(object_cls, "__subclasses__")()
print(all_clses)
'''for cls in all_clses:
if getattr(cls, "__name__") == "something":'''``` I'm not going to do the rest because I'm on mobile.
@sick hound why are you trying to break codingbat
for fun ๐คท
i don't have hw on it, just found it and went "hey this is neat" -> "wonder if i can cheat on these"
but they've got it locked down really well. like I kept saying before, they block
- import,
__import__() - getattr()
- access of underscore-initial attributes (including dunders)
- eval, exec, compile
- type()
- iter()
- yield statements
- .next()
But how do you mean cheat
for instance: writing a generator that maintains its state outside of the function they want (from which you return generator.next()), yielding the correct answers in order
So you're still giving the necessary output
right, just w/o doing any of the work
What
for example this "passed" and it was what I was going for```py
ANSWERS = (i for i in (6, 2, 6, 4, 3, 0, 0, 0, 0, 0, 14, 5, 0, 0))
def sum13(nums):
for i in ANSWERS:
return i
except they still have some hidden "extra tests/checks", which afaict just make sure you actually do the requested computation, and it fails those
sum13() is the function they want
every time it's called, it returns the next element of the generator
which holds the answers (they show you the answers to your failed tests), but it doesn't do the work required to get those answers from nums
Man I'm not gonna lie
I am way to gone for this
Let's say they want you to square numbers, and they test it with numbers 1..10, instead of actually squaring the input numbers he/she is making a list of the first ten squares and outputting them in order.
It's cheating by some metrics, clever loophole abuse by others.
I understand now
This channel is like reading chinese
i love this channel, perhaps a bit too much. :D
I would superimpose "It's only Python, how unreadable could it be?" over the evil Kermit doppelganger, but I'm on mobile.
Hey guys, i'd like to understand a bit more yield from so i've happened with that :
def recurseReduce(array):
for i in array: yield from recurseReduce(i) if type(i) in [tuple, list, dict] else [i]
print(*recurseReduce([2,[3,[2]]]))
as u may know, this returns me 2 3 2, but could u explain me why ?
i think yield from is doing a yield from all indexes of an iterable
but i could be wrong
also, is it possible to reduce [tuple, list, dict] into something like iterable ?
@sick hound check if i has the __iter__ method.
or if you wanted to do it in non-esoteric code, use ```py
from collections.abc import Iterable
...
if isinstance(my_var, Iterable):
...```
or more esoteric
from types import FunctionType,MethodType
def iterable(v):
return hasattr(type(v),'__iter__') or (isinstance(v,(FunctionType,MethodType)) and v.__code__.co_flags&32)
if iterable(my_var):
#...
lol
if u want i can explain, it is actually pretty simple 
noted a mistake, thanks for mentioning the topic 
i see that it checks
- if the object itself is iterable
- if it's a generator function
yes
although that may not work because you can't iterate over the function itself, you'd need to call it first.
u are right
>>> def a():
yield 5
yield 6
>>> iterable(a)
32
>>> [v for v in a]
Traceback (most recent call last):
File "<pyshell#43>", line 1, in <module>
[v for v in a]
TypeError: 'function' object is not iterable
>>> [v for v in a()]
[5, 6]
>>> [v for v in iter(a)]
Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
[v for v in iter(a)]
TypeError: 'function' object is not iterable
though to be fair, if i wanted to flatten a container then i wouldn't want it to call all functions/generator functions in it
thank
plz tell me what's the level of esoterism of this :
@bot.command()
async def memberinfo(ctx):
"""`g/memberinfo` : Shows infos about members status in this guild."""
counts = [0, 0, 0, 0]
for member in ctx.guild.members:
counts[{discord.Status.online: 0, discord.Status.idle: 1, discord.Status.dnd: 2, discord.Status.offline: 3}[
member.status]] += 1
embed = discord.Embed(colour=discord.Colour(0xFFFF),
description=f":green_circle: {counts[0]}\n:yellow_circle: {counts[1]}\n:red_circle: {counts[2]}\n:black_circle: {counts[3]}")
embed.set_author(name="Current users", icon_url=ctx.guild.icon_url)
embed.set_thumbnail(url=ctx.guild.icon_url)
await ctx.send(embed=embed)
or if it is ok
what the...
xD
IT'S SHOWTIME
TALK TO THE HAND "Hello, World!"
YOU HAVE BEEN TERMINATED
It's not Python but I find esoteric programming languages like Arnoldc very amusing
+[+.] here's an infinite loop.
That prints out ASCII characters in order.
(In brainf*** rather than Python)
def outer():
a = 1
class Inner:
def __init__(self, store):
nonlocal a
a = store
def get(self):
return a
return Inner```
This stores instance variables without using `self`. I'm a bad person.
first = outer()(5)
second = outer()(10)
print(first, first.get())
print(second, second.get())
<__main__.outer.<locals>.Inner object at 0x0000022E32F7D240> 5
<__main__.outer.<locals>.Inner object at 0x0000022E3326F0F0> 10```
a for each instance is stored in a closure, rather than in the instance
first.__init__.__func__.__closure__[0].cell_contents``` It's in there if you look.

The bit about reference counting for garbage collection is implementation-specific, right? An implementation of Python might use a different garbage collection scheme.
yep
yeah, the book does point that out very specifically, just not on this page
it's Fluent Python by the way
>>> class MetaMetaclass(type):
... pass
...
>>> class Metaclass(type, metaclass=MetaMetaclass):
... pass
...
>>> Metaclass.__class__ = Metaclass
>>> Metaclass in Metaclass.__mro__
True
>>>
:^)
then again, that's not too special because type is an instance of itself
type and object are both instances of themselves. what do we call this sorcery? 
Are they instances of each other?
they are, actually.
i think type is the cooler example of the two though
because it's an instance of itself directly, whereas object is an instance of one of it's own subclasses.
!eval ```py
print(isinstance(type, type))
print(type.class is type)
print(isinstance(object, object))
print(object.class is object)
@brisk zenith Your eval job has completed.
001 | True
002 | True
003 | True
004 | False
It's really good, highly recommended
You guys might enjoy this
if __name__ != '__main__':
from sys import modules
import inspect
self = modules[__name__]
mod = type(self)
body = {}
prop = {}
for att in dir(self):
val = getattr(self, att)
if inspect.isfunction(val):
prop[att] = RequireConnection('conn') # Descriptor
body[att] = val
mod = type(mod.__name__, (mod,), prop)
self = modules[__name__] = mod(__name__)
for k, v in body.items():
setattr(self, k, v)
self.__dict__['set_project'] = set_project # Does not require connection
Creates a module object with property behaviors
Basically an interface module that uses a connection variable. This codes requires the user to set the project for connection before they can call any of the interface functions.
The descriptor looks something like
class RequireConnection:
def __init__(self, connection_name):
self.connection_name = connection_name
def __set_name__(self, owner, name):
self.name = name
def __get__(self, instance, owner):
if self.connection_name not in instance.__dict__:
raise ConnectionError("No project selected")
else:
return instance.__dict__[self.name]
def __set__(self, instance, value):
instance.__dict__[self.name] = value
how would i go about one lining this? ```python
def isprime(integer):
for i in range(2, integer):
if integer % i == 0:
return False
return True
wonder why builtins are not colored
ยฏ_(ใ)_/ยฏ
/doubletableflip
Fwiw you could probably speed that loop up by starting from 3 and using a step size of 2. And also checking first if the number is even
(Ignoring the special case needed for 2)
Wait nvm. I donโt think that works thinking about it more
You can decrease its O() by only checking up to โx or x/2
running a loop from 0 to x/2 instead of x still makes the algorithm O(x), because 1/2 is a constant factor, which doesn't change the big-O class
i just made a function for async exec that dynamically creates a function containing the code to be executed and awaiting the created function
it gets the correct scoping for the dynamic function by getting the locals in the parent frame and inserting source before the input code declaring each variable to be put in local scope because otherwise the variables are shown by locals() and dir() but cause a name error if you try to use them
thats esoteric, right?
its using sys._getframe
certainly sounds like it. mind giving an example of it in action?
await execasy('async for x in asynciterator:\n print(x)')
x=42
await execasy('print(x)\nawait client.send_message("hello world", channel_id)')
``` -> outputs 42 and sends a discord message
any code that exec could run can also be used in my execasy
someone challenged me to write a quine
(lambda a:print(a.__repr__().join(__import__("pickle").loads(a))))(b'\x80\x03XC\x00\x00\x00(lambda a:print(a.__repr__().join(__import__("pickle").loads(a))))(q\x00X\x01\x00\x00\x00)q\x01\x86q\x02.')
behold
the one liner
you can do it shorter with eval or json but i think this adds flare
short version
(lambda a:print(a.__repr__().join(eval(a))))("('(lambda a:print(a.__repr__().join(eval(a))))(', ')')")```
you could probably go even shorter if you replaced the repr with actual escaped quotation marks
but that's extremely boring
are you "allowed" to use imports when making a quine?
imports are file reads in the same way the interpreter is a file read
nonetheless, shorterer version
(lambda a:print(a+repr(a)+")"))('(lambda a:print(a+repr(a)+")"))(')```
well, some people don't see it that way
but from a conceptual perspective, a standard module is just as non-cheaty as the interpreter's builtins
and as you can see, you can arrive at shorter solutions when not importing because import is long
import is reading a file, it might be for that reason
_='_=%r;print _(%%)_';print _(%)_
huh
%r takes the repr of a thing
whoda thunk
old stackexchange answer though
for python 3 support the next best thing is
_='_=%r;print(_%%_)';print(_%_)
this is old formating syntax
i mean it still works though
yeah, it is not deprecated
I use this sometimes by mistake out of old habbits
!r would be the repr object
actually that version i wrote runs in python 3 and saves two space characters
well, not wrote, quickly edited
why does the python 2 version have those parentheses anyways
yeah... was wondering what that does
uhhh
>>> _='_=%r;print _(%%)_';print _(%)_
File "<stdin>", line 1
_='_=%r;print _(%%)_';print _(%)_
^
SyntaxError: invalid syntax```
Python 2.7.15 (default, Jun 27 2018, 13:05:28)
what is this for
that is for py3
>>> _='_=%r;print _(%%)_';print _(%)_
File "<stdin>", line 1
_='_=%r;print _(%%)_';print _(%)_
^
SyntaxError: invalid syntax
nope, print needs outer parenthesis in py3
true, my bad
_%_ is printing the variable _ with _as an input to the string formating
yeah, but the code you posted doesn't run unmodified in any python interpreter afaik
but i checked stackoverflow and the version there didn't have the weird parentheses
yes it should..
what does _(%)_ do
ermm.. then i missspelled it ๐
and this runs
oh yeah.. your right
fizzbuzz in 68 characters
for i in range(1,101):print(("Fizz"*(i%3==0))+("Buzz"*(i%5==0))or i)```
this is 65 char but starts from 0
*nvm, 67 if (1,101)

oops, had extra parenthesis
64 char
for i in range(1,101):print("Fizz"*(i%3==0)+"Buzz"*(i%5==0)or i)```
Just replace i%3==0 with i%3<1
Should be effectively the same thing in this case
Same with i%5
62 char
for i in range(1,101):print("Fizz"*(i%3<1)+"Buzz"*(i%5<1)or i)``` 
This works but it's the same 62 char i=1;exec('print("Fizz"*(i%3<1)+"Buzz"*(i%5<1)or i);i+=1;'*100)
.
^broken in py3 ```for i in range(1,101):print(i%3/2*'Fizz'+i%5/4*'Buzz'or-~i)
TypeError: can't multiply sequence by non-int of type 'float'```
oh, right, double slash
@green nymph py3 61 char ```python
for i in range(0,100):print(i%3//2*'Fizz'+i%5//4*'Buzz'or-~i)
i=0;exec("print(i%3//2*'Fizz'+i%5//4*'Buzz'or-~i);i+=1;"*100)``` Because of parenthesis the exec form is same as for loop.
yeah
code golfing is a bit better in py2
you could also use shit like `var` (back quotes) to call repr of a variable
usually it's short on py2, because it's ineffictient and things like map/reduce returning lists
print is not a function
etc
there is even function input and raw_input and if you do input in py2 it would also do a typecast
i did quite a lot of golfing, most of the times py2 would beat py3, but still personally I think py3 is a huge step for python.
oh dur when range is (0,100) can just (100)
which brings it to 59 char under py3, actually shorter than exec...
fizzbuzz should calculate it from 1 to 100
exec is doing byte shifting magics that is why it starts from 0 ๐
in fact it will print it starting from 1
Hm
Since challenges are on hiatus, I'll write some;
1 == 2
It's not difficult to understand, make 1 == 2 evaluate to True. Try to Golfยน your code, and the one with the shortest answer after a week gets a point.
ยนCode golfing is the act of making your code as short as possible
==================================
After X weeks the one with the most points gets a steam key from me cause I have so many spare ones.
like
from ctypes import *
cast(id(2),POINTER(c_int))[6]=1
But can you do it shorter? I know how
only on py2
surprisingly it does not work
In [4]: False = True
In [5]: 2 == 1
Out[5]: False
In [6]: False
Out[6]: True
In [7]: True
Out[7]: True
not that easy yeah, you're just rebinding False, but the underlying bool is still there
hmm, now I'm a bit having struggle with that challenge. redefining __cmp__ of int instance would have be the way, but python says fuckoff when you try to do it for integer.
:)
alright alright, while I struggle with this one here is one for your head of course in case if you don't know this problem yet.
Find out if there is a loop in singly linked list, while using constant memory (a.k O(1) memory).
and since that is a python channel you could also program that in python then:P
example input-output?
{1:2, 2:6, 6:"blah", (1,2,3,4):1, "blah":(1, 2, 3, 4,)} => Truthy value e.g. 1
{6:8} => falsey EDIT: probably best to always start with 1, or pass in a certain parameter to represent the first element.
Also cheating: python 1+\
By which I mean python 1+\ 1 == 2 and not print("True") or print("False") in case you couldn't figure out how to print the result
If that doesn't float your boat, python from ctypes import* cast(id(2),POINTER(c_int))[3]=1 is slightly shorter than above. Btw, it's 3 rather than 6, at least on my implementation, but maybe yours is different.
To check the number on your implementation, try printing python3 cast(id(142),POINTER(c_int))[0:20] and find the index of 142.
Here's my attempt at the other one: python def check(linked_list: dict, list_start=1): #returns bool, true if the linked list loops, else false max_length = len(linked_list) #total number of links in list current_value = linked_list[list_start] #initialised to first link in linked list for _ in range(max_length): #(range() uses constant memory in py3) try: current_value = linked_list[current_value] except KeyError: #ran out of keys #hence links cannot form infinite loop return False else: #therefore more links traversed than exist #key has been repeated, ergo loop return True
(Constant memory rather than low complexity)
i have async exec and is_nsfw in discord.py async
when they say "no, thats not possible, youll have to do somthing else" i make it happen by sheer force of will
they said you couldnt get if a channel is nsfw in discord.py async, that you have to use rewrite
you dont
they said you cant use exec with async code; you have to just run the code without exec
you dont
i can have a discord bot exec code including awaits
to check if the channel is nsfw
in async, not rewrite
oh cool
def check(data: dict):
start = random.choice(data.keys())
def inner(key):
val = data.get(key)
if val == start:
return True
if val is None:
return False
return inner(val)
return inner(data[key])
```O(n) performance when True iirc
(all(v in data for v in data.values()))
as long as it's a dict :p
actually hmmmm dict is a really bad way to represent a linked list
bc the point of a linked-list node is to have both its own "data" and keep track of the "next node"
this dict representation only shows "next node"
Is it based on memory or performance?
Also, do you have to detect if the whole list is a loop, or just part of it loops?
advanced currying
>>> def test(first,second,third):
... fourth = first+second
... return fourth*third+second
...
>>> test2 = curry(test,"second",15)
>>> dis.dis(test)
2 0 LOAD_FAST 0 (first)
2 LOAD_FAST 1 (second)
4 BINARY_ADD
6 STORE_FAST 3 (fourth)
3 8 LOAD_FAST 3 (fourth)
10 LOAD_FAST 2 (third)
12 BINARY_MULTIPLY
14 LOAD_FAST 1 (second)
16 BINARY_ADD
18 RETURN_VALUE
>>> dis.dis(test2)
-665 0 LOAD_FAST 0 (first)
2 LOAD_CONST 1 (15)
4 BINARY_ADD
6 STORE_FAST 2 (fourth)
-664 8 LOAD_FAST 2 (fourth)
10 LOAD_FAST 1 (third)
12 BINARY_MULTIPLY
14 LOAD_CONST 1 (15)
16 BINARY_ADD
18 RETURN_VALUE
>>> test(1,15,3)
63
>>> test2(1,3)
63
function curry adds overhead
but if you just edit the function's bytecode you get the legendary zero overhead
it's pretty much safe for most functions
but if a function has, say, 124 or more arguments
it's very dangerous
@snow beacon if you meant "is the idea that 'a dict is a bad way to represent a linked list' based on memory or performance?" then neither
I meant the competition
I don't think Python has a builtin linked list, so I improvised.
I'm sure the principle would apply to a proper linked list too
Whoops, one day too late with challenge 2.
Anyways, congrats to @snow beacon for having the shortest answer.
Next up, we'll have something simple:
While not really esoteric, there's bonus points for this one.
The task is as follows:
Assuming function x has parameters completely annotated, figure out the return type (including Typing.*).
Bonus points for:
- Shortest code
- Supporting generics
- Not using the
astmodule
Each of these is worth one point, so have fun trying to implement this, each point adds up!
A good way to do this is to check the return value of each function used, you may assume each of these functions are annotated
Meanwhile, I'm working on some more esoteric focused challenges.
lambda f:object``` is not quite what you're looking for, I don't think
nope, I mean e.g. ```py
def test_func(x: int, y: Union[float, int]) -> ...:
return x * y
def test_func_2(x: str, y: int) -> ...:
return str(len(x * y)) * y
your_function(test_func) # => Union[float, int]
your_function(test_func_2) # => str
also @snow beacon your code would fail on something that returns a subclass of type :^)
I'm going to assume that side effects are allowed.
e.g. when checking python def test_func(x: object): print("Hello, world!") return True outputting a whole bunch of "Hello, world!\n"s to the console
def get_return_type(fun):
annotations = fun.__annotations__
param_types = [annotations[param] for param in annotations if param != "return"]
print(param_types)
params = [param_type() for param_type in param_types]
return_type = type(fun(*params))
return return_type```
works for some types and functions
x=lambda f:type(f(*[a()for a in f.__annotations__.values()]))``` is the same, except it doesn't work for functions with return annotations
It's also very short
And I made another one that works if the function has an accurate return annotation:python x=lambda f:f.__annotations__["return"]
The challenge is to estimate the return annotation based on either returning explicit values or the type of the variables used. You may assume all functions called WITHIN the function are perfectly annotated
So for each operation inside the function, we will know what type it results in?
Would that apply to e.g. python def fun(a: float, b: int): return a + b
goal afaict is just to figure out how to call the function
and then check the type() of its return value
That's what my first bit of code does
It tries to call the class of all the parameters with no arguments, and puts them into the function.
It should probably ignore **kwargs classes because they already have defaults, but I didn't implement it, nor did I golf it
right, looks good
the aliases in the typing module (specifically the ones that correspond to python types 1:1) have attributes __origin__ and __args__
typing.List.__origin__ is list and typing.List[int].__args__ == (int,)
would need to recurse to handle, like, List[List[int]]
But there are still types like slice that need a parameter to instantiate
And builtin types aren't annotated
It would be possible to create an example object for every builtin type, but tedious.
And even if the type works, the example object still might cause errors in the function.
It's impossible to design around every possible type and function
of course, goal's just try for as many as possible
wdym
okay so basically
you have this situation:
def x(args_with_annotations_go_here) -> ...:
# code goes here
Your goal is to look at the function, do whatever with it (calling it is possible but you need to return all possible types) and return the return type.
Examples:
def thing(a: int, b: KT, c: List[Dict[KT, VT]]) -> ...:
return c[a][b]
def other_thing(a: List[Union[str, int]]) -> ...:
return list(reversed(a))
def third_thing(x: str) -> ...:
with open(x) as f:
return json.load(f)
your_func(thing) # => VT
your_func(other_thing) # => Union[str, int]
your_func(third_thing) # => Union[str, int, None, List[Union[str, int, None, ...]], Dict[str, Union[str, int, None, List[Union[str, int, None, ...]], ...]
where ... may be used to specify recursive types
of course, all functions that are called have a return annotation so for third_thing all you need to do is return the json.load return annotation
this is actually very hard
not even the compiler knows this one
instead of solving the problme
i'd like to show one of the worst case scenarios
lambda: type(str(__import__("random").random()),(int,),{})(1)
>>> f = lambda: type(str(__import__("random").random()),(int,),{})(1)
>>> f()
1
>>> type(f())
<class '__main__.0.22194218050586645'>
>>> type(f())
<class '__main__.0.37382486759827716'>
>>> type(f())
<class '__main__.0.295342834932274'>
randomly generated types
a phrase i never should have been able to say
the correct answer to this one is listing every possible float that random.random can generate
i assume that class instantiation is a gimme because the class instantiation will always return the type of the class
But some instantiation requires parameters

