简体   繁体   English

无法弄清楚为什么我的函数返回带有字谜的True

[英]Can't figure out well why my function is returning True with anagrams

This is my function (says if 2 compared words are anagrams or not): 这是我的功能(说两个比较单词是否是字谜):

def are_anagrams(word1, word2):
    word1list = list(word1)
    word2list = list(word2)
    anagramfalse = False
    anagramtrue = True
    if (word1 == word2):
        return anagramfalse
    if (word1list.sort()) == (word2list.sort()):
        return anagramtrue
    else:
        return anagramfalse

So this function is returning 所以这个功能正在返回

are_anagrams("lopped", "poodle")

as True , for some reason. 由于某种原因,它为True Can't figure out why. 不知道为什么。 It should be compared the sorted list of letters for each word and returning a False . 应该比较每个单词的字母排序列表并返回False

Solution? 解? Mainly just want to know what's wrong. 主要只是想知道怎么了。

sort does not do what you think. sort不符合您的想法。 Observe: 观察:

>>> x = list('lopped')
>>> print(x.sort())
None

Since None == None is always True, the function always returns True. 由于None == None始终为True,因此该函数始终返回True。

Further, the code can be simplified: 此外,可以简化代码:

def are_anagrams(word1, word2):
    return sorted(word1) == sorted(word2)

Sample runs: 样品运行:

>>> are_anagrams("lopped", "poodle")
False
>>> are_anagrams("lopped", "doppel")
True

Notes: 笔记:

  1. Both sort and sorted operate on strings as well as lists. sortsorted对字符串和列表sorted操作。 There is no need to convert to lists first. 无需先转换为列表。

  2. sorted(word1) == sorted(word2) evaluates to True or False. sorted(word1) == sorted(word2)计算结果为True或False。 Consequentl, the if-then-else statement can be eliminated. 因此,可以消除if-then-else语句。

Extensions to phrases and mixed-case 短语和大小写混合的扩展

Phrases can also be considered anagrams of each other. 短语也可以视为彼此的字谜。 Also, for anagrams, case should generally be ignored. 同样,对于字谜,通常应忽略大小写。 Thus: 从而:

def are_anagrams(word1, word2):
    return sorted(word1.lower().replace(' ', '')) == sorted(word2.lower().replace(' ', ''))

Thus: 从而:

>>> are_anagrams('Lopped', 'Ed Plop')
True

Rejecting the case of words being equal 拒绝单词相等的情况

If the words are the same, should they be considered anagrams? 如果单词相同,是否应将它们视为字谜? If not, then use: 如果不是,则使用:

     def are_anagrams(word1, word2):
        return (word1.lower() != word2.lower()) and sorted(word1.lower().replace(' ', '')) == sorted(word2.lower().replace(' ', ''))

Example: 例:

>>> are_anagrams('Lopped', 'Lopped')
False
>>> are_anagrams('Lopped', 'Old Pep')
True

Here's the issue: wordlist.sort() will return None because it does the sorting in place comparing None to None will always evaluate to True and yield falsified results. 这就是问题所在: wordlist.sort()将返回None因为它将进行适当的排序NoneNone进行比较将始终评估为True并产生伪造的结果。 You should be using sorted() which instead returns the newly sorted list and then perform the comparison: 您应该使用sorted() ,而不是返回新排序的列表,然后执行比较:

def are_anagrams(word1, word2):
    word1list = list(word1)
    word2list = list(word2)
    anagramfalse = False
    anagramtrue = True
    if (word1 == word2):
        return anagramfalse
    if (sorted(word1list)) == (sorted(word2list)):
        return anagramtrue
    else:
        return anagramfalse

Apart from that, there are further things to note, first, no need to set explicit names for True and False ; 除此之外,还有其他需要注意的事情,首先,无需为TrueFalse设置显式名称; just return them: 只需退货:

def are_anagrams(word1, word2):
    word1list = list(word1)
    word2list = list(word2)
    if (word1 == word2):
        return False
    if (sorted(word1list)) == (sorted(word2list)):
        return True
    else:
        return False

Second off, no need to cast the strings to lists with list , sorted will take care of that for you automatically by creating a list from the string, sorting it and then returning it: 其次,无需将字符串转换为具有listsorted可以通过从字符串创建list ,对其进行排序然后返回来自动为您处理:

def are_anagrams(word1, word2):
    if (word1 == word2):
        return False
    if (sorted(word1)) == (sorted(word2)):
        return True
    else:
        return False

Third off word1 == word2 won't really do much as a "quick check" to exit early; 第三位word1 == word2并不会真正起到提早退出的“快速检查”的作用。 sorting is fast in general, you could drop that all together: 一般而言,排序速度很快 ,您可以将它们放在一起:

def are_anagrams(word1, word2):
    if (sorted(word1)) == (sorted(word2)):
        return True
    else:
        return False

For the final step to make this code as sortest as possible, look at Johns answer; 为了使该代码尽可能地排序,最后一步,请看Johns的答案。 he simply returns the result of comparing the sorted objects. 他只返回比较已排序对象的结果。 No need to be explicit if your comparison will yield the right value for you. 如果您的比较能够为您带来正确的价值,则无需明确。 :-) :-)

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

相关问题 我不知道如何将数据写入到csv文件中以及如何正确执行排序代码 - I can't figure out how to write to my data to a csv file as well as having my sorting code function correctly 无法弄清楚为什么我的列表索引超出范围 - Can't figure out why my list index is out of range 我的函数没有返回值,无法弄清楚原因 - My function doesn't return a value, can't figure out why 我计算最大二进制间隙的函数不起作用,但我不知道为什么 - My Function To Count The Largest Binary Gap Doesn't Work But I Can't Figure Out Why 我的二分查找函数返回 None,我不知道为什么 - My function for binary search returns None, I can't figure out why Python 函数正在改变我输入的值,我不知道为什么 - Python function is changing the value of my input, and I can't figure out why 不明白为什么我的 else 语句仍然用负输入调用这个 function - Can't figure out why my else statement is still calling this function with negative input 我的清单是空的,但我不知道为什么? - My list is empty but I can't figure out why? 我不明白为什么我的 python 代码没有以英里为单位返回答案 - I cant figure out why my python code isn't returning the answer in miles Python requests.get(url) 返回空但不知道为什么 - Python requests.get(url) returning empty but can't figure out why
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM