【问题标题】:Error in anagram code: python字谜代码错误:python
【发布时间】:2018-04-09 12:46:33
【问题描述】:

此函数将从 .txt 文件的列表中搜索字谜,我希望能够检查字谜并返回我输入的单词的所有字谜,如果它不是字谜,它将返回输入,当我在下面的代码中执行此操作时,它会遍历 for 循环,然后忽略我的第一个 if 语句并直接转到我的 else 语句。我该如何解决这个问题?

def find_in_dict():

input_word = input("Enter input string)")

sorted_word = ''.join(sorted(input_word.strip()))

a_word = ''.join((input_word.strip()))

word_file = open("filename", "r")

word_list = {}

for text in word_file:
    simple_text = ''.join(sorted(text.strip()))
    word_list.update({text.strip(): simple_text})
alist = []
for key, val in word_list.items():
    if val == sorted_word:
        alist.append(key)
        return alist
    else:
        return "No words can be formed from:" + a_word

【问题讨论】:

  • 使 if 语句中的条件评估为真 - python 不仅仅是“跳过”代码。

标签: python


【解决方案1】:

您正在 if 和 else 分支中创建 return 语句,这将破坏 for(因为在函数内部调用的 return 正是这样做的,中断执行并返回值),所以,不要这样做,只问单词是否相等,最后检查是否没有出现(空列表)

for text in word_file:
    simple_text = ''.join(sorted(text.strip()))
    word_list.update({text.strip(): simple_text})
alist = []
for key, val in word_list.items():
    if val == sorted_word:
        alist.append(key)

if alist == []: print("No words can be formed from: " + a_word)

【讨论】:

    猜你喜欢
    • 2018-12-15
    • 2017-02-13
    • 2013-07-02
    • 2016-12-06
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-13
    相关资源
    最近更新 更多