#esoteric-python

1 messages ยท Page 62 of 1

night quarryBOT
#

@frosty wyvern Your eval job has completed.

20
frosty wyvern
#

wat

#

wait what does __sizeof__ even do

#

!e import sys;print(sys.getsizeof(0))

night quarryBOT
#

@frosty wyvern Your eval job has completed.

24
pure dew
#

i would think it gets the in memory size

#

!e print(object.sizeof({}))

night quarryBOT
#
I'm sorry Dave, I'm afraid I can't do that.

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

pure dew
#

wat

sick hound
#
>>> sys.getsizeof(x)
66
>>> object.__sizeof__(x)
32
>>> x.__sizeof__()
42``` wat
sick hound
#

(x is a special object that overrides __sizeof__, but sys.getsizeof and object.__sizeof__ are entirely untouched)

brisk zenith
#

hmm.. how is sys.getsizeof different to object.__sizeof__()?

green nymph
#

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.

brisk zenith
#

oh hmm i see

green nymph
#

apparently garbage collector need more space than object itself, lol

brisk zenith
#

fair enough

brisk zenith
#

that doesn't make sense though

#
sys.getsizeof("hi") < object.__sizeof__("hi")```
#

from what i can see, sys.getsizeof(obj) just calls obj.__sizeof__()

green nymph
#

yes

#

it makes sense because you are calling object.__sizeof__

#

while you should call here str.__sizeof__

#
>>> sys.getsizeof("hi") < str.__sizeof__("hi")
False
brisk zenith
#

yup

sick hound
#
>>> sys.getsizeof(x)
1000000023```
brisk zenith
#

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)
green nymph
#

could you share a code snippet to see how this is implemented?

brisk zenith
#

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

green nymph
#

ok through the ctypes I see

brisk zenith
#

yeah

green nymph
#

I just was wondering how did you access the memory, since I haven't seen any python functions to manipulate memory tables.

brisk zenith
#

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.

green nymph
#

Yeah I've used it a lot when working with .dlls through the python

brisk zenith
#

i've never worked with .dlls

green nymph
#

that is pretty straight forward with the ctypes, you just load that dll file and then manipulate with it using ctypes data structures

pure dew
#

@brisk zenith you can literally override literal values???

brisk zenith
#

yeah

pure dew
#

lmfao

#

that gives me an idea

green nymph
#

@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

pure dew
#

yea

#

i guess it wont work with numbers > 1000

brisk zenith
#

hm?

pure dew
#

cus cpython caching

brisk zenith
#
mem_switch(1001, 1002)
print(1002)  # prints 1001
pure dew
#

oh

brisk zenith
#

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

green nymph
#

btw does not work for me ๐Ÿ˜„

#
In [5]: mem_switch(10004, 10005)

In [6]: print(10005)
10005
brisk zenith
#

it doesn't work properly in a REPL

green nymph
#

which python?

brisk zenith
#

well, i've tested it on 3.7

green nymph
#

hm, does not work for me on 3.6

brisk zenith
#

well it works in 2.7.15 for me

#

ยฏ_(ใƒ„)_/ยฏ

#

just not in a REPL

#
mem_switch("hello", "hi")
print "hello"  # prints "hi"```
green nymph
#

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

brisk zenith
#

yeah, probably.

green nymph
#

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

brisk zenith
#

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.

pure dew
#

i mean

#

how would it recover from a segfault

brisk zenith
#

not sure.

brisk zenith
#
>>> 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? ๐Ÿ‘€

vague gust
#

probably but I don't remember it

brisk zenith
#

i see.

pure dew
#

@brisk zenith what did you do

brisk zenith
#

overwrote dict in memory

#
mem_replace(dict, object)
print()

(where mem_replace is a function of the memory utils i made)

pure dew
#

uh, yea

#

i imagine that breaks globals

brisk zenith
#

yup

#

but it does give a lovely error.

#

i wonder what else could be added to my memory utils.

brisk zenith
#

oh you can use the mem_replace function i made to assign to ...

#
>>> mem_replace(..., "hello world!")
>>> print(...)
hello world!
>>> 
pure dew
#

idea

#

make Ellipsis work like ... in lua

sick hound
#
>>> import sys
>>> sys.stdout
<_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf-8'>```
pure dew
#

what

grizzled epoch
#

big brain code brainmon

pure dew
#

@sick hound what are you showing me

grizzled epoch
#

big brain code

sand coral
#

I wrote a magic library using python

#

that's esoteric ๐Ÿ˜ƒ

brisk zenith
#

oh oh do tell us more

#

haha

fast torrent
#

Juan is a massive golf-head

sharp canyon
#

I wish I knew how to think like you guys

#

This stuff just breaks me

pure dew
#

you have to let it break you, then it will give its knowledge

tropic gulch
cunning wave
#

#JuanCares

fast torrent
#

"you have to let it break you, then it will give its knowledge" - God 2k18

brisk zenith
#

:D

sick hound
#
>>> 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
>>>```
pure dew
#

doof

mellow comet
#

Global variables... why should we have them? or does it really matter?

brisk zenith
#

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

mellow comet
#

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.

brisk zenith
#

well, the first thing you'd have to ask yourself is, would that change make it easier to improve and maintain the program later?

mellow comet
#

answer...not really

#

no

brisk zenith
#

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?

mellow comet
#

definitely laziness and ignorance.

mellow comet
#

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

brisk zenith
#

you'd probably be better off asking in one of the actual help channels c:

pure dew
#

none of the code in here should ever touch a production machine

sand coral
#

this is an elsoteric library

pure dew
#

@sand coral Does play only play the "pure" tone or does it also generate the harmonic overtones? Looks awesome btw

gentle pagoda
#

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

sick hound
#

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```
gentle pagoda
#

hmm, i havent looked into lambda, how does that work?

sick hound
#
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

gentle pagoda
#

ok :p

sick hound
#

you can also make that double slice a bit shorter

gentle pagoda
#

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

sick hound
#

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

rapid bridge
#

def palidrome(n,c):return c + c[1::-1] why doesnt this work?

#

i feel like im missing something

sick hound
#

the palindrome has to be of length n

gentle pagoda
#

Ah ok, I tried combining those slices but I couldn't work it out. Thanks :D

rapid bridge
#

oh duh

gentle pagoda
#

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

novel vine
#

global variables are only useful for constants

#

oops scrolling

sand coral
#

interesting feedback

soft idol
#

PyTheory looks like it will really help me wrap my head around scales, thanks!

sick hound
#

@gentle pagoda It doesn't look like you need the +1 there...?

#

nevermind

#

that gives you the wrong length

gentle pagoda
#

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

sick hound
#

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

gentle pagoda
#

less than :c

sick hound
#

:c

gentle pagoda
#

but thats really impressive, how did you cut it down so much

sick hound
#

just playing around in the python repl with things that are similar but shorter until something works

gentle pagoda
#

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

sick hound
#

oh

gentle pagoda
#

thats why i had the -1 in mine

#

to avoid that

#

*+1

sick hound
#

...i'm confused

gentle pagoda
#

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

sick hound
#
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]

gentle pagoda
#
>>> 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

sick hound
#

...OH

#

i understand now

#

:c

gentle pagoda
#

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

sick hound
#

'c'*-1==''

gentle pagoda
#

@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

sick hound
#

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

gentle pagoda
#

ah clever. how does the .center work?

sick hound
#

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

gentle pagoda
#

i wouldnt have got that myself ยฏ_(ใƒ„)_/ยฏ

#

my naive approach worked at least :p

sick hound
#

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?

gentle pagoda
wicked surge
#
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

worthy pollen
#
>>> 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)```
mellow comet
#

how do I install or upgrade the latest python on my linux machine?

tropic gulch
calm rampart
#

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)

nocturne saddle
#

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.

brisk zenith
#
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

brisk zenith
#

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

whole kiln
#

what's so esoteric about this?

brisk zenith
#

the way it works is kind of "nani the fuck" i suppose.

whole kiln
#

well then talk more about the implementation ๐Ÿ˜„

brisk zenith
#

i shall, i'm just refining it :D

whole kiln
#

I already knew what it does on the surface

#

I guess it's unassuming then cause I thought nothing of it

brisk zenith
#
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?
whole kiln
#

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

brisk zenith
#

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

whole kiln
#

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

brisk zenith
#

oh, this is a custom class, it's got nothing to do with the enum module.

whole kiln
#

๐Ÿค”

brisk zenith
#

it just happens to work like an Enum

whole kiln
#

ok that wasnt clear

brisk zenith
#

yeah haha my bad

sick hound
#

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
unique sinew
#

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")))]
sick hound
#
[(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

brisk zenith
#

@sick hound what's with your scott nick?

#

maybe pastebin is his name. are you making assumptions now? yert

#

sorry, i'll stop memeing and go to bed.

sick hound
#

@sick hound just a random thing I decided to do

sick hound
#

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

green nymph
#

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.

dull furnace
#

@wise ingot what is that monospace script font in your screenshot called?

slim pecan
#

That's Operator

#

It's quite expensive

dull furnace
#

Ouch. Yes it is.

dull furnace
#

Hella pretty tho

slim pecan
#

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

dull furnace
#

Yeah I was looking at that one too. Hm.

sick hound
#

What is esoteric python?

tropic gulch
#

If you have a look at the channel description on top: "Golfing, Python VM languages, obfuscation, code gore and other general Python weirdness "

unique sinew
#

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)
wheat iris
#

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)
tropic gulch
#
>>> 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...

wheat iris
#

yeah

#

is there a recursive way? I'm trying to learn recursion and this seemed like a good problem.

tropic gulch
#

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

wheat iris
#

๐Ÿ˜ƒ

tropic gulch
#

well, to write something recursive, you need to identify the recursive case and the stop case

wheat iris
#

yeah: I think my recursive case is having the list be length 1, and the recursive case modify list until it is

tropic gulch
#

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

wheat iris
#

sorry. *base case

tropic gulch
#

whatever the correct terms are ๐Ÿ˜…

wheat iris
#

haha. right. :-)

tropic gulch
#

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

wheat iris
#

okay. I'll give it a go

#

thanks @tropic gulch !

tropic gulch
#

๐Ÿ‘

hasty leaf
#

guys, what is the shortest method to remove whitespaces from a string?

#
str.replace(" ", "")
#

Please tell me, how you beat this, if possible

tropic gulch
#

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(" ","")

hasty leaf
#

for example, just found out that reverse can be written as [::-1]

#

so that saves some chars

.reversed()
[::-1]
tropic gulch
hasty leaf
#

Thanks!

tropic gulch
#

@frosty wyvern you might even pin that link maybe...

frosty wyvern
sick hound
#

''.join(s.split()) is one char longer but gets all whitespace

topaz fractal
#

really? i learned [::-1] before .reversed()

#

u got me addicted to this game ๐Ÿ˜ฆ

narrow lynx
#

there's .reversed() ? grizzWtf grizzThink grizzShrug

tropic gulch
#

I don't think so

#

there's e.g. list.reverse() and there is the built-in function reversed()

narrow lynx
#

built in function for what? lists?

tropic gulch
#

everything iterable

#

wait, not everything iterable

#

it must have either a __reversed__ method or support indexing, i.e. have a __len__ and __getitem__

narrow lynx
#

cool. didint know that

cunning wave
#

@frosty wyvern so now where the code jam ended, are the challeneges gonna come back?

frosty wyvern
#

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

sick hound
#

Suggestion: Build a chunks iterator which works on lists, tuples, and generators

forest crescent
#

make a program that creates another program when it's own code is input

#

without checking

green nymph
#

everything iterable
wait, not everything iterable
it's called sized type

tropic gulch
#

this is the first time I hear "sized type". Got any documentation for that?

green nymph
#

ah sorry not sized but sequence

#

you start to know better python types/abc modules when you are using mypy and type hints

tropic gulch
#

Right, sequence sounds correct

#

but __reversed__ is not required for a sequence.

green nymph
#

well yes, but you automatically get default reversed if you have len and getitem defined

tropic gulch
#

true, I didn't deny that

green nymph
#

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 ๐Ÿ˜ƒ

grave rover
#

always use abcs !!!

#

actually dont it gets tedious

stone apex
#

I've done something bad. I'm sorry. python class O: def __call__(self): return O() o = O()()()()()()()()()()()()()()

topaz fractal
#

what?

#

how does that work

#

is that infinite recursion?

stone apex
#

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

trim grove
#

Hrm, and each call creates a new instance?

stone apex
#

yes

trim grove
#
>>> class O:
...     def __init__(self):
...         print('init')
...     def __call__(self):
...         print('call')
...         return O()
... 
>>> o = O()()()
init
call
init
call
init
#

Clever~

stone apex
#
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

trim grove
#

It's evil enough having to do ()(). Never done three or more.

green nymph
#

could just return self

#

to make your gc happy

stone apex
#

What if I want to make the gc very, very sad

green nymph
#

btw you can do another magiclike

#
a = a[0] = [0]
a[0][0][0][0][0][0][0][0][0]
stone apex
#

wow, that first line is really cursed

trim grove
#

I'm surprised it works.

stone apex
#

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]"

calm rampart
#

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```

stone apex
#

if we ever need to know this in production code that we actually wrote, it is we who are the true criminals

calm rampart
#

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

fallen heath
#

while a := func():
stuff

#

I do like the idea of it

topaz fractal
#

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

shy vector
#

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

wild cairn
#

a = f"{'%s' % '{}'.format('hey')}"

tropic gulch
#

that won't work

#

you can't nest the same type of quotes

sick hound
#
>>> 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]```
silk ruin
#

w...

#

This is not how sorting works

tame valley
#

Yeah, I looked at that and just kinda noped

slim pecan
#

Almost looks like bogosort

#

Just like, single steps lol

sick hound
#

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

sick hound
#

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()
... 
[_, _, _, _, _, _, _, _, _, #, _]
[_, _, _, _, _, _, _, _, #, #, _]
[_, _, _, _, _, _, _, #, #, #, _]
[_, _, _, _, _, _, #, #, _, #, _]
[_, _, _, _, _, #, #, #, #, #, _]
[_, _, _, _, #, #, _, _, _, #, _]
[_, _, _, #, #, #, _, _, #, #, _]
[_, _, #, #, _, #, _, #, #, #, _]
[_, #, #, #, #, #, #, #, _, #, _]
topaz fractal
#

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

pine edge
#

yo that's pretty fucking neat

topaz fractal
#

zip is super useful

#

๐Ÿ˜ƒ

sick hound
#

fwiw that trick's neat but not new, zip is just transposition

#

when you use it on a 2d list

topaz fractal
#

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 :/

pine edge
#

oh i was talking about the rule 110 thing

#

i didn't even read yours

#

i'll decide if your thing is neat later

sick hound
#

my weird sort is using normal list.sort on objects that return True or False randomly for __lt__

lusty briar
#
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

crisp pendant
#

Are you familiar with Euclid's gcd algo?

lusty briar
#

can't say that i am

crisp pendant
#

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

topaz anchor
#

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))```
crisp pendant
#

wups

topaz fractal
#

๐Ÿ˜ฎ

#

how come sometimes u don't need square brackets tho?

#

like sum(blah blah blah)

#

works without

vestal solstice
#

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 ()

topaz fractal
#

oh

sick hound
#

-- 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)

topaz fractal
#

thats cool

#

so they made it so that you don't need to put the second ()?

sick hound
#

yupyup

sick hound
#
>>> .... __class__
<class 'ellipsis'>```
sick hound
#

(... is an ellipses object, ....__class__ gets the __class__ attribute from it)

calm rampart
#

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

steel ice
#

print("Hello world.")

#

How all great programmers start.

vague gust
#

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())
fallen heath
#

you can obfuscate the print by doing

import __hello__```
mortal ingot
#

joseph's one reminds me of that crazy lambda one

vague gust
#

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

mortal ingot
#

needs less numbers

#

:^)

vague gust
#

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

jade dust
#

Maybe you could change all the numbers to hex or binary?

vague gust
#

hmm I like the sound of huge binary numbers :^)

sick hound
#
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

vague gust
#

that's off topic

#

if you want to shitpost memes this isn't the right server

sick hound
#
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? :)

vague gust
#

oh you're the guy who taught me that ctypes stuff aren't you

cold karma
#

My eyes, it hurts.

queen herald
#
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

sick hound
#

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

sick hound
#

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

#

any idea on how to resolve this challenge ?

whole kiln
#

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

sick hound
#

i used easy python decompiler and uncompyle2 but both of them aren't working

#

i'll try this and let you know

whole kiln
#

I don't think it'd be too hard to read the bytecode anyway

#

It's a short program

mortal ingot
#

whats the new module out of curiosity

whole kiln
#

some python 2 thing

sick hound
#

#!/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

whole kiln
#

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

sick hound
#

maybe make a BytesIO out of the code object to make it work with uncompyle?

glacial rampart
#

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

cunning wave
#

(if you dont like it file an issue or PR it into cpython)

glacial rampart
#

no, i'm p sure this is a python language thing

#

cause there's an FAQ entry about it

nocturne saddle
#

It's also because of consistency, I believe

#

Otherwise, this would not work:

i = 1
i += 1
sick hound
#

but there's no int.__iadd__() so that has to be handled differently regardless

nocturne saddle
#

Well, but it still calls INPLACE_ADD

whole kiln
#

๐Ÿค” 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

snow beacon
#

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))]

green nymph
#

you can just do L[:] = range(len(L))

snow beacon
#

True, but that's the same number of characters. I'll stick with what I have for now.

trim linden
#

why the L[:]?

snow beacon
#

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.

cinder quiver
#

Are mutable strings possible in python?

snow beacon
#

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...

sick hound
#

*L,=range(len(L))

snow beacon
#

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.)

cunning wave
#

new method for obfuscation of integers:
int('เญงเงฌ๐Ÿ™เผฃ')
will evaluate to 1613

vestal solstice
#

these are just numbers that mean 1,6,1,3 correspondingly I assume?

cunning wave
#

yes

#

although idk in whihc language

#

wikipedia lists it under or but i dont know whihc country or is so ยฏ_(ใƒ„)_/ยฏ

sick hound
#

python

#

only

#

to see all the things going on

#

must be made in python

#

all about control

#

of your whitespace

slim pecan
#

are you okay over there

sick hound
#

no

#

experiencing

#

hallucinatory effects

slim pecan
#

You should probably close Discord until you sober up

sick hound
#

very sober

#

very

crisp pendant
#
def f(n):
  return n and('fizz'if n%3==0else'')+('buzz'if n%5==0else'')or n
keen bridge
#
"fizz"*(not n%3)
#

Shorter than comparing to 0.

mortal ingot
#
'fizz'*(n%3<1)
```is generally how golfers do it iirc (assumes `n` will always be an integer, however)
snow beacon
#
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)}")

crisp pendant
#

Niice

mortal ingot
#

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

crisp pendant
#

0

#
print(*((lambda n:(n%3<1)*"fizz"+(n%5<1)*"buzz"or n)(i) for i in range(100)), sep='\n')
mortal ingot
#

oh f returns fizzbuzz dang it

crisp pendant
#
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

mortal ingot
#

ye

snow beacon
#
for n in range(100):print(n and(n%3<1)*"fizz"+(n%5<1)*"buzz"or n)```
green nymph
#

that is current shortest

#
i=0;exec"print i%3/2*'Fizz'+i%5/4*'Buzz'or-~i;i+=1;"*100
unique sinew
#

arg

#

no we can do shorter

green nymph
#

in case of py3 you need to a bit change the print execution

unique sinew
#

why not just ```py
print(n and(n%3<1)"fizz"+(n%5<1)"buzz"or n for n in range(100))

green nymph
#

because it's longer?

unique sinew
#

its not

green nymph
#

it is

unique sinew
#

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

green nymph
#

man, whole code golfing is about cheating

unique sinew
#

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 :')

slim pecan
#

There are no rules to golfing usually

#

You make your code as short as you can, however you can

green nymph
#

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

unique sinew
#

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")))]
dense spire
#

golfing means as short as possible. your rules suck

mortal ingot
#

reminds me of that really bad golfing challenge that had some really strange rules

formal timber
#

๐ŸŒ who's down for 9 holes today

unique sinew
#

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

slim pecan
#

it's not about making it one line

#

it's about making it short

#

lol

unique sinew
#

i don't care xD

#

that's my view of it

slim pecan
#

well your view is wrong

#

:P

unique sinew
#

i don't care ๐Ÿคท๐Ÿฟ

slim pecan
#

I noticed

#

lol

unique sinew
#

much more challenging, so much more interesting

lone ruin
#

not using your fingers also makes it more challenging

unique sinew
#

that's fun

#

using nose

#

or toes

snow beacon
#

To be honest, I also have an arbitrary rule for golfing python that increases my character count. I don't use Python 2.

green nymph
#

@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]]))
slim pecan
#

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]]))

night quarryBOT
#

@slim pecan Your eval job has completed.

["I still don't get it, could you show the", 'example of input-output?']
slim pecan
#

๐Ÿ‘

brisk zenith
#

i imagine this point of this is to not use textwrap? it's a pretty interesting solution.

unique sinew
#

Pretty cool, i didn't understand the need

green nymph
#

@brisk zenith not efficient tbh, but tiny.

cunning minnow
#

quite cool example. That is why I love this channel.

green nymph
#

@austere aurora do you want to abuse python in your code even more?

austere aurora
#

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

green nymph
#

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)+'-'
austere aurora
#

oh you guys collect golfed code?

#

wait till I show you my coup de grace

green nymph
#

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?

austere aurora
#

ok thats better actually

#

yep

green nymph
#

there is combinations function in python

austere aurora
#

lemme guess .combinations

#

lol

green nymph
#

yes ๐Ÿ˜„

austere aurora
#

ok use that here and show me

green nymph
#
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)+'-'
austere aurora
#

nice!!

green nymph
#

ah shit

#

sorry

#

that is wrong

#

fixed

austere aurora
#

oh kk makes more sense ๐Ÿ˜„

green nymph
#

you could also apply map if you like it

#

not sure if it will make your code shorter

austere aurora
#

map where?

green nymph
#

if not all(map(lambda (x,y): gcd(x,y), combinations(m, 2))

austere aurora
#

should be gcd(x,y)==1

#

but its about the same really

green nymph
#

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

austere aurora
#

what were you going for?

#

you cant use gcd(*pair)?

green nymph
#

in python2 you could unpack elements in lambdas, so you could do lambda (x,y): x+y

austere aurora
#

you still can tho

green nymph
#

and that would mean that lambda expects a tuple of 2 elements and unpack it into arguments x,y

austere aurora
#

I do lambda x,y: x+y all the time

green nymph
#

that is different

#

that means that it expects 2 parameters

austere aurora
#

ohhh I get it

#

yeah understood

#

lol

green nymph
#

yeah just do *pair

austere aurora
#

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

green nymph
#

oh shit

austere aurora
#

GL figuring that out lol

green nymph
#

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

austere aurora
#

no, one is if 0 <= a[i] - a[j] <=1 and the other is 0 <= a[j] - a[i] <= 1

sick hound
#

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

snow beacon
#

exec, eval or compile?

#

.__dict__?

sick hound
#

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 :(

sick hound
#

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)

sick hound
#

WOW they don't even allow type() (or compile(), rip, & still no imports)

#

definitely clever though gg

snow beacon
vague gust
#

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())

night quarryBOT
#

@vague gust Your eval job has completed.

NSJAIL
vague gust
#

it's pretty cool

snow beacon
#

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
#

@sick hound why are you trying to break codingbat

sick hound
#

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

snow beacon
#

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.

sick hound
#

I understand now

junior bluff
#

This channel is like reading chinese

brisk zenith
#

i love this channel, perhaps a bit too much. :D

snow beacon
#

I would superimpose "It's only Python, how unreadable could it be?" over the evil Kermit doppelganger, but I'm on mobile.

sick hound
#

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 ?

brisk zenith
#

@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):
...```

coral fiber
#

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):
    #...
sick hound
#

lol

coral fiber
#

if u want i can explain, it is actually pretty simple GWchiakiSataniaLaugh

#

noted a mistake, thanks for mentioning the topic GWsiraMeguThumbsUp

brisk zenith
#

i see that it checks

  1. if the object itself is iterable
  2. if it's a generator function
coral fiber
#

yes

brisk zenith
#

although that may not work because you can't iterate over the function itself, you'd need to call it first.

coral fiber
#

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
brisk zenith
#

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

coral fiber
#

thats right too

#

Juanita so smart GWspcKya

brisk zenith
#

yert thank

sick hound
#

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

silk ruin
#

what the...

slim pecan
#

It's not esoteric

#

But it's a mess

sick hound
#

xD

sick hound
#

no that's not an xD

#

that's a "fix it"

silk ruin
#
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

snow beacon
#

+[+.] here's an infinite loop.

#

That prints out ASCII characters in order.

#

(In brainf*** rather than Python)

stone apex
#
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

snow beacon
#
first.__init__.__func__.__closure__[0].cell_contents``` It's in there if you look.
stone apex
#

Just thought the footnote was funny and relevant to this channel

tropic gulch
snow beacon
#

The bit about reference counting for garbage collection is implementation-specific, right? An implementation of Python might use a different garbage collection scheme.

thorny granite
#

yep

stone apex
#

yeah, the book does point that out very specifically, just not on this page

#

it's Fluent Python by the way

brisk zenith
#
>>> class MetaMetaclass(type):
...     pass
... 
>>> class Metaclass(type, metaclass=MetaMetaclass):
...     pass
... 
>>> Metaclass.__class__ = Metaclass
>>> Metaclass in Metaclass.__mro__
True
>>> 

:^)

brisk zenith
#

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? yert

snow beacon
#

Are they instances of each other?

brisk zenith
#

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)

night quarryBOT
#

@brisk zenith Your eval job has completed.

001 | True
002 | True
003 | True
004 | False
wraith lance
#

@stone apex what book is that?

#

oh sorry i never saw your message

#

sorry

stone apex
#

It's really good, highly recommended

crisp pendant
#

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
broken agate
#

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

coral fiber
#
def isprime(x): return not any(x%i==0 for i in range(2,x))
#

@broken agate GWpingPingedPong

broken agate
#

โ›ณ

#

well done

coral fiber
#

wonder why builtins are not colored

broken agate
#

ยฏ_(ใƒ„)_/ยฏ

coral fiber
#

/doubletableflip

novel vine
#

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

snow beacon
#

You can decrease its O() by only checking up to โˆšx or x/2

tropic gulch
#

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

cosmic crystal
#

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

brisk zenith
#

certainly sounds like it. mind giving an example of it in action?

cosmic crystal
#

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

pine edge
#

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

tropic night
#

are you "allowed" to use imports when making a quine?

pine edge
#

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

tropic night
#

import is reading a file, it might be for that reason

#
_='_=%r;print _(%%)_';print _(%)_
pine edge
#

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(_%_)
tropic night
#

this is old formating syntax

pine edge
#

i mean it still works though

tropic night
#

yeah, it is not deprecated

#

I use this sometimes by mistake out of old habbits

#

!r would be the repr object

pine edge
#

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

mortal ingot
#

yeah... was wondering what that does

pine edge
#

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

green nymph
#

that is for py3

pine edge
#
>>> _='_=%r;print _(%%)_';print _(%)_
  File "<stdin>", line 1
    _='_=%r;print _(%%)_';print _(%)_
                                ^
SyntaxError: invalid syntax

nope, print needs outer parenthesis in py3

green nymph
#

true, my bad

tropic night
#

_%_ is printing the variable _ with _as an input to the string formating

pine edge
#

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

tropic night
#

yes it should..

mortal ingot
#

what does _(%)_ do

pine edge
#

nothing afaik

#

i made this modification _='_=%r;print(_%%_)';print(_%_)

tropic night
#

ermm.. then i missspelled it ๐Ÿ˜„

pine edge
#

and this runs

tropic night
#

oh yeah.. your right

cursive fox
#

fizzbuzz in 68 characters

for i in range(1,101):print(("Fizz"*(i%3==0))+("Buzz"*(i%5==0))or i)```
#

oops, had extra parenthesis
64 char

for i in range(1,101):print("Fizz"*(i%3==0)+"Buzz"*(i%5==0)or i)```
sick hound
#

Just replace i%3==0 with i%3<1

#

Should be effectively the same thing in this case

#

Same with i%5

cursive fox
#

62 char

for i in range(1,101):print("Fizz"*(i%3<1)+"Buzz"*(i%5<1)or i)``` ![thnkng](https://cdn.discordapp.com/emojis/341883240010874881.webp?size=128 "thnkng")
cursive fox
#

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.

green nymph
#

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.

cursive fox
#

oh dur when range is (0,100) can just (100)
which brings it to 59 char under py3, actually shorter than exec...

green nymph
#

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

grave rover
#

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.

green nymph
#

like

from ctypes import *
cast(id(2),POINTER(c_int))[6]=1
grave rover
#

But can you do it shorter? I know how

green nymph
#

like

False=True
#

I guess might work

#

lemme try

thorny granite
#

only on py2

green nymph
#

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
mortal ingot
#

not that easy yeah, you're just rebinding False, but the underlying bool is still there

green nymph
#

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.

grave rover
#

:)

green nymph
#

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

grave rover
#

example input-output?

snow beacon
#

{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.

lone ruin
#
o = print
__builtins__.print = lambda d: o(True)
print(1 == 2)```

True

#

cheating a bit

snow beacon
#

Also cheating: python 1+\

snow beacon
#

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.

snow beacon
#

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)

cosmic crystal
#

when they say "no, thats not possible, youll have to do somthing else" i make it happen by sheer force of will

sick hound
#

So confuused by what you mean

#

๐Ÿค”

#

@cosmic crystal

#

?

cosmic crystal
#

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

sick hound
#

oh cool

grave rover
#
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
sick hound
#

(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"

snow beacon
#

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?

pine edge
#

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

sick hound
#

@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

snow beacon
#

I meant the competition

sick hound
#

it's just that the dict you were using ain't a linked list

#

ah

snow beacon
#

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

grave rover
#

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 ast module

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.

snow beacon
#
lambda f:object``` is not quite what you're looking for, I don't think
grave rover
#

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 :^)

snow beacon
#

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

snow beacon
#
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
snow beacon
#
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"]

grave rover
#

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

snow beacon
#

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

sick hound
#

goal afaict is just to figure out how to call the function

#

and then check the type() of its return value

snow beacon
#

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

sick hound
#

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]]

snow beacon
#

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

sick hound
#

of course, goal's just try for as many as possible

grave rover
#

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

pine edge
#

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

snow beacon
#

But some instantiation requires parameters

grave rover
#

^

#

The easiest way to solve this problem would be to use ast, or you could fuck around with the raw code

#

maybe even dis :P

#

I'll submit my own solution later today