函数不断循环回答

时间:2014-11-18 18:00:49

标签: python string function python-3.3

更新

def get_dictionary_word_list():
    with open('dictionarys.txt') as f:
        return f.read().split()

def partial_anagram(str1,str2):
    str2_list = list(str2)
    for char in str1:
        if char in str2_list:
             str2_list.remove(char)
        else:
             return False
    return True

def find_partial_anagrams_in_word_list(str1,strlist):
     partial_anagrams = []
     for word in str_list:
          if (partial_anagram(word, str1)):
              partial_anagrams.append(word)
          print(partial_anagrams)

函数find_partial_anagrams_in_word_list(str1,str_list)现在可以正常工作,但不断循环回答并且不会停止返回它们。我怎么能让它只返回一次?

4 个答案:

答案 0 :(得分:1)

def partial_anagram(str1,str2):
    str2_list = list(str2)
    for char in str1:
        if char in str2_list:
             str2_list.remove(char)
        else:
             return False
        return True

看起来你有缩进问题。如果for循环完成执行而不点击return True块,则只应else。尝试一个人不知情。

def partial_anagram(str1,str2):
    str2_list = list(str2)
    for char in str1:
        if char in str2_list:
             str2_list.remove(char)
        else:
             return False
    return True

您还需要对最终印刷品进行去缩进。

def find_partial_anagrams_in_word_list(str1,strlist):
     partial_anagrams = []
     for word in str_list:
          if (partial_anagram(word, str1)):
              partial_anagrams.append(word)
     print(partial_anagrams)

答案 1 :(得分:1)

将此行移出for for循环:

def find_partial_anagrams_in_word_list(str1,strlist):
     partial_anagrams = []
     for word in str_list:
          if (partial_anagram(word, str1)):
              partial_anagrams.append(word)
          print(partial_anagrams) # THIS LINE... <<<

应该是:

def find_partial_anagrams_in_word_list(str1,strlist):
     partial_anagrams = []
     for word in str_list:
          if (partial_anagram(word, str1)):
              partial_anagrams.append(word)

     print(partial_anagrams) # same level as the for loop

答案 2 :(得分:0)

def get_dictionary_word_list():
    return open('dictionarys.txt').read().split()


def partial_anagram(str_1, str_2):
    return not any(str_1.count(char_1) > str_2.count(char_1) for char_1 in str_1)


def find_partial_anagrams_in_word_list(str_1, str_list):
    return [word for word in str_list if partial_anagram(word, str_1)]

答案 3 :(得分:0)

这段代码不会无限循环回答并返回文本文件的部分字谜。

def find_partial_anagrams_in_word_list(str1,str_list):
    partial_anagrams = []
    for word in str_list:
         if (partial_anagram(word, str1)):
             partial_anagrams.append(word)
             print(word)