函数返回给定的相同答案

问题描述:

所需的是一个函数,它接受一个字符串并返回其中最重复的字符,而不考虑标点符号,空格和数字,如果该字符串具有相同的重复次数,它也会处理"A" == "a"字符会返回拉丁字母中第一个字母。函数返回给定的相同答案

这里给出的例子中的功能,我评论它更多的澄清

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! 
+1

你只是循环使用小写字符串,对于'.count()'你仍然使用原始字符串。 –

+4

在你的代码中首次使用'for'之后,你是否有一个压痕问题? – Fabien

+0

缩进问题只是因为我在这里写错了,但在编辑器中没有问题 –

何时为“AAaooo !!!!”执行text.count(i),它执行以下操作: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 
+0

奇怪!那么如果我必须再次调用.lower(),那么从头开始迭代小写的好处是什么呢?它们已经是小写了! –

+0

您致电text.lower()不会更新'文本'。为了只能调用lower()方法一次,你应该将结果保存到其他一些变量,如'new_text = text.lower()'。然后,您可以在new_text上执行所有操作,而无需一次又一次调用lower()方法。 –

您对text.count通话不叫lower()第一。在函数的顶部,您应该调用text = text.lower()。然后你的text.count调用将使用你的迭代器所使用的相同的规格化小写字符。

+0

谢谢,这很有帮助。 –