Learn how to Repair String Casing in Python


The problem

You’ll be given a string that will have combined uppercase and lowercase letters and your process is to transform that string to both lowercase solely or uppercase solely primarily based on:

  • make as few adjustments as potential.
  • if the string comprises equal variety of uppercase and lowercase letters, convert the string to lowercase.

For instance:

remedy("coDe") = "code". Lowercase characters > uppercase. Change solely the "D" to lowercase.
remedy("CODe") = "CODE". Uppercase characters > lowecase. Change solely the "e" to uppercase.
remedy("coDE") = "code". Higher == lowercase. Change all to lowercase.

The answer in Python code

Possibility 1:

def remedy(s):
    decrease = 0
    for c in listing(s):
        if c.decrease()==c:
            decrease += 1
    return s.decrease() if decrease>=len(s)/2 else s.higher()

Possibility 2:

def remedy(s):
    return (s.decrease, s.higher)[sum(map(str.isupper, s)) > len(s) / 2]()

Possibility 3:

def remedy(s):
    higher = 0
    decrease = 0
    for char in s:
        if char.islower():
            decrease += 1
            higher += 1
    if higher == decrease or decrease > higher:
        return s.decrease()
        return s.higher()

Take a look at instances to validate our resolution

take a look at.it("Primary exams")
take a look at.assert_equals(remedy("code"),"code")
take a look at.assert_equals(remedy("CODe"),"CODE")
take a look at.assert_equals(remedy("COde"),"code")
take a look at.assert_equals(remedy("Code"),"code")


Leave a Reply