![]() ![]() ![]() ![]() Let’s have a look at some code that implements this idea: This gives us complete flexibility! Instead of just being able to choose a specific list index for the comparison, like index 1 or 2, we can tell our function to select something else entirely – for example, the length of the item’s name. We can write different kinds of key funcs and pass them to my_max as necessary. How can we make max() more flexible?īecause Python allows us to treat functions as data we can extract the code selecting the comparison key into its own function. Wouldn’t it be great if we could reuse the bulk of the code in our implementation of my_max? Some parts of it will always work the same, for example checking if an empty sequence was passed to the function. Maybe sometimes it’ll be the third or fourth item, or a different kind of lookup is necessary all together. Perhaps the index (or key) we’re interested in won’t always be the second item. Now imagine we needed to find the maximum of different kinds of lists. Let’s imagine we had an updated version of my_max called my_max_by_weight that uses the second element of each inner list for comparison: How do we tell max to compare the second item of each inner list? That’s why it returns cherry as the maximum element if we just call max(nested_list). In our example, Python’s max looks at the first item in each inner list (the string cherry, apple, or anaconda) and compares it with the current maximum element. We need to tell max to compare the items differently. How can we change the comparison behavior? Now that we understand why we get an unexpected result we can think about ways to fix our code. When max needs to compare two sequences to find the “larger” element then Python’s default comparison behavior might not be what we want 3. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison if they are equal, the next two items are compared, and so on, until either sequence is exhausted. Sequence objects may be compared to other objects with the same sequence type. Let’s look at the Python docs to learn how Python compares sequences: However, if sequence contains other sequences then things get a little more complex. This condition works nicely if sequence only contains primitive types like int or float because comparing those is straightforward (in the sense that it’ll give an answer that we intuitively expect like 3 > 2). The interesting bit of behavior here can be found in the condition that selects a new maximum: if item > maximum. Def my_max ( sequence ): """Return the maximum element of a sequence""" if not sequence : raise ValueError ( 'empty sequence' ) maximum = sequence for item in sequence : if item > maximum : maximum = item return maximum ![]()
0 Comments
Leave a Reply. |