Exercise 71 **

Write a Python algorithm that takes a string 's' as input and which determines the minimum digit within the string s. Example: if s = "Python3.7 is more power than Python2.7" , the algorithm must returns 2. We assume that the string s does not contain any negative number.

Solution

First method:

  • To solve this exercise we can do it as follow:
  • We use the for loop to iterates over every character in the string s.
  • We use the isdigit() method to checks if the character is a digit.
  • If the character is a digit, we appended it to the digits list as an integer.
  • Finally, we use the min method to find the smallest integer in the digits list. In this case, it's 2.
def min_digit(s):
    digits = []
    for c in s:
        if c.isdigit():
            digits.append(int(c))
    return min(digits)

s = "Python3.7 is more power than Python2.7"
print(min_digit(s)) # Output: 2





Second method: by using the regular expression

import re

def min_digit(s):
    The re.findall('\d', s) method returns a list of all digits in the string s.
    digits = re.findall('\d', s)

    # Now we can use the min method() to find the smallest digit in the list
    return min(digits)

s = "Python3.7 is more power than Python2.7"
print(min_digit(s)) # Output: 2

 

Younes Derfoufi
my-courses.net

One thought on “Solution Exercise 71: python program to find the minimum digits within a given string”

Leave a Reply