Home Software Engineering Learn how to Repair String Casing in Python

Learn how to Repair String Casing in Python

0
Learn how to Repair String Casing in Python

[ad_1]

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 based mostly 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:

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

The answer in Python code

Choice 1:

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

Choice 2:

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

Choice 3:

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

Check circumstances to validate our answer

take a look at.it("Fundamental exams")
take a look at.assert_equals(clear up("code"),"code")
take a look at.assert_equals(clear up("CODe"),"CODE")
take a look at.assert_equals(clear up("COde"),"code")
take a look at.assert_equals(clear up("Code"),"code")

[ad_2]

LEAVE A REPLY

Please enter your comment!
Please enter your name here