等距图是一个没有重复字母,连续或不连续的单词.实现一个函数,该函数确定仅包含字母的字符串是否为等距图.假设空字符串是一个等轴测图.忽略字母大小写.
is_isogram("Dermatoglyphics" ) == true is_isogram("aba" ) == false is_isogram("moOse" ) == false # -- ignore letter case这是我的代码:
def is_isogram(string): string = string.lower() for char in string: if string.count(char) > 1: return False else: return True当我尝试运行测试代码Test.assert_equals(is_isogram("moOse"), False, "same chars may not be same case" )时,它失败了,但是我认为我确实将所有内容都转换为小写.有人可以帮忙吗?
解决方案尝试一下:
def is_isogram(string): string = string.lower() for char in string: if string.count(char) > 1: return False return True在您的代码中,调用is_isogram("moose")时,它将看到第一个字符('m')的计数不大于1.因此它将返回True.一旦命中return语句,它将停止执行其余字符串.因此,只有在for循环之后才应该真正编写return True,以确保该函数检查整个字符串.
但是,如果在任何时候它发现一个字符的计数大于1,那么它将简单地返回False并停止执行,因为当发现一个条件不成立的点时,便不再进行任何检查./p>
An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case.
is_isogram("Dermatoglyphics" ) == true is_isogram("aba" ) == false is_isogram("moOse" ) == false # -- ignore letter caseHere is my code:
def is_isogram(string): string = string.lower() for char in string: if string.count(char) > 1: return False else: return TrueAnd when I tried to run the test code Test.assert_equals(is_isogram("moOse"), False, "same chars may not be same case" ) It failed, but I thought I did convert everything into lowercase. Can someone help?
解决方案Try this:
def is_isogram(string): string = string.lower() for char in string: if string.count(char) > 1: return False return TrueIn your code when is_isogram("moose") is called, it will see that the first character's ('m') count is not greater than 1. So it will return True. Once it hits the return statement, it will stop the execution for the rest string. So you should really write return True only after for-loop to make sure that the function checks for the whole string.
If however, at any point, it finds a character's count to be greater than 1, then it will simply return False and stop executing because there's no point of checking any more when one point is found where condition does not hold.
更多推荐
检查python函数确定来自Codewars的等距图
发布评论