检查python函数确定来自Codewars的等距图

编程入门 行业动态 更新时间:2024-10-07 16:16:06
本文介绍了检查python函数确定来自Codewars的等距图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

等距图是一个没有重复字母,连续或不连续的单词.实现一个函数,该函数确定仅包含字母的字符串是否为等距图.假设空字符串是一个等轴测图.忽略字母大小写.

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 case

Here is my code:

def is_isogram(string): string = string.lower() for char in string: if string.count(char) > 1: return False else: return True

And 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 True

In 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的等距图

本文发布于:2023-11-30 18:43:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651108.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   python   Codewars

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!