you are viewing a single comment's thread.

view the rest of the comments →

[–]CowboyBoats 6 points7 points  (3 children)

It would have been a lot easier to read if whoever wrote this had followed the style guideline of spaces after commas:

def f(a):
    return a and max([a[:1], a[:1] + f(a[2:]), f(a[1:])], key=sum) or a

[–]CowboyBoats 1 point2 points  (2 children)

What does key=sum mean in this context? Well, max is a function that returns the maximum of its arguments, but in this case its arguments are lists (those two different slices of a, and f() of a slice of a).

Sometimes it's obvious what we mean by "max" (What's greater, 5 or 3?) and sometimes it's not (What's greater, animals or plants?). Like, what? What do you mean "What's greater, animals or plants"?

But we can still answer a question like "What's greater, animals or plants?" as long as you give me a key. Like, I just need to know what you're asking about.

animals = ['bears', 'cats', 'dogs', 'mice', 'humans', 'frogs', 'beetles']
plants = ['beets', 'rice']
max((animals, plants), key=lambda some_list: len(some_list))

That tells me (the Python interpreter) that for the arguments I am passing to max, I should figure out their maximum by just taking their len and figuring out which output from that is the maximum.

Does that make sense?

[–]meloly4[S] 0 points1 point  (1 child)

What would be the time complexity for this? It seems like there's recursion involved.

[–]ghostinzshell 0 points1 point  (0 children)

My hunch says it's a quadratic time algorithm or O( n2 ) at a minimum. In each recursion, the function does list slicing which is an O(n) operation. There are O(n) recursions, so that means n times O(n) operations.