def isBeautifulString(inputString): cnts = [0] * 26 for c in inputString: idx = ord(c)-97 cnts[idx] += 1 return True if cnts[::-1] == sorted(cnts) else False
testcases = {"bbbaacdafe": True, "aabbb": False, "bbc": False, "bbbaa" : False, "abcdefghijklmnopqrstuvwxyzz": False, "abcdefghijklmnopqrstuvwxyz": True, "abcdefghijklmnopqrstuvwxyzqwertuiopasdfghjklxcvbnm": True, "fyudhrygiuhdfeis": False, "zaa": False, "zyy": False,} def test_solution(testcases) : for t in testcases.keys(): result = isBeautifulString(t) if testcases[t] != result: print(f"Wrong Case: {t} / expected: {testcases[t]} / your : {result}") print("Test Finished")
## Refactoring
import string def isBeautifulString(inputString): cnts = [inputString.count(c) for c in string.ascii_lowercase] # return cnts[::-1] == sorted(cnts) return cnts == sorted(cnts, reverse=True)
- python battery included 만세
ref
- count occurrence of substring
- https://docs.python.org/3/library/stdtypes.html?highlight=str%20count#str.count
- Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.
- https://docs.python.org/3/library/stdtypes.html?highlight=str%20count#str.count