In this chapter we are going to solve the above problem with a Python method. Given a string which consists of words and numbers, we are going to extract out the numbers that are within those words from that string, then compare and return the largest number within the given string.

These are the steps we need to do.

  1. Turn the string into a list of words.
  2. Create a string which only consists of digits separated by empty space that replaces the words within the digits.
  3. Create a new list only consists of digits then returns the maximum digit.
def solve(s):
    
    s_list = list(s)
    str = ''
    for e in s_list:
        if e.isdigit():
            str += e
        else:
            str += ' '
    n_list = str.split(' ')
    e_list = []
    for x in n_list:
        if x.isdigit(): 
            e_list.append(int(x))
    return max(e_list)

The max method will return the maximum digit within a list.

Please follow and like us:
error0

4 Comments

  1. Cool idea!
    Here’s a slightly shorter version. (I changed str to st because str() is a function and got a different color in my editor).

    def solve(s):

    s_list = list(s)
    st = ”
    for e in s_list:
    if e.isdigit():
    st += e
    else:
    st += ‘ ‘
    n_list = st.split()
    return max([int(x) for x in n_list if x.isdigit()])

  2. PS, here’s an even shorter version (the comment field doesn’t seem to keep the indents…)
    def solve(s):

    st = ”
    for e in s:
    if e.isdigit():
    st += e
    else:
    st += ‘ ‘
    n_list = st.split()
    return max([int(x) for x in n_list if x.isdigit()])

  3. A two line version: (should be a one liner with lambda)
    “`
    def solve(s):
    return max(int(num) for num in ”.join([c if c.isdigit() else ' ' for c in s]).split())
    “`

  4. Not tested so might need some tweaking but why not just something like:

    max([int(i) for i in re.find_iter(r’\d+’, s)])

Leave a Reply

Your email address will not be published. Required fields are marked *