Software Engineering

How to Fix String Casing in Python

The challenge

You will be given a string that may have mixed uppercase and lowercase letters and your task is to convert that string to either lowercase only or uppercase only based on:

  • make as few changes as possible.
  • if the string contains equal number of uppercase and lowercase letters, convert the string to lowercase.

For example:

solve("coDe") = "code". Lowercase characters > uppercase. Change only the "D" to lowercase.
solve("CODe") = "CODE". Uppercase characters > lowecase. Change only the "e" to uppercase.
solve("coDE") = "code". Upper == lowercase. Change all to lowercase.

The solution in Python code

Option 1:

def solve(s):
    lower = 0
    for c in list(s):
        if c.lower()==c:
            lower += 1
    return s.lower() if lower>=len(s)/2 else s.upper()

Option 2:

def solve(s):
    return (s.lower, s.upper)[sum(map(str.isupper, s)) > len(s) / 2]()

Option 3:

def solve(s):
    upper = 0
    lower = 0
    for char in s:
        if char.islower():
            lower += 1
            upper += 1
    if upper == lower or lower > upper:
        return s.lower()
        return s.upper()

Test cases to validate our solution"Basic tests")