#Checking if a word is an isogram
from collections import Counter
def count_isogram(words, index):
a=Counter(words[int(index)])
d=words[int(index)]
for (b,c) in a.items():
if c >= 2:
print(b,c)
return(d+' is not an isogram')
else:
print(b,c)
return(d+' is an isogram')
嗨,这是我上面的代码。我正在尝试制作一个非常基本的等值图检查器(等值图是一个没有任何重复字母的单词(狗,猫,鸟等)。我已经让代码大部分工作,但是当我到达我的if 语句,它检查每个单词的第一个字母以确定要使用哪个返回短语。如何让我的代码检查每个字母?例如下面的图片链接演示了该问题(我没有足够高的代表来发布图像尚未):
示例:
您可以看到第一个场景中的单词:“silly”(索引为 1)正在通过该函数运行,但因为只有 1 个 S,所以它返回该单词是等值线图,而实际上不是。当运行单词“dude”(索引为 1)时,由于第一个字母在单词中出现多次,因此运行正确的返回值,但这只是因为检查的第一个字母是重复的字母。
我尝试运行 c.all()
、c.any()
和其他一些运算符,但它不起作用,因为 c 是整数只有 1 个值。
我可以更改/添加什么以使代码在运行返回之前检查所有可能的字母?
最佳答案
解决方案
问题的解决方案是在完成每个字母的循环后返回程序的最终结果。
对于每个字母,检查其计数是否大于或等于 2
。如果是,则立即返回并显示适当的消息(返回单词 + '不是等值线'
)。但是,如果到达循环末尾,您就知道该单词确实是一个等值线图,因此您可以返回另一条消息(word + ' is an isogram'
)
from collections import Counter
def is_isogram(words, index):
el = words[index]
letter_occurences = Counter(el)
for word, count in letter_occurences.items():
print(word, count)
if count >= 2:
return word + ' is not an isogram'
return word + ' is an isogram'
算法改进
因为我们知道等值线图是
any word that has no repeating letters
我们可以使用set
从字符串中删除任何可能的重复字母。然后我们可以将集合的长度与字符串的原始长度进行比较。如果长度相等,则没有删除任何字母,并且该单词是等位图。如果它们不相等,我们就知道该单词不是等值线图:
def is_isogram(words, index):
word = words[index]
if len(set(word)) == len(word):
return word + ' is an isogram'
return word + ' is not an isogram'
这比原始方法快得多(准确地说大约快九倍):
------------------------------------
| Original method | 6.47415304184 |
------------------------------------
| Above method | 0.669512987137 |
------------------------------------
关于python - 我怎样才能让代码检查所有情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46554702/