Почему моя собственная функция mymax (замена встроенной в Python max) не может правильно сравнивать строки?Python

Программы на Python
Гость
Почему моя собственная функция mymax (замена встроенной в Python max) не может правильно сравнивать строки?

Сообщение Гость »


I am writing mymax() function as a replacement of python in-built max function. mymax will be universal function - can take any iterable (list, tuple, string) and returns the largest element in the iterable. While this works totally fine for list and tuple, it is inconsistent while returning the larger string.

-- The following function returns 'lives in Jungles' as larger element which is incorrect.

def mymax(seq): #for loop to initiate var as emtpy string or as 0 depending on user input. for elemType in seq: if isinstance(elemType, str): var = '' break else: var = 0 # for loop to find the largest element in the sequence. for element in seq: if element > var: var = element return var mymax(('Lions', 'live in Jungles', 'and under the starry sky')) -- this return 'live in Jungles' although 3rd element is larger. mymax(('Lions', 'live in Jungles', 'and under the starry sky', 'within this galaxy where earth revolves around the sun.')) -- rightly returns the 4th element What could be causing this inconsistency?

I tried to different arguments to mymax function but it still seems to be behaving inconsistently with list of strings.


Источник: https://stackoverflow.com/questions/780 ... compare-st

Вернуться в «Python»