Skip to content Skip to sidebar Skip to footer

Need Explanation For Max And Min Building Function

I don't understand the built-in functions max and min in python 2.7 max('sehir') min('sehir') max gives the letter 's' and min gives the letter 'e'

Solution 1:

max and min take as parameter (given you only give it one unnamed parameter) an iterable, and returns the maximum / minimum item.

A string is an iterable: if you iterate over a string, you obtain the 1-char strings that are the characters of the string.

Then max and min iterate over that iterable and returns the maximum or minimum item. For a string the lexicographical order is defined. So 'a' < 'b', and 'ab' > 'aa'. So it is compared lexicographically, and the individual characters are compared by ASCII code (Unicode code in ). Since all characters have are one-caracter strings. We only have to take the ASCII code into account here. You can inspect the ASCII table here [wiki].

So max("sehir") will return 's', since max(['s', 'e', 'h', 'i', 'r']) == 's': the maximum character in the iterable. For min('sehir') == 'e', since min(['s', 'e', 'h', 'i', 'r']) == 'e' because it is the "smallest" character in the string.

Post a Comment for "Need Explanation For Max And Min Building Function"