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
else:
upper += 1
if upper == lower or lower > upper:
return s.lower()
else:
return s.upper()
Test cases to validate our solution
test.it("Basic tests")
test.assert_equals(solve("code"),"code")
test.assert_equals(solve("CODe"),"CODE")
test.assert_equals(solve("COde"),"code")
test.assert_equals(solve("Code"),"code")