The required is a function that takes a string and returns the most repeated character in it without considering the punctuations, white spaces and numbers, it also treats "A" == "a"
, if the string has equally repeated characters it returns the letter which comes first in the Latin alphabet.
Here is the function given the examples, I've commented it for more clarification
def checkio(text):
# any char
result = "a"
# iterating through small chars
for i in text.lower():
# iterating through lowercase letters only and not considering punctuation, white spaces and letters
if i in string.ascii_lowercase:
# If i is repeated more than the result
if text.count(i) > text.count(result):
result = i
# in case the letters are equal in repeated the same time
elif text.count(i) == text.count(result):
# returning according to the letter which comes first in the
Latin alphabet
if string.ascii_lowercase.find(i) < string.ascii_lowercase.find(result):
result = i
return result
print(checkio("Hello World!"))
print(checkio("How do you do?"))
print(checkio("One"))
print(checkio("Oops!"))
print(checkio("abe"))
print(checkio("a" * 9000 + "b" * 1000))
# Here is the problem
print(checkio("AAaooo!!!!")) # returns o
print(checkio("aaaooo!!!!")) # returns a --> the right solution!
答案 0 :(得分:1)
您拨打text.count
的电话不会先致电lower()
。在函数的顶部,您应该调用text = text.lower()
。然后,text.count
调用将对迭代器执行的相同的规范化小写字符起作用。
答案 1 :(得分:0)
何时执行text.count(i)for“AAaooo !!!!”,它会执行以下操作:A:count = 2 a:count = 1 o:count = 3 ....依此类推。
因此,在计算字符之前,您需要将整个字符串转换为小写字母。这将解决您的问题。
def checkio(text):
# any char
result = "a"
# iterating through small chars
for i in text.lower():
# iterating through lowercase letters only and not considering punctuation, white spaces and letters
if i in string.ascii_lowercase:
# If i is repeated more than the result
if text.lower().count(i) > text.lower().count(result):
result = i
# in case the letters are equal in repeated the same time
elif text.lower().count(i) == text.lower().count(result):
# returning according to the letter which comes first in the Latin alphabet
if string.ascii_lowercase.find(i) < string.ascii_lowercase.find(result):
result = i
return result
print(checkio("AAaooo!!!!")) # returns a
print(checkio("aaaooo!!!!")) # returns a