I'm currently facing the problem of not being able to print the last longest string. Strings example:
banica
pizza
kiufte
The first and the third are same length, but I want the last longest string.
def longest(list1):
longest_list = max(len(elem) for elem in list1)
return longest_list
somelist=[]
while True:
s = input()
if s == "END":
break
somelist.append(s)
longest_string = max(somelist, key=len)
print(longest_string)
CodePudding user response:
I don`t know, what exactly you are trying to achieve, but as
longest_string = max(somelist, key=len)
gives you the first element with max length, you can just reverse the list, and get the last:
longest_string = max(somelist[::-1], key=len)
CodePudding user response:
This will work as you want :
def longest(list1):
longest_list = max(len(elem) for elem in list1)
return longest_list
somelist=[]
while True:
s = input()
if s == "END":
break
somelist.append(s)
longest_string = max(somelist[::-1], key=len)
print(longest_string)
CodePudding user response:
To employ your longest()
function:
longest_length = longest(somelist)
longest_string = [s for s in somelist if len(s) == longest_length][-1]
(Index [-1]
extracts the last element.)