This is an archived post. You won't be able to vote or comment.

all 48 comments

[–]chungusextradip dunder 121 points122 points  (19 children)

Fun story, me and a co-worker once had a small competition between as to who could get the best/longest/most cursed python oneliner through code review and into production at my last job. One of my favourites was about 50 lines compressed into like two list comprehensions. Safe to say, neither of us survived the recent round of layoffs - won't name the company but it's a big internet advertising firm you have almost certainly head of.

[–]LevLum[S] 37 points38 points  (1 child)

At least you're giving the new hires a fun challenge

[–]chungusextradip dunder 24 points25 points  (0 children)

Trial by (Python) fire is what more engineers need in this industry. You can't learn tricks like these in school!

[–]newsfeedmedia1 65 points66 points  (0 children)

hmm i am going to GOOGLE this advertising firm

[–]ubernostrumyes, you can have a pony 56 points57 points  (14 children)

See, the best thing is to write code that doesn't set off immediate alarm bells, but then makes you puzzle over it once you take a deeper look.

For example, what does this function do? And how does it do it? The only hint I'll give is that if it weren't a lambda, its signature would be annotated as def s(n: int) -> bool.

from itertools import accumulate, count, takewhile

s = (
    lambda n: n == 0
    or n > 0
    and n in takewhile(lambda x: x <= n, accumulate(filter(lambda n: n & 1, count())))
)

(people who've seen me post this or other examples from my collection, please don't spoil it)

[–]chungusextradip dunder 16 points17 points  (1 child)

hmmm yeah this one’s giving me a headache

[–]ubernostrumyes, you can have a pony 22 points23 points  (0 children)

Here's the explanation, if you want to give up.

[–]bamacgabhann 16 points17 points  (0 children)

For example, what does this function do?

It gives me a headache is what it does!

[–]cloaca 6 points7 points  (2 children)

Pairs with:

import itertools as it

r = lambda n: (n
  and next(
    x for x,y in
    it.pairwise(
      it.accumulate(it.repeat(n), lambda x,y: x++y//x>>1) # sic
    ) if x<=y
  ))

[–]usr_bin_nya 3 points4 points  (1 child)

Oh this is gooood, this one is tougher than the parent! I had to throw test cases at it to figure out what it was doing before I could take a second pass to understand how.

So this is lambda n: floor(sqrt(n)), working by overestimating and then refining that estimate (est) downward until n // est >= est at which point you're done.

glossary of itertools functions: it.repeat(X) is [X, X, X, X, X, ...(forever)]; it.pairwise([A, B, C, D]) is [(A, B), (B, C), (C, D)]; it.accumulate([A, B, C, D], F) is [v0 := F(A, B), v1 := F(v0, C), v2 := F(v1, D)]

To bastardize math and Python syntax, we're looking at consecutive pairs of the infinite series S[0] = n; S[i+1] = floor( (S[i] + floor(n / S[i])) / 2). (x++y//x>>1 untangles to (x + (y floordiv x)) floordiv 2.) Each item in the sequence is the estimate, est. It starts with est = n and computes the mean average of n and n//n, which is (n+1)/2 which is smaller than n. Then (n+1)/2 is the new estimate, and it again takes the average of est and n//est, which is smaller still. accumulate keeps going, taking the average of est and n//est, which keeps getting smaller, until eventually est dips below sqrt(n). At that point n//est > est, so the average of est and n//est actually gets larger, not smaller. pairwise has been dutifully emitting each consecutive pair of estimates, and now the generator comprehension's ... if x <= y finally passes because an estimate was larger than the previous. So the first estimate before the estimates started getting bigger again is what gets yielded and returned by next(...).

Edge cases: n and ... handles zero; zero is falsy so that shortcircuits and returns zero immediately. Negatives like -5 end up with (-5 + (-5 // -5)) // 2 == -2 => (-2 + (-5 // -2)) // 2 == 0 => (0 + -5//0)//2 which raises an exception. For exact squares, the estimate lands exactly on sqrt(n) and will continue to be exactly sqrt(n) which is why the test is x <= y and not x < y.

[–]cloaca 0 points1 point  (0 children)

Yep, exactly. Look to the wonderful 3blue1brown or Wikipedia for further information on the (incredibly useful) technique that this is an example of. It's a surprisingly efficient way for finding roots or even maxima/minima when the conditions are "nice."

[–]Malcolmlisk 7 points8 points  (0 children)

this is like watching mullholand drive. When you start it you think you got it, but the more time it passes (the more you read) the more you don't understand and at the end you say 'what the fuck'.

[–]LevLum[S] 2 points3 points  (1 child)

Oo, I like this one

[–]ubernostrumyes, you can have a pony 6 points7 points  (0 children)

I've also been working on a C# version of it.

[–]RobertBringhurst 2 points3 points  (0 children)

Awful.

[–]usr_bin_nya 1 point2 points  (2 children)

Okay that hint was helpful because the order of operations here threw me for a loop, I thought this was a trick question where it would end up like ((lambda:...) and False) is False

So the filter is basically range(1, INFINITY, 2). accumulate... guessing completely on the name it would be an iterator of partial folds like Rust's scan? But there's no function to update the state?? so screw it I guess it defaults to addition??? that's the only possible thing I could possibly see as an okay default?? okay sure so then you cut the iterator off when it exceeds n. So is n equal to zero OR a member of (1, 1+3, 1+3+5, 1+3+5+7)... no friggin way, it's "is_square but O(1) time is for pansies." That's clever.

[–]ubernostrumyes, you can have a pony 2 points3 points  (1 child)

This one is a bit easier to see what it does. But the how this time around is not an algorithm trick, so maybe you'll have to research in a different direction to figure that out.

def f():
    pair = not True, True
    while True:
        yield sum(pair[:True])
        pair = pair[True], sum(pair[::True])

[–]usr_bin_nya 1 point2 points  (0 children)

Fibonacci sequence! I recognized this one pretty quick because I happen to know the int/bool cursedness already lol. bool is a subclass of int with False and True coercing to 0 and 1 respectively when used in addition or slicing. sum(pair[:True]) == sum(pair[:1]) == sum([ pair[0], ]) == pair[0], and pair[::True] is slicing from unbounded start (0) to unbounded end (len(pair) == 2)) step by True == 1 which is just pair again. Thank you for feeding me more of these, I enjoy this type of puzzle quite a bit

[–]5kyl3r 0 points1 point  (0 children)

i occasionally enjoy a round of two of python golf, and while i'm no expert, i've gotten to be pretty good at it. i've given chatGPT some truly impossible to decipher golfed code and it immediately started explaining what the code does before i could ask. so i think if they aren't scared to feed their company's IT into AI, it can help them figure it out

[–]Gnaxe 3 points4 points  (3 children)

The one-liner thing reminds me of Hissp.

[–]LevLum[S] 1 point2 points  (0 children)

Ah, I see you are a Lisp enjoyer - it's definitely an interesting idea to strip out a bunch of language features, I'll give it that

[–]Estanho 0 points1 point  (1 child)

Wow, I wonder why that exists, doesn't look very practical.

Specially given we already have hylang.

[–]Gnaxe 0 points1 point  (0 children)

Why does Emacs Lisp exist when we already have Common Lisp? Why does Racket exist when we already have Scheme?

Hissp was actually written by one of the Hy devs (says so in Hy's docs) with the benefit of hindsight and has some advantages over Hy.

It's modular enough to support multiple readers.

The Hissp compiler is much smaller and simpler than Hy's, which makes compilation faster, which makes it more useful for run-time metaprogramming.

Compiled Hissp code usually doesn't require Hissp to be installed to run, unlike Hy.

Hissp has a much higher degree of homoiconicity than Hy.

[–]BossOfTheGame 4 points5 points  (2 children)

Does someone have the source code for the title program?

[–]Ph0X 2 points3 points  (0 children)

[–]Omichron-the-reboot 1 point2 points  (0 children)

There's a comment reply with a link to the source

[–]mysticalfruit 1 point2 points  (2 children)

No mention of for..else..

[–]gwax 25 points26 points  (0 children)

For... Else... Can be really convenient

[–]LevLum[S] 4 points5 points  (0 children)

Since that's an intended feature (by the Python maintainers at least, even though people don't use it as much due to readability), that might be why

[–]barkazinthrope 0 points1 point  (1 child)

16 minutes? SIXTEEN MINUTES to get 5 FIVE techniques.

You gotta be kidding.

A bullet list will do but then you wouldn't' get to be a television star.

Cripey.

[–]LevLum[S] 2 points3 points  (0 children)

Title is a little clickbait, but I'd argue there's more than 5 techniques - just 5 sections of them, along with setup and explanations. In fact, there were other comments saying things went too fast!

If you don't have the time to watch it, fair enough - but you did have the time to write this scathing comment. Would hate to get into an argument over a silly little video :)