Wednesday, August 28, 2019

IslandT: Find the maximum value within a string with Python

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.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...