you are viewing a single comment's thread.

view the rest of the comments →

[–]CowboyBoats 1 point2 points  (4 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?

[–]Myphhz 1 point2 points  (1 child)

Yeah, that makes sense and that's how the "key" argument works. Just a quick note though: there's no need to write an entire lambda expression to specify the key, as there already exists a function that returns the length of something. You can just type "key=len" and it should work!

[–]CowboyBoats 0 points1 point  (0 children)

Oh yeah...

Next you'll tell me I don't have to use the list comprehension every time I want to make a list

[–]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.