Reputation: 25
Hey beautiful community :)
I have this code:
list1 = ['aaaa', 'bbb', 'c', 'ddddd', '', 'ff']
def getLongestStringIndex(list_of_strings):
longest_string = ""
for string in list_of_strings:
if len(string) > len(longest_string):
longest_string = string
return longest_string
print(getLongestStringIndex(list1))
I had a task to do it without max function so I dont need to change a lot of the code, but instead of printing the longest string, I need to print the longest string INDEX, so it will return 3
What I need to do to make it done ?
EDIT: I've been asked to do it without .index method and enumerate ..
Thanks in advance :)
Upvotes: 1
Views: 117
Reputation: 605
I solved that in a short and pythonic way!
>>> strings = ['aaaa', 'bbb', 'c', 'ddddd', '', 'ff']
>>> strings.index(max(strings, key=len))
>>> 3
Upvotes: 3
Reputation: 637
One way to do this without the use of max()
, list.index()
, or enumerate()
is by iterating over the entire list and storing the index of the longest string found.
However, we can bypass the entire list iteration by directly finding the longest string and only needing to obtain its index. Assuming of course there are no other restrictions on what to do if more than 1 string is the longest string. Here is an example of how this can be accomplished:
list1 = ['aaaa', 'bbb', 'c', 'ddddd', '', 'ff']
def getLongestStringIndex(list_of_strings):
longest_string = sorted(list_of_strings, key=len, reverse=True)[0]
idx: int
for k in range(len(list_of_strings)):
if list_of_strings[k] == longest_string:
idx = k
break
return idx
Note: This is especially helpful if the longest string is closer to the beginning of the list since the iteration will be much faster, but if the longest string is near the end or at the end of the list then this method is potentially slower than the initial solution I proposed.
A much more Pythonic way to do this is with this one-liner which keeps the list indices "mapped" to the sorted list:
def getLongestStringIndex(list_of_strings):
return sorted(range(len(list_of_strings)), key=lambda k: len(list_of_strings[k]), reverse=True)[0]
Upvotes: 0
Reputation: 33335
As you're iterating over the string list, keep track of the current position in the list (enumerate
is a handy way to do that). When you find a longer string, remember that position.
def getLongestStringIndex(list_of_strings):
longest_length = 0
longest_position = 0
for position,string in enumerate(list_of_strings):
if len(string) > longest_length:
longest_length = len(string)
longest_position = position
return longest_position
Upvotes: 2
Reputation: 25
In my opinion, you just need a tiny modification.
list1 = ['aaaa', 'bbb', 'c', 'ddddd', '', 'ff']
def getLongestStringIndex(list_of_strings):
longest_string = ""
for string in list_of_strings:
if len(string) > len(longest_string):
longest_string = string
return list1.index(longest_string)
print(getLongestStringIndex(list1))
Upvotes: 0