Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
空列表中的Python字谜_Python_Dictionary_Anagram - Fatal编程技术网

空列表中的Python字谜

空列表中的Python字谜,python,dictionary,anagram,Python,Dictionary,Anagram,问题:编写一个程序,初始化一个空列表,然后提示用户输入一个单词,并不断提示用户输入单个单词,将每个单词添加到列表中,直到用户输入一个句点字符“.”,然后打印所有字词对,这些字词是字谜。比较应该不区分大小写可以简单地使用字典,但不是必需的。可以根据需要定义函数 我已经尝试了下面代码的几个版本,但我似乎不知道我做错了什么。有人能帮我指出正确的方向/给我一个类似的示例代码吗?我只是太困了 def areAnagrams(inputList): """Return inputList if wo

问题:编写一个程序,初始化一个空列表,然后提示用户输入一个单词,并不断提示用户输入单个单词,将每个单词添加到列表中,直到用户输入一个句点字符“.”,然后打印所有字词对,这些字词是字谜。比较应该不区分大小写可以简单地使用字典,但不是必需的。可以根据需要定义函数

我已经尝试了下面代码的几个版本,但我似乎不知道我做错了什么。有人能帮我指出正确的方向/给我一个类似的示例代码吗?我只是太困了

def areAnagrams(inputList):
    """Return inputList if words are anagrams, False otherwise"""
    inputList = sorted(inputList.lower())
    return inputList

inputList = raw_input ("Enter a word period to end: ") 
list = []
while inputList != '.':
    anagram = inputList
    list.append(anagram)
    inputList = raw_input("Enter a word (period to end): ")


print "Anagrams:", areAnagrams(inputList)

只需关注检查两个单词是否为字谜的部分,函数就需要检查两个单词是否长度相同,并且包含所有相同的字母。所以你可以做:

def areAnagrams(word1, word2):
    if len(word1) == len(word2):
        word1Letters = sorted(list(word1))
        word2Letters = sorted(list(word2))
        if word1Letters == word2Letters:
            return True
        else:
            return False
    else: 
        return False

实际上,您还没有实现任何可以找到字谜的代码。
arenagrams
方法所做的就是返回排序后的输入列表。你希望有人帮你做作业吗?为什么要对列表进行排序?变量命名可能不好。。。在这里,您将数据附加到一个名为“list”的变量,并对一个名为“inputList”的变量调用您的函数,此时该变量始终包含一个“.”。不,我不需要任何东西。只是在这个问题上迷失了方向。我根据我们在课堂上遇到的一个字谜问题(输入两个单词,然后排序)创建了这个例子。想知道我是否已经接近正确的轨道,但我没有。”然后打印所有的字词对,这些字词对是字谜。第一个提示:如果你希望你的函数
areAnagrams
能够告诉你一对字词是否是字谜,当你调用它时,你必须给它两个单独的单词。这个代码比它应该的复杂得多,只需执行
def areAnagrams(w1,w2):return sorted(list(w1))==sorted(list(w2))
@Doboy是的,你可能是对的。更简单的版本只会在边缘情况下失败,其中一个单词包含一个额外的字母,该字母在字母表中的出现时间比所有其他单词都晚(例如“rap”、“prat”),这是假设长度约束适用。