简体   繁体   English

python程序检查两个词是否是字谜

[英]python Program to check whether two words are anagrams

I have written a small program to check whether two words are anagrams. 我写了一个小程序来检查两个词是否是字谜。 If two words are anagrams it should return "true" otherwise it should return "False", but I am not getting the correct output. 如果两个词是字谜,则应返回“ true”,否则应返回“ False”,但我没有得到正确的输出。 Kindly, tell me what is the mistake in the below program. 请告诉我以下程序中的错误是什么。

 def anagram(s1,s2):
     for x in s1:
         if (x in s2) and (s2.count(x)==s1.count(x)):
             pass
         return(True)
     else:
         return(False)

You are iterating over a word and then not doing anything (with pass , the empty statement). 您正在遍历一个单词,然后什么也不做(使用pass ,空语句)。 Then you return True unconditionally, leaving no chance to return False . 然后,您无条件返回True ,没有机会返回False

Instead, you can simply sort the two words and then see if they end up the same: 相反,您可以简单地对两个单词进行排序,然后查看它们是否最终相同:

def anagram(s1, s2):
    return sorted(s1) == sorted(s2)

Please format this in a more readable way. 请以更具可读性的方式设置此格式。 However, it looks like you are calling return True inside the loop, meaning that if any character occurs the same amount of times in each string, your function will return True 但是,看起来您正在循环内调用return True ,这意味着如果任何字符在每个字符串中出现的次数相同,则您的函数将return True

Try this: 尝试这个:

def anagram(s1,s2):
    for x in s1:
        if ( x in s2 ) and (s2.count(x) == s1.count(x) ):
            pass
        else:
            return False
    for x in s2:
        if ( x in s1 ) and (s1.count(x) == s2.count(x) ):
            pass
        else:
            return False
    return True

You may try this: 您可以尝试以下方法:

>>> def anagram(str1,str2):
    s1=str1.lower()
    s2=str2.lower()
    a=len(s1)
    b=len(s2)
    if a==b:
        for c in s1:
            if c in s2:
                for s in s2:
                    if s in s1:
                        return True
            else:
                return False
    else:
        return False

You were really close. 你真的很亲近 Your indentation was bad but that is probably due to the text formatting here in SO. 您的缩进不好,但这可能是由于SO中的文本格式。

The mistake in your code was that you were returning True too soon. 代码中的错误是您过早返回True。 What you have to do is to go through all letters and check for existance and count. 您要做的是仔细阅读所有字母并检查是否存在和计数。 Below you can find a corrected and somewhat optimised version of what you were trying to do. 在下面,您可以找到自己想做的经过修正且经过某种程度优化的版本。

def anagram(s1, s2):
    if set(s1) == set(s2) and all(s2.count(x) == s1.count(x) for x in set(s1)):
        return True
    return False

But then again @Tigerhawk's solution is way better. 但是@Tigerhawk的解决方案还是更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM