简体   繁体   中英

python, printing longest length of string in a list

My question is to write a function which returns the longest string and ignores any non-strings, and if there are no strings in the input list, then it should return None.

my answer:

def longest_string(x):
    for i in max(x, key=len):
        if not type(i)==str:
            continue
        if 
    return max
longest_string(['cat', 'dog', 'horse'])

I'm a beginner so I have no idea where to start. Apologies if this is quite simple.

This is how i would do it:

def longest_string(x):
    Strings = [i for i in x if isinstance(i, str)]
    return(max(Strings, key=len)) if Strings else None

Based on your code:

def longest_string(x):
    l = 0
    r = None
    for s in x:
        if isinstance(s, str) and len(s) > l:
            l = len(s)
            r = s
    return r


print(longest_string([None, 'cat', 1, 'dog', 'horse']))
# horse

def longest_string(items):
    strings = (s for s in items if isinstance(s, str))
    longest = max(strings, key=len) if strings else None
    return longest


print(longest_string(['cat', 'dog', 'horse']))
def longest_string(items):
   try:
     return max([x for x in items if isinstance(x, str)], key=len)
   except ValueError:
     return None

You're on a good way, you could iterate the list and check each item is the longest:

def longest_string(x)

    # handle case of 0 strings
    if len(x) == 0:
        return None

    current_longest = ""
    # Iterate the strings
    for i in x: 
        # Handle nonestring
        if type(i) != str:
            continue
   
        # if the current string is longer than the longest, replace the string.
        if len(i) > len(current_longest):
            current_longest = i

    # This condition handles multiple elements where none are strings and should return None.
    if len(current_longest) > 0:
        return current_longest 
    else:
        return None

Your syntax is wrong (second-to-last line: if with no condition) and you are returning max which you did not define manually. In actuality, max is a built-in Python function which you called a few lines above.

In addition, you are not looping through all strings, you are looping through the longest string. Your code should instead be

def longest_string(l):
 strings = [item for item in l if type(item) == str]
 if len(strings):
  return max(strings, key=len)
 return None

Since you are a beginner, I recommend you to start using python's built-in methods to sort and manage lists. Is the best when it comes to logic and leaves less room for bugs.

def longest_string(x):
    x = filter(lambda obj: isinstance(obj, str), x)
    longest = max(list(x), key=lambda obj: len(obj), default=None)
    return longest

Nonetheless, you were in a good way. Just avoid using python´s keywords for variable names (such as max , type , list , etc.)

EDIT: I see a lot of answers using one-liner conditionals, list comprehension, etc. I think those are fantastic solutions, but for the level of programming the OP is at, my answer attempts to document each step of the process and be as readable as possible.

First of all, I would highly suggest defining the type of the x argument in your function.

For example; since I see you are passing a list, you can define the type like so:

def longest_string(x: list):
    ....

This not only makes it more readable for potential collaborators but helps enormously when creating docstrings and/or combined with using an IDE that shows type hints when writing functions.

Next, I highly suggest you break down your "specs" into some pseudocode, which is enormously helpful for taking things one step at a time:

returns the longest string
ignores any non-strings
if there are no strings in the input list, then it should return None.

So to elaborate on those "specifications" further, we can write:

  1. Return the longest string from a list.
  2. Ignore any element from the input arg x that is not of type str
  3. if no string is present in the list, return None

From here we can proceed to writing the function.

def longest_string(x: list):
    # Immediately verify the input is the expected type. if not, return None (or raise Exception)
    if type(x) != list:
        return None  # input should always be a list

    # create an empty list to add all strings to
    str_list = []
    # Loop through list
    for element in x:
        # check type. if not string, continue
        if type(element) != str:
            pass
        
        # at this point in our loop the element has passed our type check, and is a string. 
        # add the element to our str_list
        str_list.append(element)

    # we should now have a list of strings
    # however we should handle an edge case where a list is passed to the function that contains no strings at all, which would mean we now have an empty str_list. let's check that
    if not str_list:  # an empty list evaluates to False. if not str_list is basically saying "if str_list is empty"
        return None

    # if the program has not hit one of the return statements yet, we should now have a list of strings (or at least 1 string). you can check with a simple print statement (eg. print(str_list), print(len(str_list)) )
    
    # now we can check for the longest string
    # we can use the max() function for this operation
    longest_string = max(str_list, key=len)

    # return the longest string!
    return longest_string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM