#esoteric-python

1 messages ยท Page 92 of 1

calm rampart
#

oh this is esoteric python

#

still mixing directions is so ugly ๐Ÿ˜›

vestal solstice
#

no, this is ugly

n^s<(a[10:]==e^w*a) 
#

damn, that doesn;t work

vestal solstice
#

e^w<(w+n<6)>n^s if there are only these letters?

thin trout
#

no, this is ugly
@vestal solstice isn't that the point? lemon_pleased

brisk zenith
#

challenge: make a program that outputs hello, world! (exactly like that) such that each character in the code only appears once. if that's too difficult, try without the comma in the string.

#

i don't know if it's possible, and i have my doubts

snow beacon
#

So, that excludes lambdas, defining then calling a function, returns, more than one call, quoted strings, more than one attribute access, defining a class unless you can find a tuple of types somewhere, try...

#

else and elif, exponentiation...

brisk zenith
#

haha yikes, that is a lot of restrictions.

edgy kelp
#

Not sure if you can with a print

snow beacon
#

You can't import sys or os for write-type functions.

#

You can't .encode without some shenanigans.

#

You can't use variables.

#

Perhaps Python 2 can get closer, with the print statement.

#

That frees up a call to try and get the string from somewhere.

#

I wonder if it's cheating to use a different encoding for the file.

edgy kelp
#

Can't think of a way that'd make this possible with unique everything, maybe with some funky source file encoding

snow beacon
#

I'm inclined to call this one impossible without encoding machinations. It does give me another challenge idea: I wonder how much you could do with only brackets, space and lowercase ASCII letters.

edgy kelp
#

Could try the smallest amount of unique chars/codepoints

snow beacon
#

A scoring mechanism could be taking each codepoint in the file, counting the instances of it and multiplying the results together.

#

That way the fewer duplicates, the better.

#

If you don't repeat characters, you get a score of 1, and if you repeat you get 2. If you repeat one character twice, that's pretty bad. If you repeat two characters once, that's worse.

brisk zenith
#

i think repeating one character twice should be worse

#

a reasonable scoring to me would be to add 1 for each character, then 2 for each first duplicate, then 3 for the next, and so on

#

so "hello" would get (1 + 1 + 1 + 2 + 1) == 6

#

that makes dunders very expensive

rugged sparrow
#

!e import hello

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

Hello world!
sick hound
#

!eval

def hidden_w(keyword, counter=0):
    return ''.join(c if (i < counter or c == ' ') else '.' for i, c in enumerate(keyword))

for c in range(11):
    print(hidden_w("house boat", c))
night quarryBOT
#

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

001 | ..... ....
002 | h.... ....
003 | ho... ....
004 | hou.. ....
005 | hous. ....
006 | house ....
007 | house ....
008 | house b...
009 | house bo..
010 | house boa.
011 | house boat
sick hound
#

@fiery hare It's been fixed :)

fiery hare
#

@sick hound yay

thin trout
#

i think repeating one character twice should be worse
@brisk zenith print('Hello, world!') is a valid solution then lemon_pleased

#

Oh wait no

#

!charinfo o

night quarryBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

brisk zenith
#

:D

thin trout
#

Can't even use the Unicode point, it starts with two zeros

brisk zenith
#

haha yeah

thin trout
#

Or we need to use another o

brisk zenith
#

i mean, i said the word "exactly" on purpose :D

#

but also there's three l's and two quotes

thin trout
#

And the freakin' l

idle lynx
#

I don't know what is so fun about these but they just are...

def complexify(func, layers=5):
    new_func = func
    for _ in range(layers-1):
        new_func = lambda *args, func=new_func, **kwargs: (
            lambda *args2, **kwargs2: func(*args, *args2,
                                           **kwargs, **kwargs2))
    return new_func

# tests | | |
#       V V V
def print_args(*args, **kwargs):
    print(args, kwargs)

yeet = complexify(print_args)
yeet(2)(3)(d=2)(a=5)()```
river idol
formal sandal
#

oh, it mentions the pistol operator as well

#

I thought it was super clever ๐Ÿ˜ฆ

snow beacon
#

I was nonplussed and confused by the factorial bit until I realised I had code ligatures on.

#

It just looked like assert 0โ‰ 1.

dense umbra
#

Hi

sick hound
#

this channel scares me

brisk zenith
#

:)

zealous widget
#

don't be scared, we can play a game of tic-tac-toe if you'd like:

from itertools import*;m,p,q,r,s,l,a=dict(enumerate("276951438")),[[],[]],0,print,' โ”‚ โ”‚ ','โ”€โ”ผโ”€โ”ผโ”€','XO';b=[*map(list,[s,l,s,l,s])];f=lambda:r('\n'.join(map(''.join,b)));f()
while m:
 i=int(input(a[q]+' move: '))-1;p[q]+=[int(m.pop(i))];b[~(i//3*2)][i%3*2]=a[q];f()
 if any(sum(d)==15for d in combinations(p[q],3)):r(a[q]+' wins');break
 q^=1
else:r('Draw')
sick hound
#

tf is that monster

last locust
#

It's tic-tac-toe

hard spoke
#

nah, I don't think this has any relation to TensorFlow

sick hound
#

xd

glacial nova
#

The code is quite amazing, the string "276951438" seems random at first but I never thought it's also used for validating the winning pattern

#

Esoteric Python is interesting

zealous widget
glacial nova
#

Thank you!

thin trout
#

@zealous widget do you have a one line version of this bad boi? lemon_pika

zealous widget
#

I don't

#

thought it's not that far from one, if you can redo the while loop to some comp

proper vault
#

execute code in a __name__=='__main__' from a different file without starting a new process

zealous widget
#
with open('my_code.py', 'r') as code:
      exec(dedent(code.read().partition('__name__ == "__main__":')[-1])
proper vault
#

I guess you could also do exec with __name__ as a local

zealous widget
#

that's true

#

sounds easier

uneven coral
#

Hello. Excuse me if this is the wrong place to ask, please direct me if so.

I need to create a non linear ruler image using a function. An example would be exp(11.78*x-99.64)/(x+230)). I would have a baseline x=1,2,3.... and then based on x place hashmarks for certain values of x(2,6,13).
Does anyone have an idea for how to create such an ruler?
This is for creating a slide ruler for those interested.

hard spoke
#

not really the right channel, but there isn't a topical one for this

you could use something like PIL directly, I suppose.

uneven coral
#

okey thanks

snow beacon
#

Is there a way to select all elements of a frozenset that have a given hash, without iterating through the whole frozenset?

neat otter
#

Pretty amazing way to do it

proper vault
#

@snow beacon maybe sth like

class Hashy:
  def __init__(self, hash_)
    self.hash=hash_
  def __hash__(self):
    return self.hash
  def __eq__(self, _):
    return True
elems = o_set -(o_set|Hashy(target_hash))
#

Can't test cause phone, but it should work

snow beacon
#

The __eq__ will need another parameter.

#

I see what you're getting at.

proper vault
#

But it does break the hash contract

#

Which is not great

snow beacon
#

I don't think the final set operation is right either. It'll end up with an empty set. Maybe o_set - (o_set - {Hashy(target_hash)}).

proper vault
#

Ah right

snow beacon
#

I can't decide if I want to use something like this in proper code or not.

proper vault
#

A better way may be to make eq check hash

snow beacon
#

A possible issue: even if Hashy(...) thinks it's equal to something, the thing might not think it's equal to Hashy(...).

proper vault
#

That would be a valid class at that point

snow beacon
#

I don't think Python makes any guarantees about what checks what's equality for set operations.

proper vault
#

==

snow beacon
#

I like your solution though. There I was thinking about ctypes and all.

proper vault
#

And == guarantees hash equality

snow beacon
#

a == Hashy(0) and Hashy(0) == a might give different results though.

proper vault
#

No, == is always commutative, it checks both sides

#

!e

class U:
	def __eq__( self, _ ):
		return True
print(1==U(), U()==1)
night quarryBOT
#

@proper vault :white_check_mark: Your eval job has completed with return code 0.

True True
snow beacon
#

It seems to work fine for integers, but if I define a class that always compares unequal, then it depends on the order.

proper vault
#

Huh

snow beacon
#

I wrote one of the hash-equality classes and a class that always compares False with its hash equal to 0. Looks like for in, it runs element.__eq__ for each element in the set.

#

With a & b it runs __eq__ on elements of a.

#

Same with |.

zealous widget
#

== isn't always commutative

snow beacon
#

a - b, the important one, checks a, which is not the one we want.

#

At least it's deterministic. I had my fears.

zealous widget
#
In [65]: ANYTHING == NOTHING, NOTHING == ANYTHING
Out[65]: (True, False)
snow beacon
#

Weird, a ^ b seems to check b's __eq__.

#

Amusingly you can have a & b == a ^ b for non-empty sets.

#

o_set ^ (o_set ^ {hash_eq}) should do it, then.

#

Or I suppose o_set & (o_set ^ (o_set ^ {hash_eq})) in case nothing hashes to what you want.

thin trout
#

It seems to work fine for integers, but if I define a class that always compares unequal, then it depends on the order.
@snow beacon that make sense, int is probably returning NotImplemented for objects other than int or float, so it will delegate the check to the other class, while if you class always return False, only the first check will be ran (I might be misunderstanding this though)

stark fable
#
>>> 1 .__eq__('a')
NotImplemented``` yup
potent comet
#

That's why it's important to return NotImplemented. Python itself will raise the TypeError if both do so.

thin trout
#

Yup

snow beacon
#

That is useful.

sick hound
#
def f(_: (x := lambda func: lambda arg: func(arg + 1)) = 1):
    @x
    def a(b):
        print(b) # 2

    a(1)


f()
#
i = 2

def f() -> (g := lambda: print(i)):
    i = 1
    g() # not 1,this is 2 

f() # 2
snow beacon
#

Prints... 2?

sick hound
#

correct!

marsh void
#

makes sense since g's namespace does not use f's locals

#

but like... why would one use that?

thin trout
#

Because one would use the rest of the code in this channel? pithink

unkempt crow
#

.

burnt pasture
#

@snow beacon i'm curious about your interest in objects that hash the same. that doesn't sound what hashes are normally used for.

snow beacon
#

My goal was to use a regular frozenset of key/value pairs to implement a mapping with less than linear time complexity.

burnt pasture
#

sets are already constant-time

snow beacon
#

Dicts and frozensets divide their objects into hash buckets, which is how they find things so quickly. The hard part is that the value half of the key/value pair won't compare equal without some massaging.

burnt pasture
#

i don't understand what you are trying to make. it sounds like a dictionary. how is it different?

snow beacon
#

It's an immutable dictionary.

#

There is an implementation of them built on regular dicts, but I wanted to built something immutable from the ground up.

#

Frozensets and tuples all the way down, for the most part.

burnt pasture
#

i see

snow beacon
#

I put what I have on PyPI this evening, but what I don't have is that O(log(n)) indexing.

#

Using set operations is fast because it's in C, but it's probably O(n) and makes my code look like someone made spaghetti out of confetti.

burnt pasture
#

did you try wrapping your key/value tuples in a class that implements __hash__ and __eq__ as you need?

snow beacon
#

I currently wrap my values in a class, so that they can be hashable.

#

frozenset({(key, HashBox(value))})

burnt pasture
#

doesn't that give you O(1) lookup?

snow beacon
#

For __contains__, but if I want __getitem__ I need to make sure I'm getting back the value in the set, not the one I use to compare.

burnt pasture
#

i see

snow beacon
#

It's unfortunate that .remove() doesn't return what it removes.

#

Not that it's implemented on frozensets anyway.

#
def __getitem__(self, key_to_find):
    contents = self._get_contents()
    same_hash_object = HashEqObject(DEFAULT_HASH)
    same_hash_set = frozenset({(key_to_find, same_hash_object)})
    #trick relying on non-commutative edge cases of set operations
    #fast but not a good idea
    equal_contents = contents & (contents ^ (contents ^ same_hash_set))
    #equal_contents is all contents that match the key.
    for key, box in equal_contents:
        if key == key_to_find:
            return box.contents
    raise KeyError(key_to_find)```I'm ruminating about whether to put this beast into my code, or to keep it just iterating through pairs.
#

I don't strictly need the if statement, but it makes the code seem more intelligible.

proper vault
#

why not do something like

@dataclass
class Item:
    k: Hashable
    v: Any
    def __hash__(self):
        return hash(self.k)
    def __eq__(self, other):
        return self.k == other.k
```and have the frozenset contain those
#

then you can just use Item(k, None) as the search

formal sandal
#

If you just iterate through pairs, it's just O(n), right?

#

@snow beacon what about this hack

#

wait a moment

#

!e

class Probe:
    def __init__(self, k):
        self.k = k
        self.last_equality_check = None

    def __eq__(self, other):
        if not isinstance(other, (Pair, Probe)):
            return NotImplemented
        self.last_equality_check = other
        return self.k == other.k
    
    def __hash__(self):
        return hash(Pair(self.k, None))


class Pair:
    def __init__(self, k, v):
        self.k = k
        self.v = v

    def __hash__(self):
        return hash(hash(self.k) + 42000)

    def __eq__(self, other):
        if not isinstance(other, Pair):
            return NotImplemented
        return self.k == other.k

    def __repr__(self):
        return f"Pair({self.k!r}, {self.v!r})"


frozendict = frozenset([
    Pair("hello", 1),
    Pair("world", 2),
    Pair("abc",   3),
])


def get_value_from_frozendict(fd, key):
    probe = Probe(key)
    if probe not in fd:
        raise KeyError(key)
    return probe.last_equality_check.v

print(get_value_from_frozendict(frozendict, "hello"))
print(get_value_from_frozendict(frozendict, "world"))
print(get_value_from_frozendict(frozendict, "abc"))
print(get_value_from_frozendict(frozendict, "aaaaa"))
night quarryBOT
#

@formal sandal :x: Your eval job has completed with return code 1.

001 | 1
002 | 2
003 | 3
004 | Traceback (most recent call last):
005 |   File "<string>", line 49, in <module>
006 |   File "<string>", line 43, in get_value_from_frozendict
007 | KeyError: 'aaaaa'
formal sandal
#

behold

#

amortized O(1) lookup

#

the probe remembers the last object it was compared to

snow beacon
#

I like this trick, and may corrupt it for my aims.

formal sandal
snow beacon
#

I thought I did, but a part of me wants to make one myself. For any actual projects I'll probably use that or frozendict.

pine wagon
#

!e

class Hah:
    def __init__(s, k, p=None):
        s.p = p
        s.k = k
    
    def __getattr__(s, k):
        return Hah(k, s)
    
    def __str__(h):
        if h.p is None:
            return h.k
        return str(h.p)+h.k

H = Hah("H")
print(
    H.e.l.l.o._.W.o.r.l.d
)
night quarryBOT
#

@pine wagon :white_check_mark: Your eval job has completed with return code 0.

Hello_World
boreal slate
#
import sys; print(a:=sys.argv[1])
for x in range(int(sys.argv[2])-1):print(a:=a[1:]+a[0])``` how do i make this shorter?
snow beacon
#

Does this work?python import sys;v=sys.argv;p=print;p(a:=v[1]) for()in-~int(v[2])*[()]:p(a:=a[1:]+a[0])

boreal slate
#

nope,

snow beacon
#
import sys;v=sys.argv;p=print;p(a:=v[1])
for _ in-~int(v[2])*[0]:p(a:=a[1:]+a[0])```How about now?
#

Oh, I got the - and ~ round the wrong way.

#
import sys;v=sys.argv;p=print;p(a:=v[1])
for _ in~-int(v[2])*[0]:p(a:=a[1:]+a[0])```
zealous widget
#

might save some subscripting if you unpack argv at the start

snow beacon
#
import sys;_,f,s,*r=sys.argv;p=print;p(a:=f)
for _ in~-int(s)*[0]:p(a:=a[1:]+a[0])```
#

I don't think this is shorter.

#

You might not need the ,*r. I haven't tested any of this.

zealous widget
#

why do you have a:=f

grizzled cloak
#
import sys;_,g,a=sys.argv
for i in range(int(g)):print(a[i:]+a[:i])

longer right?

snow beacon
#

You might need another thing to unpack into.

#

sys.argv[0] is generally the script name.

grizzled cloak
#

true

snow beacon
#

Does that work for a>len(g)?

grizzled cloak
#

um

#

1 sec

#

wait

#

do you mean g > len(a)?

snow beacon
#

That one, yes.

grizzled cloak
#

nope

#

works until g == len(a)

#

fix:

import sys;_,g,a=sys.argv;l=len(a)
for i in range(int(g)):print(a[i%l:]+a[:i%l])
#

80 char

zealous widget
#
import sys;_,a,t=sys.argv
for i in range(int(t)):print(a[i:]+a[:i])
grizzled cloak
#

thats what i posted earlier, but it wont work for t > len(a)

#

oh

snow beacon
#

Perhaps some % is in order?

grizzled cloak
#

i had a typo in there

#

yes

#

check my last codeblock ๐Ÿ™‚

snow beacon
#

Oh, I didn't see that message.

boreal slate
#

hmmm, py import sys;_=sys.argv;print(a:=_[1]) for x in range(int(_[2])-1):print(a:=a[1:]+a[0]) this is what i got

snow beacon
#

My brain is still grappling with Rust and misses things.

grizzled cloak
#

did you just name a actually usefull var _? lol

#

very esoteric

boreal slate
#

wana make it shorter, hmmmmm

#

how short can i get that with py2?

grizzled cloak
#

so my best is 80

#

oh

#

i think mine is broken

boreal slate
#

mine is 85 currently

grizzled cloak
#

nvm mine is fine

boreal slate
#

which one? @grizzled cloak lemme try that

grizzled cloak
#
import sys;_,a,g=sys.argv;l=len(a)
for i in range(int(g)):print(a[i%l:]+a[:i%l])
#

arg order is reversed here i think

boreal slate
#

nah not working

#

for this this

grizzled cloak
#
SpiralMePlz
piralMePlzS
iralMePlzSp
ralMePlzSpi
alMePlzSpir
lMePlzSpira
MePlzSpiral
ePlzSpiralM
PlzSpiralMe
lzSpiralMeP
zSpiralMePl
SpiralMePlz
piralMePlzS
iralMePlzSp
ralMePlzSpi
#

my output

boreal slate
#

it should be only 7

grizzled cloak
#

i used 15

#

try now

#

i reversed the args so it matches the problem statement now

boreal slate
#

works

#

hmm, my friend did it 67

#

in python2

snow beacon
#

Is there no other way to get inputs?

boreal slate
#

nah

proper vault
#
import sys;_,a,g=sys.argv
for()in[[]]*int(g):print(a);a=a[1:]+a[0]
```66
boreal slate
#

why [[]] and not [] @proper vault ?

proper vault
#

[]*85 is just [], which does not contain 85 elements

boreal slate
#

okh but i did't understand

#

i understood everything else

#

but not [[]]*int(g)

#

is this the same as []*int(g)

proper vault
#

[[],[],[],[],[]] is what you get, each element of which you unpack into 0 variables

boreal slate
#

okh

#

i get it know

formal sandal
#

!e

print( float("iNfInItY") )
night quarryBOT
#

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

inf
scarlet shoal
#

Damn this was a Lil error that stopped my execution

proper vault
#

use #bot-commands for messing with the bot please

scarlet shoal
#

Uh oh... Sorry I'll keep that in mind!

sick hound
#

!e
import sys;_,a,g=sys.argv
for()in[[]]*int(g):print(a);a=a[1:]+a[0]

night quarryBOT
#

@sick hound :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | ValueError: not enough values to unpack (expected 3, got 1)
gloomy orchid
#

pog

snow beacon
#

Can !e be passed command line arguments?

edgy kelp
#

Don't think you can, it passes the evaled string after -c

sick hound
#

Can this hcf be function be more compacted?

a=lambda x,y:a(y,x%y) if y else x
zealous widget
#
a=lambda x,y:(a(y,x%y),x)[not y]
sick hound
#

๐Ÿ‘€

#

Makes sensee

#

Eh

#

ZeroDivisionError: integer division or modulo by zero

#

!e

a=lambda x,y:(a(y,x%y),x)[not y]
a(100,3)
night quarryBOT
#

@sick hound :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 |   File "<string>", line 1, in <lambda>
004 |   File "<string>", line 1, in <lambda>
005 |   File "<string>", line 1, in <lambda>
006 | ZeroDivisionError: integer division or modulo by zero
cedar herald
#

doesn't that result in infinite recursion?

sick hound
#

It actually shudnt but a(y,x%y) is causing an error

#

if y is 0 then not y will be 1 then (a(y,x%y),x)[1] will be x which stops the recursion

cedar herald
#

as in, a(y,x%y) still has to be evaluated in that case, no?

sick hound
#

Yess thats why the error occurs

rugged sparrow
#

it makes sense cause using the tuple in that method means that a(y,x%y) is always execed

#

which means that the recursion never exits

boreal slate
#

so i want to make a code which takes a input int, and then converts it into a list, for example if the input it is 5 then the list will be [1,2,3,4,5] and on that i need to perform this function,(sum of even number squares) - (sum of odd number squares). how do i do this in lambda and short

cedar herald
#

!e

x = lambda n: sum(map(lambda e: e**2, range(2, n+1, 2))) - sum(map(lambda e: e**2, range(1, n+1, 2)))
print(x(5))
night quarryBOT
#

@cedar herald :white_check_mark: Your eval job has completed with return code 0.

-15
boreal slate
#

it should get this output ```py
For k = 5, the output should be
appleBoxes(k) = -15.

There are 1 + 3 * 3 + 5 * 5 = 35 yellow apples and 2 * 2 + 4 * 4 = 20 red apples, making the answer 20 - 35 = -15.```

#

oh i tried that but failed

#

lemme see where i went wrong

#

is there anyway to get that shorter?

cedar herald
#

With only the standard Python libraries? Not too sure

boreal slate
#

i tried making short but doesn't work then

#

With only the standard Python libraries? Not too sure
@cedar herald yes with only standard ones

spring fractal
#
((b := lambda x: print(x))
,(sqrt := __import__("math").sqrt)
,(i := lambda k: int(k))
,(c := lambda n: i(((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))))
,[b(c(x)) for x in range(20)]
)
#

yes

boreal slate
#

it takes too much time @cedar herald 57 seconds,

#

i tried to get it down, but wasn't successful

cedar herald
#

is it really necessary that you do it in one line?

boreal slate
#

nah, just one functino @cedar herald

#

i tried reducing your solution and making it more efficient but it doesn't happen

#

by friend got it 36, oof

cedar herald
#

don't use one line then

#
def fn(n):
    result = 0
    for x in range(1, n+1):
        if x % 2 == 0:
            result += x * x
        else:
            result -= x * x
    return result
boreal slate
#

this was my first solution, i need to keep it short but efficient

#

or only very short

cedar herald
#

why though?

boreal slate
#

we are having a challenge to who gets it the most down

cedar herald
#

then it's kinda pointless if I helped you xD

boreal slate
#

but i couldn't get below 99

#

then you got 95

cedar herald
#

If this beats your friend then I win, not you ๐Ÿ˜›

#

!e

import itertools
x = lambda n: sum(v * v * c for v, c in zip(range(1, n+1), itertools.cycle([-1, 1])))
print(x(5))
night quarryBOT
#

@cedar herald :white_check_mark: Your eval job has completed with return code 0.

-15
zealous widget
#
s=lambda n:sum((i*i)*((-1)**(i%2))for i in range(1,n+1))
cedar herald
#

they want it to be fast, I wonder whether the repeated computation of i%2 would be faster than simply cycling through the list

zealous widget
#

if you want it to be fast use closed form solution

#
In [32]: evens=lambda n:2*n*(n+1)*(2*n+1)//3
    ...: odds=lambda n:n*(2*n+1)*(2*n-1)//3

In [33]: evens(2) - odds(3)
Out[33]: -15
#

no loops

boreal slate
#

it needs to be one-line and small

zealous widget
#

it can still be small

boreal slate
#

your other one is 66 but kinda slow

#

nah, by small i mean like 40

cedar herald
#

40 what?

#

also that closed form solution is the fastest but it might be considered cheating by your friend, idk

boreal slate
#

idk, maybe even he is

#

got it down two short

cedar herald
#

what did you use

boreal slate
#

i just removed unwanted things from salt-die's solution

#

lambda n:sum(i*i*((-1)**(i%2))for i in range(1,n+1))

snow beacon
#

lambda n:sum(i*i*((-1)**i)for i in range(1,n+1)) should work just as well.

#

You might not need the brackets around ((-1)**i).

copper thunder
#

Instead of (-1)**(i%2) you can do 1-(i%2)*2

#

Not sure if you can remove the last two parenthesis though but maybe... You'll have to check

#

And if you want it to be faster i&2 could be better ^^

boreal slate
#

And if you want it to be faster i&2 could be better ^^
@copper thunder what do you mean by this

copper thunder
#

I meant replacing the i%2 by a i&1, since it is the same operation but may be faster

#

Btw it is &1 not &2

boreal slate
#

okay lemme try that

thin trout
#

I hope CPython is already applying this optimisation

#

It would be pretty stupid not to

copper thunder
#

I hope so, but it's worth trying

boreal slate
#

this is much slower

copper thunder
#

This is very surprising

#

What code dit you try?

thin trout
#

Unh

boreal slate
#

x=lambda n:sum(i*i*1-(i&2)*2for i in range(1,n+1))

#

it passes 0 test cases

vestal solstice
#

&1

#

you made a mistake

boreal slate
#

oh k

copper thunder
#

And it needs parenthesis around (1-2*(i&1))

#

Also you could drop the 1, in the range since when i=0 it adds nothing to the sum

boreal slate
#

even that doesn't work @vestal solstice

#

x=lambda n:sum(i*i*(-1)**(i%2)for i in range(1,n+1)) this is current code,

#

i didn' get what you said

#

(1-2*(i&1)) there is no 1, and 2?

copper thunder
#

x=lambda n:sum(i*i*(1-i%2*2)for i in range(n+1))

#

Though computing the exact solution directly would solve it faster and in less code, but I won't do it for you if it is a challenge with your friend

sick hound
#

Can this go any shorter?: ''.join([re.sub(r'\S', f'||{l}||', l) for l in m]) where m is a string and l is a letter in that string (spaces should be ignored)

thin trout
#

You can get rid of the list comp and use a generator expression I think (without any [])

#

You can also remove spaces after commas

sick hound
#

sum(re.sub(r'\S',f'||{l}||',l) for l in m)?

#

I don't know I've never used that before

#
for a in d:
    for b in a:
        e += (b + ' | ')
    e += 'txt'

Can i make this 1 line?

thin trout
#

Wait, you can sum() strings instead of joining?

#

Thatโ€™s awesome, enever thought about that

sick hound
#

Eh?

#

TypeError: sum() can't sum strings [use ''.join(seq) instead]

#

right yeah

#

I just tried out something, had no idea if it was going to work

#

sry

#

I personally got TypeError: unsupported operand type(s) for +: 'int' and 'str'

#

Even though I wasn't doing any calculations ๐Ÿค”

#

Thats when u put strings inside a list and use sum() on it

#

If you do sum('a','b','c') it will raise my error

#

sum(['a','b','c']) raises ur error

#

I see

boreal slate
#
def decorator(func):
  def warp_func(k):
    print('---------')
    func(k)
    print('---------')
  return warp_func


@decorator
def name(j):
  print(j)
mn=decorator(name)
mn('dhrumil') ``` can i get this in one line?
thin trout
#

You want a oneline decorator?

#
decorator = lamda f: lambda: (print('โ€”โ€”โ€”'), f(), print('โ€”โ€”โ€”'))[1]```I think?
next flame
#

inner lambda needs a param

rugged sparrow
#
decorator = lambda f:lambda *a,**k:(print('-'*9),f(*a,**k),print('-'*9))[1]```
#

^ that will pass all args and kwargs into the wrapped function

vague hearth
#

don't you also need to print the output otherwis functions that just return a value with have 2 lines printed

#
decorator = lambda f:lambda *a,**k:(print('-'*9),f(*a,**k),print('-'*9))[1]
@decorator
def foo():
    return 1

x = foo()
---------
---------```
#

it involves expanding the decorator but you can get it to this

#

!e ```py
decorator = lambda f:lambda *a,**k:((print('-'*9),print(o := f(*a,**k)),print('-'*9)), o)[1]
@decorator
def foo():
return 1

x = foo()
print(f"output: {x}")```

night quarryBOT
#

@vague hearth :white_check_mark: Your eval job has completed with return code 0.

001 | ---------
002 | 1
003 | ---------
004 | output: 1
rugged sparrow
#

in his usecase he was printing inside the decorated function

vague hearth
#

ah ok, that would still work then, this just expands it to non-printing functions, doesn't look very nice tho but then again, if thats what your after this probably isn't the way to do it at all xD

sick hound
#

Any other weird way to do this?

#

!e

some_var = 10

def weirdStuff(global_var, v):
    if global_var % 2 == 0:
        globals()[[n for n, v in globals().items() if v == global_var][0]] = v

print(some_var)
weirdStuff(some_var, 12304234)
print(some_var)
night quarryBOT
#

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

001 | 10
002 | 12304234
sick hound
#

Another way I thought of was to use ast, currently looking for a way to ast the same file it's called in without putting the code in a string. Not sure if that's even possible

hard spoke
#

You should be able to inspect the frame the function was called from and change the locals() of it.

formal sandal
#

locals() isn't guaranteed to reflect the changes, though, right?

#

!d locals

night quarryBOT
#
locals()```
Update and return a dictionary representing the current local symbol table. Free variables are returned by [`locals()`](#locals "locals") when it is called in function blocks, but not in class blocks. Note that at the module level, [`locals()`](#locals "locals") and [`globals()`](#globals "globals") are the same dictionary.

Note

The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.
formal sandal
#

^

#

I already hear you screaming -- yes, this is the most appropriate channel to avoid implementaiton-specific behavior!

brisk zenith
#

@boreal slate can't you also do ```py
@(lambda f: ...)
def function(...):
...

boreal slate
#

noice, something new

#

i will surely check it out

brisk zenith
#

idk if it's actually valid syntax

snow beacon
#

I don't believe it is.

brisk zenith
#

!e ```py
@(lambda f: ...)
def function():
...

night quarryBOT
#

@brisk zenith :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     @(lambda f: ...)
003 |      ^
004 | SyntaxError: invalid syntax
brisk zenith
#

ah indeed

snow beacon
#

You can only use identifiers and calls, possibly attributes.

proper vault
#

There is a PEP to fix this IIRC

edgy kelp
#

3.9 will allow any expression in them

copper thunder
#

noice

thin trout
#

They will support that because of some GUI app who had some issues because of that

#

!pep 614

night quarryBOT
#
**PEP 614 - Relaxing Grammar Restrictions On Decorators**
Status

Final

Python-Version

3.9

Created

10-Feb-2020

Type

Standards Track

spring fractal
#

yup works

boreal slate
#

can we compress try and except blocks?

steep mural
#

No you'd have to make a function or something

#

I mean unless you wanna do this exec('try:\n print(x)\nexcept Exception as e:\n print(e)')

boreal slate
#

thanks, i am doing a bunch of challenges online in one liner

#

so asked

#
def sum_up_diagonals(matrix, sum=0):
    for m in range(len(matrix)) :
        sum += matrix[m][m] + matrix[m][-m-1]
    return sum``` can i get this in one line in lambda
steep mural
#

hmm let me know how this goes sum_up_diagonals = lambda matrix, sum=0: sum([matrix[m][m] + matrix[m][-m-1] for m in range(len(matrix))])

#

Pretty sure sum is being redefined there so

#

sum_up_diagonals = lambda matrix, sum_=0: sum_ + sum([matrix[m][m] + matrix[m][-m-1] for m in range(len(matrix))])

#

There

boreal slate
#

oh thanks,

vague hearth
#

instead of -m-1 you can use ~m i think

copper thunder
#

Damn i never though about that! That's a great trick thanks !

hexed siren
#

it is the binary not operator

copper thunder
#

Yep. Often seen as "two's complement"

boreal slate
#

how is ~m different from -m-1 @copper thunder ?

snow beacon
#

It's shorter.

boreal slate
#

so basically ~m subtracts one from m?

formal sandal
#

- m - 1 is not the same as m - 1

snow beacon
#

It inverts all of the bit in the binary representation of an integer.

#

Well, not really in CPython, but that's what it's meant to look like.

spring fractal
#

two's complement says ~n + 1 = -n therefore ~n = -n - 1

boreal slate
#

okh

proper frigate
#

It inverts all of the bit in the binary representation of an integer.
Well, not really in CPython, but that's what it's meant to look like.
What does CPython really do, then ? It just "remembers" that the bits were flipped and inverts all subsequent logic ?

proper vault
#

pretty sure it actually inverts the bits

thin trout
#

Yeah, it is just a C call to do a not on the integer

sick hound
#
async def emojify(emoji: str, *m):
    return ''.join([re.sub(f'{w}', f'{emoji}{w}', w) for w in m]) + emoji
# input: emojify('๐Ÿ‘', 'this is a test message')
# output: "๐Ÿ‘this๐Ÿ‘is๐Ÿ‘a๐Ÿ‘test๐Ÿ‘message๐Ÿ‘"

How can I write this shorter? not sure if re.sub was the right choice here

#

also not really the right channel

grizzled cloak
#
def emojify(e, m):
  return f"{e}{m.replace(' ',e)}{e}"
sick hound
#

I like the idea but I can't use replace on a tuple

#

๐Ÿค”

twilit grotto
#

what tuple are you giving it

rugged sparrow
#
async def emojify(e, *m):
  return ''.join(w.replace(' ',e) for w in m)```
twilit grotto
#

replace changes all of the occurrences though

#

just pass it the string

snow beacon
#

pretty sure it actually inverts the bits
I was expecting there to be weird logic for the arbitrary length integers.

rugged sparrow
#

@twilit grotto his original func took an arbitrary number of arguments m which you need to loop thru

twilit grotto
#

yeah

proper vault
#

e+e.join(''.join(m).split())+e may possibly be shorter

wind karma
#

What exactly is this channel for?

snow beacon
#

Code golf and obfuscation, mainly.

#

Treating Python as a challenge rather than a helper.

sick hound
#

Thanks Chilaxen, that works ๐Ÿ‘

spring pollen
#

A particular retailer is having a 60 percent off sale on a variety of discontinued products. The
retailer would like to help its customers determine the reduced price of the merchandise by
having a printed discount table on the shelf that shows the original prices and the prices after
the discount has been applied.
Create a Function that uses a loop to generate this table, showing the original price, the
discount amount, and the new price for purchases. Ensure that the discount amounts and the
new prices are rounded to 2 decimal places when they are displayed. Return 3 Array of
Original Price, Discount Amount, After Discount Price.
Function Style: ComputeDiscount( TotalNoOfElements, ArrayElements)

#

can some on help me

#

whit this

twilit grotto
hollow patrol
#

I added then and catch to Python coroutines

#
async def returnFive():
    return 5

async def other():
    return await returnFive().then(lambda i: i + 3)

async def main():
    print(await other())

loop.run_until_complete(main())
#

This works internally by turning coroutines to asyncio.Tasks and adding a done callback

snow beacon
#
ComputeDiscount=lambda n,a:[*zip(*((x,.6*x,.4*x)for x in a))]
```Golfed version of the function.
#

Not sure how they want the function to display yet return.

formal sandal
#

...from #internals-and-peps

So I made this.

from functools import partial
import gc
d = gc.get_referents(dict.__dict__)[0]


HELLO = [None]
window = {
    "answer": {
        "get": lambda: 42,
    },
    "hello": {
        "get": lambda: HELLO[0],
        "set": lambda v: HELLO.__setitem__(0, v),
    },
}

@partial(d.__setitem__, "__getitem__")
def get_item(self, key, *, ACTUAL_GETITEM=d["__getitem__"]):
    try:
        return ACTUAL_GETITEM(self, key)
    except:
        if key not in window:
            raise
        if "get" not in ACTUAL_GETITEM(window, key):
            raise KeyError(f"{key} exists, but is not readable (just like your code, ha!)")
        return ACTUAL_GETITEM(ACTUAL_GETITEM(window, key), "get")()


@partial(d.__setitem__, "__setitem__")
def get_item(self, key, value, *, ACTUAL_GETITEM=d["__getitem__"], ACTUAL_SETITEM=d["__setitem__"]):
    if key not in window:
        ACTUAL_SETITEM(self, key, value)
    elif "set" not in window[key]:
        raise KeyError(f"{key} exists, but is not writable")
    else:
        ACTUAL_SETITEM(ACTUAL_GETITEM(window, key), "set")(value)

to make an extra fallback for dict lookup.

runic ruin
#
import random;import string as s;print(*random.choices('_'+s.ascii_letters+s.digits,k=16),sep='')
```I make it a challenge to make it in as least lines (then as least characters) as possible
#

Anything I missed?

#

Any way to make it shorter?

rugged sparrow
#

@formal sandal using dict[key] calls the c code directly

#

dict.__getitem__(key) performs a dot lookup (which looks for python methods first by default)

formal sandal
#

sad

#

Is there any other way to hook into getting a global variable then?

#
Object.defineProperty(window, 'answer', {
  get: () => {
    return 42
  }
});

like this in JS

#

This is how you define a getter for the window obejct.

#

So every time you try to access the answer global variable, you get 42

snow beacon
#
print(*__import__("random").choices(["_",*filter(str.isalnum,map(chr,range(128)))],k=16),sep="")
rugged sparrow
#

@formal sandal the answer is yes, but it needs much ctypes fuckery

snow beacon
#

Or something like forbiddenfruit.

#

(Which is a wrapper around ctypes, of course.)

rugged sparrow
#

yea true

grand tree
#

!e ```py
print(*import("random").choices(["_",*filter(str.isalnum,map(chr,range(128)))],k=16),sep="")

night quarryBOT
#

@grand tree :white_check_mark: Your eval job has completed with return code 0.

M2ZYvWgje6U8cxYr
grand tree
#

cool

snow beacon
#

I invite anyone to do it in less lines.

broken mesa
#
class ParentInstanceMixin():
    def __getattribute__(self, name):
        try:
            return object.__getattribute__(self, name)
        except AttributeError:
            return object.__getattribute__(object.__getattribute__(self, "parent_instance"), name)

i am a horrible person, i know

gentle pagoda
#

ive never used much ctypes, why doesnt this work? py t = type("", (), {}) ctypes.py_object.from_address(id(t)+8).value = type(lambda x: x)

stark fable
#

well what were you expecting it to do, and what did it actually do?

gentle pagoda
#

i was expecting the base class of t to be function, but i got a segfault

#

unless ive misunderstood what thats doing

stark fable
#

well you changed the class of t to be function

#

as in t is now a function object

gentle pagoda
#

hm

#

thats what i wanted i think

stark fable
#

because the thing at that offset into PyObject is a pointer to the type of the object

gentle pagoda
#

right

stark fable
#
>>> import ctypes
>>> t = type("", (), {})
>>> ctypes.py_object.from_address(id(t)+8).value = type(lambda x: x)
>>> t
<function  at 0x000001EEB8140538>```
gentle pagoda
#

that segfaults when running a file though

stark fable
#

that's not really that surprising really, since that t is a pretty nonsensical object

#

you've just unceremoniously picked up data from a type object and told it that it's a function now

gentle pagoda
#

but surely type and function have the same layout in memory, roughly

#

they are both objects

#

ok maybe im asking the wrong question. i wanted to set an attribute of a function, such as __repr__ or __add__. ive seen other examples do it for integers by creating a dummy typ inhereting from int with the new method. i wanted to do the same for functions, but python wont let you have function as a base class

stark fable
#

they're quite different

gentle pagoda
#

oh okay, i thought function was just an object like int is

stark fable
#

they are all objects

#

but they have a lot of stuff on top of that

gentle pagoda
#

hm okay

#

why does that work in the repl then?

#

or is it just setting weird values for each field, and its just coincidence that it doesnt segfault

stark fable
#

i think it's probably just a coincidence

#

doing almost anything else with that function object causes it to segfault

gentle pagoda
#

oh ok

#

so what would be the correct way of setting magic methods on a function object?

#

since i cant replace the base class

sick hound
#

!e

import ctypes
t = type("", (), {})
ctypes.py_object.from_address(id(t)+8).value = type(lambda x: x)
print(str(t))
night quarryBOT
#

@sick hound :x: Your eval job has completed with return code 139 (SIGSEGV).

<function  at 0x5629d4b38b70>
sick hound
#
>>> import ctypes
>>> t = type("", (), {})
>>> ctypes.py_object.from_address(id(t)+8).value = type(lambda x: x)
>>> print(str(t))
<class '__main__.'>

Why???

spring fractal
#

the struct depends on which python version you use

#

and how it was compiled

rugged sparrow
#

!e ```py
from ctypes import Structure, c_ssize_t, py_object

class PyObjStruct(Structure):
fields = [
('ob_refcnt', c_ssize_t),
('ob_type', py_object)
]

t = type('', (), {})
PyObjStruct.from_address(id(t)).ob_type = type(lambda x:x)
print(str(t))

night quarryBOT
#

@rugged sparrow :x: Your eval job has completed with return code 139 (SIGSEGV).

<function  at 0x55c07b4a7130>
formal sandal
#

is there some kind of tutorial on ctypes?

#

it looks a mix of Haskell and Japanese to me

rugged sparrow
#

a lot of it is relatively straight forward if you look at the python source code

remote widget
#

helps to know c, as well

#

If you're really interested or have a big project converting c to python, hit up godlygeek sometime, he's super knowledgeable on the subject.

heady stump
#

Greetings strangers. Anyone in here has had any experience with Google's foobar challange?

hard spoke
heady stump
#

I got invited and I really don't know where to look for guidance, sorry if this is the wrong place to ask.

hard spoke
#

This channel is mostly for fun stuff you wouldn't want to actually ever use ๐Ÿ™‚

heady stump
#

Got it, thanks!

regal reef
#

.> Remind me to tell y'all the story about someone suggesting I use the gc library's ref counter to implement layering in my game engine some time.

#

For ideas of "things that work, but why?"

formal sandal
#

Like, emulate layers with GC generations?

#

@regal reef

regal reef
#

The proposal was basically "Make each layer an object, then find out what's on that layer by using the garbage collector to grab only those object.

formal sandal
#

!e

import gc

class GameObject:
    def __init__(self, id, layer):
        self.id = id
        self.layer = layer

    def __repr__(self):
        return f"<GameObject {self.id}>"

LayerA = object()
LayerB = object()

objects = [
    GameObject(1, LayerA),
    GameObject(2, LayerA),
    GameObject(3, LayerB),
    GameObject(4, LayerA),
    GameObject(5, LayerB),
]

print( gc.get_referrers(LayerA) )
print( gc.get_referrers(LayerB) )
night quarryBOT
#

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

001 | [{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'gc': <module 'gc' (built-in)>, 'GameObject': <class '__main__.GameObject'>, 'LayerA': <object object at 0x7fedcbffbb80>, 'LayerB': <object object at 0x7fedcbffbb90>, 'objects': [<GameObject 1>, <GameObject 2>, <GameObject 3>, <GameObject 4>, <GameObject 5>]}]
002 | [{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'gc': <module 'gc' (built-in)>, 'GameObject': <class '__main__.GameObject'>, 'LayerA': <object object at 0x7fedcbffbb80>, 'LayerB': <object object at 0x7fedcbffbb90>, 'objects': [<GameObject 1>, <GameObject 2>, <GameObject 3>, <GameObject 4>, <GameObject 5>]}]
formal sandal
#

Huh, so I tried doing that, but it doesn't show the GameObjects in there for some reason?

#

only shows the globals() dict

regal reef
#

Good to know it wouldn't even work.

formal sandal
#

my disappointment is immeasurable and my day is ruined

misty jewel
#

!e ```py
from ctypes import Structure, c_ssize_t, py_object

class PyObjStruct(Structure):
fields = [
('ob_refcnt', c_ssize_t),
('ob_type', py_object)
]

t = type('', (), {})
PyObjStruct.from_address(id(t)).ob_type = type(lambda x:x)
print(str(t))

@rugged sparrow

#

@rugged sparrow
@misty jewel Not gonna lie, looks like C or something for some reason.

formal sandal
#

Well... it is C, sort of

fierce olive
#

What is the use case for this?

formal sandal
#

The term 'use case' is prohibited in this channel ๐Ÿ˜ 

#

this channel is reserved for absolutely useless and impractical stuff

fierce olive
#

yeah I guess, and I get the golfing and all, but I don't understand this at all. it doesn't seem as much esoteric as it does a hack

snow beacon
#

My criterion for 'esoteric' is "you wouldn't use it in production code".

fierce olive
#

Then it fits in perfectly here

formal sandal
#

@snow beacon append "if you don't want to get fired" ๐Ÿ™‚

snow beacon
#

"You wouldn't use it in production code if you knew your code would get read by people with the authority to get you fired who know Python best practices, and you don't want to get fired."

twilit grotto
#

why not just "clever hacks"

boreal slate
#

(i am not breaking rule 5)

cedar herald
#

I don't get it. The rays are clearly 3 characters long, not 2

boreal slate
#

i got it from the net, wanted to solve it

zealous widget
#

first code it without golfing

boreal slate
#

i couldn't figure it out

cedar herald
#

The question doesn't make sense to me

zealous widget
#

!e

import numpy as np

def sun(ray_length, start=0):
    dim = ray_length * 2 + 3
    mid = dim // 2
    
    canvas = np.zeros((dim, dim))
    xs = np.arange(dim)
    ys = -xs - 1
    # lines
    canvas[xs, xs] = 1
    canvas[xs, ys] = 1
    canvas[mid, :] = 1
    canvas[:, mid] = 1
    return canvas

print(sun(2))
night quarryBOT
#

@zealous widget :white_check_mark: Your eval job has completed with return code 0.

001 | [[1. 0. 0. 1. 0. 0. 1.]
002 |  [0. 1. 0. 1. 0. 1. 0.]
003 |  [0. 0. 1. 1. 1. 0. 0.]
004 |  [1. 1. 1. 1. 1. 1. 1.]
005 |  [0. 0. 1. 1. 1. 0. 0.]
006 |  [0. 1. 0. 1. 0. 1. 0.]
007 |  [1. 0. 0. 1. 0. 0. 1.]]
zealous widget
#

now you just need to replace the 1's with correct values starting at top-left

#

there's a more clever approach, but I'll leave it as an exercise for the reader

boreal slate
#

that is different

#
'6  7  8'
' 9 O 1'
'  234'
'5678901'
'  234'
' 5 6 7'
'8  9  0'``` it should be like this
zealous widget
#

did you read what i typed

#

it's not difficult to see the correspondence between this array and your desired output

boreal slate
#

hmmm, ok, will try

zealous widget
#

!e

import numpy as np

def cycle(start):
    while True:
        yield start
        start += 1
        start %= 10

def rays(ray_length):
    dim = ray_length * 2 + 3
    mid = dim // 2
    
    canvas = np.zeros((dim, dim), dtype=int) - 1
    xs = np.arange(dim)
    ys = -xs - 1
    # lines
    canvas[xs, xs] = 1
    canvas[xs, ys] = 1
    canvas[mid, :] = 1
    canvas[:, mid] = 1
    return canvas

def replace(canvas, start=0):
    it = np.nditer(canvas, flags=['multi_index'])
    cy = cycle(start)
    for _ in it:
        if canvas[it.multi_index] != - 1:
            canvas[it.multi_index] = next(cy)
    return canvas

def sun(ray_length, start):
    arr = replace(rays(ray_length), start)
    return '\n'.join(''.join(str(i) if i != -1 else ' ' for i in row) for row in arr)

print(sun(2, 6))
night quarryBOT
#

@zealous widget :white_check_mark: Your eval job has completed with return code 0.

001 | 6  7  8
002 |  9 0 1 
003 |   234  
004 | 5678901
005 |   234  
006 |  5 6 7 
007 | 8  9  0
boreal slate
#

ah almost got that, let me see my mistakes

#
' 9 O 1'
'  234'
'5678901'
'  234'
' 5 6 7'
'8  9  0'

is not the same as, this is problem i am getting

' 9 O 1 '
'  234  '
'5678901'
'  234  '
' 5 6 7 '
'8  9  0'```
hard spoke
#

is that an O?

boreal slate
#

yes

boreal slate
#

@zealous widget this

hexed siren
#
>>> >>> (lambda : (print("call"), gc.get_referrers(sys._getframe(0).f_code)[-1]()))()
call
call
...
call
call
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
  File "<stdin>", line 1, in <lambda>
  File "<stdin>", line 1, in <lambda>
  [Previous line repeated 993 more times]
RecursionError: maximum recursion depth exceeded while calling a Python object
``` some recursive lambda. I didn't know how to do that in a simpler way (without naming the lambda, of course).
proper vault
#

you can use a combinator (lambda f: f(f))(lambda f: f(f))

hexed siren
#

oh right ! I didn't think about it, thanks a lot !
(anyway, I love dirty codes ๐Ÿ™ƒ )

formal sandal
#

Can you somehow take advantage of gc to make fizzbuzz?

fair birch
#

Why doesn't deleting __builtins__ from globals() render everything unusable (mess things up)?

snow beacon
#

Do you have an ungolfed version?

boreal slate
#

not yet, i tried but i get the same problem as salt-die did

snow beacon
#

The O is not explained in the problem description. I would suggest one of the help channels might get you something working, and then this channel can get you something disgusting.

boreal slate
boreal slate
#
import numpy as np
import sys as u

def cycle(start):
    while True:
        yield start
        start += 1
        start %= 10

def rays(ray_length):
    dim = ray_length * 2 + 3
    mid = dim // 2
    
    canvas = np.zeros((dim, dim), dtype=int) - 1
    xs = np.arange(dim)
    ys = -xs - 1
    # lines
    canvas[xs, xs] = 1
    canvas[xs, ys] = 1
    canvas[mid, :] = 1
    canvas[:, mid] = 1
    return canvas

def replace(canvas, start=0):
    it = np.nditer(canvas, flags=['multi_index'])
    cy = cycle(start)
    for _ in it:
        if canvas[it.multi_index] != - 1:
            canvas[it.multi_index] = next(cy)
    return canvas

def sun(ray_length, start):
    arr = replace(rays(ray_length), start)
    return '\n'.join(''.join(str(i) if i != -1 else ' ' for i in row).rstrip() for row in arr)

print(sun(int(u.argv[1]), int(u.argv[2])))``` how do i get this short now? @snow beacon
snow beacon
#

For a start, you could calculate a exactly how many numbers you'll need, generate an appropriate range, then take the range % 10. You can remove whitespace and the sys import.

#

Replace i != -1 with ~i.

#

Replace ys = -xs - 1 with ys=~xs

#

Change all the identifiers to single characters.

#

Maybe instead of numpy, you could try printing character by character, checking if the x and y coordinates match any of the x = y, x = len-y, x = len/2, y = len/2 criteria.

#

Instead of using four spaces for your indentation, use one space.

#

Get rid of the sun function and just put its contents into your code.

#

You can do the same with replace.

boreal slate
#

ok let me try if i get stuck i will put it here

#

For a start, you could calculate a exactly how many numbers you'll need, generate an appropriate range, then take the range % 10. You can remove whitespace and the sys import.
@snow beacon what do you mean by this?

snow beacon
#

You have a generator to generate infinite digits.

#

You don't need that many.

#

You can calculate how many you need from the size of the sun.

boreal slate
#

can i do like this a,b,c=*1

#

like *args

#

@snow beacon

#
import numpy as np
import sys as u

def j(start):
    while True:
        yield start
        start+=1
        start%=10
def q(rl):
    d=rl*2+3
    m=d//2
    cv=np.zeros((d, d), dtype=int) - 1
    xs=np.arange(d)
    ys=-xs-1
    cv[xs, xs]=1
    cv[xs, ys]=1
    cv[m, :]=1
    cv[:, m]=1
    return cv
def r(cv,start=0):
    it=np.nditer(cv,flags=['multi_index'])
    cy=j(start)
    for _ in it:
        if cv[it.multi_index]!= -1:
            cv[it.multi_index]=next(cy)
    return cv
t=r(q(int(u.argv[1])), int(u.argv[2]))
print('\n'.join(''.join(str(i) if i !=-1 else ' ' for i in w).rstrip() for w in t))```
#

if args is possible i will do that

#

well got shorter now @snow beacon

zealous widget
#

you can remove all the function calls and just have one long sheet of code

#

and instead of starting with np.zero you can just use np.full and start with an array of spaces

boreal slate
#

this is what i did till now py import numpy as np import sys as u def j(k): while True: yield k k+=1 k%=10 def q(rl): d=rl*2+3 m=d//2 cv=np.zeros((d,d),dtype=int)-1 xs=np.arange(d) ys=-xs-1 cv[xs,xs],cv[xs,ys],cv[m,:],cv[:,m]=1,1,1,1 return cv def r(cv,k=0): it=np.nditer(cv,flags=['multi_index']) cy=j(k) for _ in it: if cv[it.multi_index]!=-1: cv[it.multi_index]=next(cy) return cv print('\n'.join(''.join(str(i) if i !=-1 else ' ' for i in w).rstrip() for w in r(q(int(u.argv[1])), int(u.argv[2]))))

#

well i didn't understand what u said

#

@zealous widget and @snow beacon sorry for the ping!

snow beacon
#

np.zeros makes zeros, which you then replace with spaces. np.full makes some default element you pass it, such as ' ' which you wouldn't need to replace.

#

Also, you can still replace all of your indentation with a single space each time rather than four.

#

I'm not sure there's a simple transformation to get rid of all the functions, but the code from r can be taken out of a function.

#

You can also get rid of the sys import because you don't use u.

zealous widget
#

it's used on the last line

snow beacon
#

Thank you, I didn't see that.

#

It's likely easier to do from sys import* and from numpy import* than using u and np.

zealous widget
#

though you'd probably save characters doing from sys import*

#

ginx

snow beacon
#

Also, @boreal slate I'm not going to apologise for this ping because I did it intentionally.

pastel grail
#

it's still pretty readable tbh

#

you just added a bunch of semicolons to separate lines

runic ruin
#

I HAVE A CHALLENGE
for anyone willing to accept.
The challenge is simple, output the word "Success" in a shorter amount of code than print('Success')
(YOU CAN ONLY USE ONE LINE OF CODE, AND NO SPECIAL MODIFICATIONS TO PYTHON)

Winner gets a pat on the back, and a thank you.

paper bloom
#

print 'Success' 1 less character, requires python 2

tame crow
#

Or go to interpreter and type 'Success'

runic ruin
#

Those both count as special modifications to Python

tame crow
#

๐Ÿค”

paper bloom
#

using python is a modification of python ๐Ÿค”

runic ruin
#

I can't be modified from standard Python 3

tame crow
#

So what's wrong with using the python 3 interpreter?

proper vault
#

quit('Success')

runic ruin
#

It's not a standard interpreter

twilit grotto
#

wait, but it is

#

it is literally the interpreter

tame crow
#

Nice @proper vault

runic ruin
#

quit('Success')
@proper vault ๐Ÿ‘

sudden osprey
#

Success

#

If you allow other text too

#

Will give a NameError

formal sandal
#

wookie184 receives the pat on the back

sudden osprey
#

Yay

runic ruin
#

But @proper vault did it first, so, I pat him instead

cedar elbow
#

Don't worry wookie I'll pat your back

runic ruin
#

If you allow other text too
@sudden osprey I thought about that by the way, but I figured not. Though good effort ๐Ÿ˜‰

paper bloom
#

!e ```py
getattr(
import(True.class.name[1] + [].class.name[2]),
().class.eq.class.name[:2] +
().iter().class.name[6:9]
)(
1, str.encode((lambda _, __: (, __))(
lambda _, : chr( % 256) + (, __ // 256) if __ else "",
753072441997358419
))
)

night quarryBOT
#

@paper bloom :white_check_mark: Your eval job has completed with return code 0.

Success
paper bloom
#

Does this count?

#

could probably obfuscate the str.encode call too

stark fable
#

not really a shorter amount of code than print('Success') :P

pastel grail
#

what are python vm languages

proper vault
#

languages that run on the cpython VM

#

which is like hy

#

and forms DSL

formal sandal
#

well, FormDSL doesn't fit that definition

#

It's just implemented in Python, it's not compiled to bytecode

#

Maybe the description should be changed to "toy languages implemented in Python" or something

proper vault
#

I would say an interpreter in python fits

night quarryBOT
#

@fair wind :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     int main() {
003 |         ^
004 | SyntaxError: invalid syntax
drowsy rock
#

@fair wind This isn't Python.

formal sandal
#

@fair wind you have a syntax error

#

this is how you do it:

twilit grotto
#

you have many syntax errors

formal sandal
#

!e

fะพr=lambda *_:lambda *_:0

fะพr (i := 1, i < 2, ++i) ({
    print(i)
});
night quarryBOT
#

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

1
drowsy rock
#

How are you running it?

formal sandal
twilit grotto
#

you have gcc in your name pithink

slate wasp
#

Challenge: FizzBuzz inside a single print statement. If possible, using only one f-string

azure hare
#

update: I think someone already completed it lol

slate wasp
#

Here's a solution:

print(f"{chr(10).join(['fizz'*(n%3==0)+'buzz'*(n%5==0) or str(n) for n in range(100)])}")
formal sandal
#
print(exec(your source code)or"", end='')

lazy hack

rugged sparrow
#

!e

print(*['fizz'*(n%3==0)+'buzz'*(n%5==0) or n for n in range(100)],sep='\n')
night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

001 | fizzbuzz
002 | 1
003 | 2
004 | fizz
005 | 4
006 | buzz
007 | fizz
008 | 7
009 | 8
010 | fizz
011 | buzz
... (truncated - too many lines)

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

rugged sparrow
#

shorter, and no f-string

slate wasp
#

Yep! That was the original and I made it use an f-string as well (that was half the challenge)

vague hearth
#

!e py print(*('fizz'*(1-n%3)+'buzz'*(1-n%5) or n for n in range(100)),sep='\n')

night quarryBOT
#

@vague hearth :white_check_mark: Your eval job has completed with return code 0.

001 | fizzbuzz
002 | 1
003 | 2
004 | fizz
005 | 4
006 | buzz
007 | fizz
008 | 7
009 | 8
010 | fizz
011 | buzz
... (truncated - too many lines)

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

vague hearth
#

swapping ==0 for 1- before makes it 2 chars shorter

#

(could also change (1-n%5) or n to (1-n%5)or n

clever nova
#

Oooh fizbuzz we were chatting about this on another server the other day

#
for i in range(100):print("Fizz"*(i%3>1)+"Buzz"*(i%5>3)or i+1)``` we got it down to 62
snow beacon
#
for i in range(100):print("Fizz"*(i%3>1)+"Buzz"*(i%5>3)or-~i)
```61
clever nova
#
for i in range(100):print(i%3//2*"Fizz"+i%5//4*"Buzz"or-~i)
``` 59
wanton tundra
#

whats that -~ part doing

twilit grotto
#

negative bit inverted i i think

snow beacon
#

-~x is x+1 but you can omit whitespace before it. ~-x is x-1.

wanton tundra
#

huh

formal sandal
#

Unfortunately, this is 61 :(

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

i had 0 clue this exec existed

#

this server is fun

snow beacon
#

I've muted every channel except this one.

#

This channel is fun.

wanton tundra
#

fair

steep mural
#

!e

fะพr=lambda *_:lambda *_:0

fะพr (i := 1, i < 2, ++i) ({
    print(i)
});

Woah this is valid python?

#

Im actually only surprised about it being wrapped in {} lol

rugged sparrow
#

its valid but it doesnt do what it looks like it does

steep mural
#

++10 doesn't do anything does it

#

I mean i

rugged sparrow
#

+(int) is __pos__

snow beacon
#

Indeed it does not.

rugged sparrow
#

i should use something in int.__pos__ to make it work ๐Ÿ‘€

steep mural
#

Hmm

steep mural
#

!e

class Integer(int):
    def __init__(self, num):
        super().__init__()
    def __pos__(self):
        self += 1
        return self

fะพr=lambda *_:lambda *_:0

fะพr (i := Integer(1), i < 2, ++i) ({
    print(i)
});
night quarryBOT
#

@steep mural :white_check_mark: Your eval job has completed with return code 0.

1
wanton tundra
#

thats some fancy code

steep mural
#

Sad I probably did it wrong

wanton tundra
#

is this what trying to reinvent the wheel looks like

steep mural
#

But it's not a generator so of course it won't work

#

Someone make it work lol

wanton tundra
#

fะพr=lambda *:lambda *: yield 0

#

would this fix it or im dumb

#

!e

class Integer(int):
    def __init__(self, num):
        super().__init__()
    def __pos__(self):
        self += 1
        yield self

fะพr=lambda *_:lambda *_:0

fะพr (i := Integer(1), i < 2, ++i) ({
    print(i)
});

night quarryBOT
#

@wanton tundra :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 10, in <module>
003 | TypeError: bad operand type for unary +: 'generator'
wanton tundra
#

ye i got 0 clue whats going i should go back to just watching

steep mural
#

!e

class Integer(int):
    def __init__(self, num):
        super().__init__()
    def __pos__(self):
        self += 1
        return self

def fะพr(var, condition, after):
    def wrapped(to_do):
        while condition:
            exec(next(iter(to_do)))
            i = after
    return wrapped
fะพr (i := Integer(0), i < 5, i := Integer(++i)) ({
"""
pass
"""});
night quarryBOT
#

@steep mural :warning: Your eval job timed out or ran out of memory.

[No output]
steep mural
#

Doesn't work properly unfortunately

next flame
#

yeah you need to make condition a object

#

bc currently it's just while True

steep mural
#

Oh I thought it had something to do with the scope lol

next flame
#

since condition is only evaluated once when you make the func call

#

returning bool

steep mural
#

!e

class Integer(int):
    def __init__(self, num):
        super().__init__()
    def __pos__(self):
        self += 1
        return self

def fะพr(var, condition, after):
    def wrapped(to_do):
        while eval(condition):
            exec(next(iter(to_do)))
            exec(after)
    return wrapped
fะพr (i := Integer(0), 'i < 5', 'i = Integer(++i)') ({
"""
print(i)
"""});
night quarryBOT
#

@steep mural :white_check_mark: Your eval job has completed with return code 0.

001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
steep mural
#

Good enough

sweet jolt
formal sandal
#

@zealous widget unleash your pink mush

thin trout
#

oh no

formal sandal
#

@sweet jolt If you have a genuine question, I would suggest opening a help channel ๐Ÿ™‚ This channel is more for stuff which is intentionally obscure, overengineered or otherwise uselessified

sweet jolt
#

but yes, I did get my answer on help channel :d

formal sandal
#

Here is an example of sum types (disjoint unions). It uses both metaclasses and metametaclasses (a metametaclass is a metaclass for a metaclass)

#
In [8]: class MaybeInt(SumType):
   ...:     Just.of(int)
   ...:     Nothing.of(())
   ...:

In [9]: x = MaybeInt.Just(42)

In [10]: x
Out[10]: 42

In [11]: type(x)
Out[11]: embellished('Just', <class 'int'>)

In [12]: y = MaybeInt.Nothing(())

In [13]: y
Out[13]: ()

In [14]: type(y)
Out[14]: embellished('Nothing', ())
#

(this is a very esoteric example, not something you would actually use)

sick hound
#

so esoteric that julius evola himself would frequent this channel

steep mural
#

Well the knock off c for loop is without strings which i think is pretty cool

#

!e

class Integer(int):
    def __new__(cls, num, name, base=10):
        self = super().__new__(cls, str(num), base)
        self.name = name
        return self
    def __init__(self, num, base):
        pass
    def __pos__(self):
        return f'Integer({self.name} + 1, {self.name})'
    def __gt__(self, other):
        return f'int({self.name}) > {other}'
    def __lt__(self, other):
        return f'int({self.name}) < {other}'

def fะพr(var, condition, after):
    def wrapped(to_do):
        while eval(condition):
            exec(next(iter(to_do)))
            locals()[var.name] = eval(after)
    return wrapped
fะพr (i := Integer(0, 'i'), i < 3, +i) ({
"""
print('Hello World!')
"""});
night quarryBOT
#

@steep mural :white_check_mark: Your eval job has completed with return code 0.

001 | Hello World!
002 | Hello World!
003 | Hello World!
wanton tundra
#

u seem to enjoy this

rugged sparrow
#

i wonder if you could grab the stackframe inside for() and repeat/cancel exec of it based off of the for args

#

then you wouldnt need the string

#

would def need inspect and ctypes stuff

steep mural
#

Hmm sounds like something out of my league lol

uneven grail
#

Hey y'all, just posted this in the wrong channel I think, so reposting here to get some assistance, hopefully

#

Hey y'all, I have a funky question / discussion topic: what is called when you raise an error? I have implemented a couple custom exception in my source, and what I want is to check the type of __context__ when raise <error> from <other error> is used, and if it is of a certain type, do some extra logic before the exception is actually raised.
I've googled and I can't find anything on this
It seems I'll have to pass it into the initializer for the custom exception, but I'd really like to leverge the raise ... from ... syntax

ornate jay
#

@rugged sparrow perhaps pdb can help you

#
try: raise Exception
except Exception as e:
    do_something_else()
#

@uneven grail

#

Havenโ€™t tested because I donโ€™t exactly know why you would need raise ... from ... but as far as Iโ€™m aware, this behaves as a context for your exception

#

Oh i see.

#

You know whatโ€™s funny is Iโ€™ve been using Python for umpteen years and Iโ€™ve completely forgotten that syntax even exists

#
try: raise SomeException
except SomeException as e:
    do_something_else()
    raise AnotherException from e
uneven grail
#

haha right? I mainly just use raise ... from None when I want to overwrite the exception thrown but yeah, I want to save some metadata into the exception object itself about the exception it is raised from

ornate jay
#

Or you could just do raise Exception

uneven grail
#

and like I get that it gets saved into context but it doesn't seem like there is any way to access it before the raise is actually handled

#

here is a simple example, how do you print what its raised from?

#

Like you can't it seems lol

ornate jay
#

You need the stackframe

#

Take a look at inspect

uneven grail
#

Yeah I could do that, but I want to do this from inside the exception, not the code raising it

#

if that makes sense

ornate jay
#

Nope ๐Ÿ˜

uneven grail
#

lol

#

Like, okay

#

assume I have a custom exception MyException

#

and in my source I have a bit that fails due to some reason and I say raise MyException(stuff, more_stuff, etc.) from OtherException

#

The idea is that I want to save something specific from the OtherException into the MyException instance.

ornate jay
#

How is your MyException written?

uneven grail
#

Now I could always do something like raise MyException(stuff, more_stuff, etc. from=other_exception)

#

but I'm hoping to leverage the from notation

ornate jay
#

Itโ€™s just a class inheriting from Exception

stark fable
#

raise MyException(stuff, more_stuff, etc. from=other_exception)
no you couldn't, from is a keyword

uneven grail
#

okay yeah

#

lol

ornate jay
#

Oh

uneven grail
#

it was just a descriptive example

#

raise MyException(stuff, more_stuff, etc. from_exc=other_exception)

#

^ the name of the arg is not important, just that I'm passing it into the initializer

#

I guess what I'm getting at is that there is not internal method that is called when you raise an exception?

#

so RIGHT when its raised, not when the object is created, you can perform some logic

ornate jay
#

Define __call__ in your class definition?

uneven grail
#

maybe? I can try that

#

here let me share a link

ornate jay
#

I canโ€™t remember if itโ€™s __call__ or __called__

#

Idk man

#

I donโ€™t know what youโ€™re trying to accomplish lol

ornate jay
#

Oh ok

#

Iโ€™m on mobile rn

uneven grail
#

no worries, the goal is to customize some logging around error handling for use in serverless apps. There are a number of exceptions we deal with daily. What I'm trying to handle are boto3 ClientException and httplib HTTPError. I want to save some metadata about the requests themselves into the error signature (see code) automatically

#

right now I just have like 5 different base classes, but really it could be simplified by just saying "oh you are raising from an httperror? Let's save that request data into the signature. Oh its a client error? let's save some of the requests metadata there too"

ornate jay
#

I wouldnโ€™t do that. Iโ€™d use logging. Youโ€™re going to shoot yourself in the foot modifying exception like this haha

uneven grail
#

^ that's what its wrapping lol

ornate jay
#

Hmmm

uneven grail
#

I don't want to insert logging everytime an exception is raised

#

that's just anti DRY

#

I want to have some prebaked, auto logging everytime my custom exception is raised

#

which is being done btw, I just want to extend it

#

the logging part is not the issue

#

its the accessing the context object when the exception is raised, not when its initialized that is the issue

ornate jay
#

Ummmm

#

AAaAAh my brain hurts

uneven grail
#

haha sorry its a pretty funky question

ornate jay
#

I literally canโ€™t fathom why you would need to access Exception after itโ€™s raised.

uneven grail
#

no not after

ornate jay
#

Definitely esoteric for sure lol

uneven grail
#

but like RIGHT before

ornate jay
#

Try except is the best youโ€™re gonna get lol

uneven grail
#

all we can do rn is create an object

#

atleast that's all I know how to do lol

#

but something must be happenning when raise is called

#

I just want to insert some functionality right at the beginning

ornate jay
#

Yea, it excepts

#

Thatโ€™s why you try

uneven grail
#

no so

#

(spacing is weird because discord, sorr)

#

try: ... except Exception as e: ... litterally just catches the exception details and saves them into the object e. That is just initializing it, and you can access all the parameters you want

ornate jay
#

Yes

#

No

#

Not initializing it

uneven grail
#

when you do try: ... except Exception as e: raise MyException from e it creates a new instance, with all the stuff of e saved as __context__ . But that is not available when e is created

ornate jay
#

Itโ€™s already initialized when it got raised

uneven grail
#

that saviing into the context object is done as a part of the raise logic

ornate jay
#

Afaik

uneven grail
#

so I want to grab that stuff from e

#

before its raised

#

again

#

I could always just do ... raise MyException(from_exc=e)

#

but I'm trying to dive into using the first pattern, if its even possible

ornate jay
#

Youโ€™re creating an entirely new exception instance. The from is for uninitialized exceptions

#

So you would have to call the type

#

But then you can access any data inside because itโ€™s not initialized when you use from

#

Does that make sense?

#

As in

uneven grail
#

You can do it either way, take a look at pep3134, how you create the exception is just a nuance,

#

whether you raise from the base class or from an instance of the base class, it doesn't matter

#

all from does is sets the context

#

litterally translates to my_exc.__context__ = e

ornate jay
#

I feel like this shouldnโ€™t be this difficult, but Iโ€™m struggling lol

uneven grail
#

it seems like everything in python has a method behind. Hell, I can even overwrite how an object is accessed as an attribute through descriptors, but I just can't find any docs on what to do when an exception is raised

#

it seems that all I can do is initialization logic and that's it

ornate jay
#

And you looked at all the dunder methods I assume?

uneven grail
#

yeah no magic methods extend raise functionality

#

what I was hoping was that, just for example's sake, there was a method __raise__ that is called when an object is raised. Creating an "exception" was just simply defining this method. I could, in my exception, do something like def __raise__(self): ... do some logic on __context__... super().__raise__() and call it a day

#

but alas lol

#

Like, a really simple but impossible problem would be when an exception is raised, print "Hello, World" before all the raise stuff happens

#

like you just can't do that

ornate jay
#

The wonders of meta programming

uneven grail
#

You can do it when you create the exception object itself, but not after you call raise

ornate jay
#

Um

#

What about exc?

#

Can you make it callable or?

uneven grail
#

I can try, but I don't think the object is called when its raised. Let me see what happens when I do that

#

Yeah no cookie

ornate jay
#

My brain is fried

uneven grail
#

Yeah same, I'm probably just going to go with the init arg route, but dang I'd love a real solution to this

zealous widget
#

you can subclass exception, and in the __init__ do whatever

uneven grail
#

yeah that's the issue though, I want to insert logic during the exception raise, not the initialization procedure

#

the reason is because raise ... from ... updates context during the raise procedure. During initialization, its just None

#

I just want to insert a little tidbit before the true raise procedure that will update the signature (see notebook from above) based on the type of exception we raised from

#

That's it ๐Ÿ˜ฟ

rugged sparrow
#

!e ```py
import ctypes
import sys

def get_obj_mem(obj):
return (ctypes.c_char * sys.getsizeof(obj)).from_address(id(obj))

get_obj_mem(2)[-4] = 3
print(2 + 2)

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

4
rugged sparrow
#

huh

#

that works in the interpreter

#
>>> get_obj_mem(2)[-4] = 255
>>> 2
255
>>> 2
255
>>> 1 + 1
255
>>> 1 + 1 == 255
True
>>> 
#

prob some optimizer i need to disable

zealous widget
#

you can try to set your own __getattribute__ to do something when __context__ or __cause__ is set @uneven grail

#
In [53]: class MyException(Exception):
    ...:     def __getattribute__(self, attr):
    ...:         print("Looking for:", attr)
    ...:         super().__getattribute__(attr)
    ...:

In [54]: try:
    ...:     raise ValueError
    ...: except ValueError as e:
    ...:     raise MyException from e
    ...:
Looking for: _render_traceback_
Looking for: __cause__
Looking for: __suppress_context__
Looking for: __context__
---------------------------------------------------------------------------
MyException                               Traceback (most recent call last)
<ipython-input-54-d2ae2723d1b0> in <module>
      2     raise ValueError
      3 except ValueError as e:
----> 4     raise MyException from e
      5

MyException:
stark fable
#
>>> class MyException(Exception):
...     def __getattribute__(self, attr):
...             print("Looking for:", attr)
...             super().__getattribute__(attr)
...
>>> try:
...     raise ValueError
... except ValueError as e:
...     raise MyException from e
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ValueError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
Looking for: print_file_and_line
__main__.MyException```
zealous widget
#
In [1]: class MyException(Exception):
   ...:     def __getattribute__(self, attr):
   ...:         print("Looking for:", attr)
   ...:         if attr == "__cause__":
   ...:             return ProxyProperty(self)
   ...:         return super().__getattribute__(attr)
   ...:

In [2]: class ProxyProperty:
   ...:     def __init__(self, instance):
   ...:         self.instance = instance
   ...:     def __setattr__(self, attr, value):
   ...:         print("Setting:", value)
   ...:         setattr(super(Exception, self.instance).__getattribute__("__cause__"), attr, value)
   ...:

In [3]: try:
   ...:     raise ValueError
   ...: except ValueError as e:
   ...:     raise MyException from e
   ...:
Looking for: _render_traceback_
Looking for: __cause__
Setting:
Looking for: __suppress_context__
---------------------------------------------------------------------------
MyException                               Traceback (most recent call last)
<ipython-input-3-d2ae2723d1b0> in <module>
      2     raise ValueError
      3 except ValueError as e:
----> 4     raise MyException from e
      5

MyException:
#

this is getting pretty hacky

stark fable
#

are you sure those gets and sets are actually from python and not ipython

boreal slate
#

@zealous widget how can i get this short py import sys a,b=map(int,sys.argv[1:]) s,c="",a*2+4 r=range(1,c) for i in r: for j in r: if i==j or i+j==c or a+2in[i,j]:s+=str(b);b=(b+1)%10 elif j<i or j<c-i:s+=" " s+="\n" print(s[:-1])

#

did that challenge shorter

stark fable
#

s+=str(b)[-1];b+=1 is shorter than s+=str(b);b=(b+1)%10

#

it will act differently if b is negative but if it isn't then it's the same (i think), just shorter

boreal slate
#

it is passing my test case so yes it works

stark fable
#

i think you can also replace i==j or i+j==c or a+2in[i,j] with len({i,j,a+2})<3or i+j==c

boreal slate
#

nah

proper vault
#

not i!=j!=a+2or c==i+j I think it should work, but am not 100% sure

boreal slate
#
import sys
a,b=map(int,sys.argv[1:])
s,c="",a*2+4
r=range(1,c)
for i in r:
 for j in r:
  if not i!=j!=a+2or c==i+j:s+=str(b)[-1];b+=1
  elif j<i or j<c-i:s+=" "
 s+="\n"
print(s[:-1])``` this?
#

well this doesn't work @proper vault

stark fable
#
>>> 1 != 2 != 1
True```
proper vault
#

oh, those do not get chained

stark fable
#

!= is getting chained, just it doesn't compare the first one and the third one

#

i'm not sure why mine didn't work though

#

len({i,j,a+2})<3 is true iff i, j and a+2 are not all different

#

(if they're all different it's 3, otherwise less than 3 since sets don't get duplicate elements)

#

i==j or i+j==c or a+2in[i,j] and that's basically what this is checking (i think), other than the i+j==c

boreal slate
#

well so is there any way of getting it shorter?

#
import sys
a,b=map(int,sys.argv[1:])
s,c="",a*2+4
r=range(1,c)
for i in r:
 for j in r:
  if i==j or i+j==c or a+2in[i,j]:s+=str(b)[-1];b+=1
  elif j<i or j<c-i:s+=" "
 s+="\n"
print(s[:-1])``` this is what i got till now `190` chars
stark fable
#

if someone can figure out what's wrong with my len({i,j,a+2})<3or i+j==c then i might be able to fix it and end up with something shorter than i==j or i+j==c or a+2in[i,j]

#

although actually

proper vault
#

depending on your test cases, you may be able to replace print with quit

stark fable
#

i think you can shorten i==j or i+j==c or a+2in[i,j] to not i!=j!=a+2!=i or c==i+j

boreal slate
#

yes that works

#

got it 188

#

hmmm, lets see to get shorter

stark fable
#

i'm still confused about len({i,j,a+2})<3or i+j==c not working

#

do you have an example where that gives something that's different to i==j or i+j==c or a+2in[i,j]?

boreal slate
#

me? i don't think so

stark fable
#

you're the one who has a load of test cases

#

if there's something wrong with len({i,j,a+2})<3or i+j==c you should be able to figure out what it is beesitt

proper vault
#

str(b%10) is shorter than str(b)[-1]

boreal slate
#

already did that

#
import sys
a,b=map(int,sys.argv[1:])
s,c="",a*2+4
r=range(1,c)
for i in r:
 for j in r:
  if not i!=j!=a+2!=i or c==i+j:s+=str(b)[-1];b+=1
  elif j<i or j<c-i:s+=" "
 s+="\n"
print(s[:-1])```
#

well i can't bee

proper vault
#

str(b)[-1] you didn't as far as I can tell

boreal slate
#

i think you can shorten i==j or i+j==c or a+2in[i,j] to not i!=j!=a+2!=i or c==i+j
@stark fable well i didn't understand this, why does this work tho

stark fable
#

i!=j!=a+2!=i -> i!=j and j!=a+2 and a+2!=i, ish

#

it's like how you can do a<b<c -> a<b and b<c

#

except in this case it's with != which is a bit weird

boreal slate
#

ye thanks

#

super weird

#

because there is 2 times i in that inequation
but smh it doesn't work anymore if u remove one of them

#

damn my friend got it in 172

stark fable
#

one of the is is being compared to j, and one of them is being compared to a+2

#

really j and a+2 are the weird ones since they appear once but they're used in comparisons twice

boreal slate
#

can we get that loop shorter?

#

it will reduce the indent spaces

#

well not much

proper vault
#

j<i or j<c-i
not-i>~j<i-cdoesn't save anything, but looks cooler

sudden osprey
#

Can you just replace elif j<i or j<c-i: with else:?

#

Oh no

#

I see

#

I guess you can't have the trailing spaces?

proper vault
#

for j in r:s,b=[[s+" "*(not-i>~j<i-c),b],(s+str(b%10),b+1)][not i!=j!=a+2!=i or c==i+j]I think this is equivalent to the if condition, but the hypothesis test did not finish yet

boreal slate
#
import sys
a,b=map(int,sys.argv[1:])
s,c="",a*2+4
r=range(1,c)
for i in r:
 for j in r:
  if(j!=2+a!=i!=j)&(c!=i+j):s+=" "[(j>i)&(j>c-i):]
  else:s+=str(b)[-1];b+=1
 s+="\n"
print(s[:-1])``` 187
#

for j in r:s,b=[[s+" "*(not-i>~j<i-c),b],(s+str(b%10),b+1)][not i!=j!=a+2!=i or c==i+j]I think this is equivalent to the if condition, but the hypothesis test did not finish yet
@proper vault didn't work

proper vault
#

had to do a small correction, think it should be correct now

#

<i-c),0],(s+ had to be <i-c),b],(s+

boreal slate
#

nah didn't work

#
import sys
a,b=map(int,sys.argv[1:])
s,c="",a*2+4
r=range(1,c)
for i in r:
 for j in r:s,b=[[s+" "*(not-i>~j<i-c),b],(s+str(b%10),b+1)][not i!=j!=a+2!=i or c==i+j]I
 s+="\n"
print(s[:-1])``` you meant this right @proper vault ?
proper vault
#

ye, though it seems like I missed something, it doesn't work for negative a, b

boreal slate
#
import sys
a,b=map(int,sys.argv[1:])
s,c="",a*2+4
r=range(1,c)
for i in r:
 for j in r:
  if(j!=2+a!=i!=j)&(c!=i+j):s+=" "[(j>i)&(j>c-i):]
  else:s+=str(b)[-1];b+=1
 s+="\n"
print(s[:-1])``` 187

@boreal slate well so need to get this down

proper vault
#

for j in r:s,b=[[s+" "*(j<i or j<c-i),b],(s+str(b)[-1],b+1)][not i!=j!=a+2!=i or c==i+j] works for everything it seems

night quarryBOT
#

@fair wind :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     mport ctypes
003 |           ^
004 | SyntaxError: invalid syntax
#

@fair wind :white_check_mark: Your eval job has completed with return code 0.

4
stark fable
#

!e import ctypes
import sys

def get_obj_mem(obj):
return (ctypes.c_char * sys.getsizeof(obj)).from_address(id(obj))

get_obj_mem(2)[-4] = 3
print(eval('2 + 2'))

night quarryBOT
#

@stark fable :white_check_mark: Your eval job has completed with return code 0.

6
stark fable
#

@rugged sparrow

#

the issue was that 2 + 2 would get compiled and then optimized into 4

#

and 4 doesn't care what the value of 2 is since it's just 4

rugged sparrow
#

ah so its the compiler optimizing

#

makes sense

hot barn
#

can someone help me convert python script to exe file

wanton tundra
#

@hot barn

formal sandal
#

well, "converting .py to .exe" is probably on the same level of usefulness as metametaclasses

thin trout
#

Iโ€™m not so sure about that

#

Packaging an interpreter should be pretty easy, but you need to unpack, have a wrapper script, etc...

#

And you canโ€™t have everything in one file

zealous widget
#

you take that back about metametaclasses

runic ruin
#
for a in range(106):print((' '*a).join('SCOTT'))
```Any way to shorten this more?
proper vault
#

for a in range(106):print(*'SCOTT',sep=' '*a)

runic ruin
#

@proper vault thank you! Is there any way to make it shorter than that? Whatโ€™s the shortest it can go?

runic ruin
#
for a in range(106):print(*'SCOTT',sep=' '*a)
``````py
a=0
while a!=106:print(*'SCOTT',sep=' '*a);a+=1
``````py
for a in range(106):print((' '*a).join('SCOTT'))
```These are ordered from shortest to longest.
rugged sparrow
#

@stark fable do you know if there is a pythonapi func that acts like gc.get_objects() but gets every currently allocated python object?

#

instead of the ones created after gc was inited internally

stark fable
#

hmm

#

there might be but idk

rugged sparrow
#

cause currently i have a ptr address and i want to check if its pointing to an actual py_object (which i can do if i loop thru all objs and compare id(obj)==ptr)

#

on a related note, is there any way to check that a given ptr is within python's address space

formal sandal
#

You can dereference it and add a SIGSEGV hook, maybe?

#

iTs EaFp AnD mOrE iDiOmAtIc

rugged sparrow
#

I kinda need to keep it referenced lmao

#

I'm trying to dynamically guess/assume the types of any struct

formal sandal
#

ah, Russian roulette ๐Ÿ™‚

#

If you guess incorrectly, your system language is changed to Russian

rugged sparrow
#

Yea a bit

#

So far it assumes everything is a long, but if it kinda looks like a valid ptr it follows it. But I need to get a way to check if a ptr is within pythons memory space

cursive mesa
#

what's esoteric python

next flame
#

weird stuff that you never want to use in prod

formal sandal
#

!e

from functools import wraps
from contextlib import contextmanager


this = None


@contextmanager
def with_this(new_this):
    global this
    old_this = this
    this = new_this
    try:
        yield
    finally:
        this = old_this


class Object: 
    def __init__(self, dict_=()):
        self.__dict__.update(dict_)

    def __repr__(self):
        return f"Object({self.__dict__!r})"

    @staticmethod 
    def constructor(fn): 
        @wraps(fn) 
        def _constructor(*args, **kwargs): 
            with with_this(Object()): 
                fn(*args, **kwargs) 
                return this 
        return _constructor 


##############
# USER CODE: #
##############

@Object.constructor
def User(uid: int, name: str):
    this.uid = uid
    this.name = name
    this.name_split = name.split()


fizzbuzz = User(42, "Fizz Buzz")
print(fizzbuzz)
night quarryBOT
#

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

Object({'uid': 42, 'name': 'Fizz Buzz', 'name_split': ['Fizz', 'Buzz']})
formal sandal
#

The next step would be to add methods and prototype inheritance, which would be pretty cool

#

it would also be cool to use new instead of the decorator...

thin trout
#

This injection is this is ๐Ÿ‘Œ

steep crest
#

what are y'all trying to do?

formal sandal
#

I'm procrastinating over actual work ๐Ÿ™‚

#

I'm emulating JavaScript's object orientation model

steep crest
#

I'm emulating JavaScript's object orientation model
oh yeah, of course

formal sandal
thin trout
#

This code is so un-pythonic, I love it

formal sandal
#

I'm pretty sure it follows PEP8 ๐Ÿ˜„

#

(the python code, not JS)

#

except for the comment

formal sandal
#

Pirate Encapsulation Protocol

thin trout
#

Haha

formal sandal
#

!e

exec(__import__("gzip").decompress(__import__("base64").b85decode(b'ABzY8N~~jF0{^{L!EW0y487|sxSZ_5$OjZCkYU($-MuIT#g-GTwq!`kvY^PnkCbFraonYcVhE6kBKgQikqm3C>7hO7+8fh3Q2k)6hocpPV?kFN?d2cesqLstH@(neCoN;l@0EiG_+hj}X*1I|vW27adroGBmd9`??-}emvlShX$iQ?BPeAb^38MpE*b_RzNy)BZ&?+suF5D!`5dm|cn7kHR8_##r7h3d^B8K~dPGE&{625wG)%M`!cWaF;+SRw<1n2~VHG{PN1h3?NUX={2^arbfGr&(C#9am9yu62-aomkKjMbfR4j#9^WbFwspmU{_=e%&TYbyfq#-9dRL8EHVABr+iG{I@jDLa7)Ob#o~DX8OoRl)1Iylv}Eu$>~23+d4zgyieP&<HP!AeC&))5>9lidB!q+EpY}ye5zo0#8%}&d-?F1^yR%E>{!mZk8ko0bjM@3`)ZrG7%+Zs5CaprRIqoo=Htznzibb^prMvtf`;MH!7j)VR{(1kXZ%4MR$<@D?#eT81P^3nkN?Whpf2D%YL$ak*ECaQtdP4CH=W?&OSl7ImDC*gN;L-s(b18rb)QCQJl92+)+3>I?mN5>?jgRinExR-3hyM72Msu9O)Fxq>b)OjVmWNT_|j7&fKbuQ2|<gg$?-=gk|(bHOB~c%M7D1k?UKHZSa`hjv)D7=%$mlAfbXpdo1L5In7T+5M`DJA+mY!7#knd%UD>nCx48cVa2Wu_q4K9<T&fx%d01{enyy|X}5*tSY7Yr>Ux8gY#EIP?`BaLEOT@h9Fb1O@8hg8r_UzmK1S}H_PKPxnGg2w%nALYE_8A1@7W|E)Y$mr>R#^uq>b2+7Rn~^$)}Anm=z8SR?!R5+l1nz9;Bai6W<=clN`&1-|R1KN>0ea2mk;')))

@Object.constructor
def User(uid: int, name: str):
    this.uid = uid
    this.name = name
    
    @Object.method
    def say():
        print(f"<{this.name} #{this.uid}>")
        
    @Object.getter
    def name_split():
        return this.name.split()


fizzbuzz = User(42, "Fizz Buzz")
print(fizzbuzz)
fizzbuzz.say()
print(fizzbuzz.name_split)
night quarryBOT
#

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

001 | Object(User, {'__props__': {'name_split': Object(Property, {'__props__': {}, '__proto__': <function Property at 0x7f63815d7700>, 'name': 'name_split', 'get': <function User.<locals>.name_split at 0x7f6381638040>, 'set': <function _cannot_set.<locals>._ at 0x7f63816381f0>})}, '__proto__': <function User at 0x7f63815d7820>, 'uid': 42, 'name': 'Fizz Buzz', 'say': <function User.<locals>.say at 0x7f638166cca0>})
002 | <Fizz Buzz #42>
003 | ['Fizz', 'Buzz']
formal sandal
#

yo

#

well, I guess I'm never using classes again!

wanton tundra
#

lol

formal sandal
#

I guess I can make sort-of-prototype inheritance... but it won't be as functional as JS

zealous widget
#

reminds me i make decorators sometimes to change the code of methods to include self in the args and add all the class attributes into the function's locals

#

looks similar in spirit

formal sandal
#

!e

exec(__import__("gzip").decompress(__import__("base64").b85decode(b'ABzY8T()Ch0{_)k&2HN;48H3rxSZ_3$O9B8kYU($-MuIT#gP-Owq!`kvY^PjPo!j5ah#>Q3>XTu7JojHpGc~#v8IFOplfeT>p*qAu^x_A^p26PHrmTyzEzt+nIxUiVka$Q%<q+hNBCy645#%(zm*LfmEUtTE3`b)NBO{D*P4xJ0gnt!yX6Te3esV42m*TwPH<AP-7;vD7HvzCWH}&&955!Yh1SONo%Dqkoy3SFFYpVjP)@>U@2%P#y!>jdu|>1^LQW8zptq)%)}P=F-Or1XftCJXHE;&uClBJTf^c3wz}-0RP8`PSRyYSwn;)|F2uSE$Y2`UDoNSv40le|2URJPGwdapTNhKO`T5-%ygak&11?L#lalWYF?Ofis^@eQ6Na%w4;6Ney>d<e6mj#_lHson#KR`v+V`0rA7F4_?kQ5?(AqSkFLtYp7pX|9@jIg^&l6W9|)zCL64e!WUC@P8R&?uLhXLNW$HFjy%s$<e)+UT*uek$Kfp{|GVV%$t-75o(KLH?@*u@_^&KizAd808Ncxys9Kw0xDP{O%I>newvysc&9=f^buaF%br97j&xbq~DuugjISkt@6c^x`b8-$-|;?-X6m03KON{xWSrs7oO=Dhcq)>3cGU^ESIlG{7U?3qgzvlWt7{JX2N;u+uW>7kpUWG<A~t(#$+Qr#M6p5ntBIq^;IefC6Pp14JCOjL<kMiX!dTH>**qsJg;QJYr3yF0x$Xd7=1U{`wQ}J@{!TOZj&*`1-j1{9uH&99pOBsQNc)jFZ8yRw!lLLiH)Ie2jRG`DugIA?h%o}Y&VDb@iOuq?9rcU7_s7#AUVDeDwaN36qllBw0;RN-_uh<Z&7vq1XkA%R>|hkaL?T(g~5D{?mwx~eXPbCU3BRXHZ9rTm?Hc?W~Rqu_fO^|Kn-ItJec#-k+cyT(i&f<dh%Js3?{?{!YaHdydokeT@(IElGp;_cREM9!f*B)s^>PXI0^s&')))

@Object.constructor
def NameSayer():
    @Object.method
    def say():
        return f"<{this.name} #{this.uid}>"
       
@Object.constructor
def WithNameSplit():
    @Object.getter
    def name_split():
        return this.name.split()        

@Object.inherit(NameSayer, WithNameSplit)
def User(uid: int, name: str):
    this.uid = uid
    this.name = name
       

fizzbuzz = User(42, "Fizz Buzz")
print(fizzbuzz)
print(fizzbuzz.say())
print(fizzbuzz.name_split)
night quarryBOT
#

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

001 | Object(User, {'__props__': {'name_split': Object(Property, {'__props__': {}, '__proto__': <function Property at 0x7f7569c223a0>, 'name': 'name_split', 'get': <function WithNameSplit.<locals>.name_split at 0x7f7569c22a60>, 'set': <function _cannot_set.<locals>._ at 0x7f7569c229d0>})}, '__proto__': <function User at 0x7f7569c22790>, 'say': <function NameSayer.<locals>.say at 0x7f7569c22820>, 'uid': 42, 'name': 'Fizz Buzz'})
002 | <Fizz Buzz #42>
003 | ['Fizz', 'Buzz']
formal sandal
#

now with inheritance... sort of

#

But it's kind of cheating here because fizzbuzz.say is a bound method, unlike in JS

#

so the proper way to implement this would be to do it via message passing, like

fizzbuzz("say")
fizzbuzz("say", arg1, arg2)
#

and then I'd have proper prototypal inheritance cause I'd be able to inherit objects, not constructor functions

runic ruin
#

Ew regex

fiery hare
#

what if bools were idempotent callables?

#
>>> True()
True
>>> True()()()()()
True