【问题标题】:define anagram Python定义字谜 Python
【发布时间】:2022-11-07 18:42:13
【问题描述】:

例如: cat - kitten 这些词不是字谜; cat - act 单词是字谜; cat - cat 应该是同一个词。 我应该在这段代码中做什么以包含相同的单词:

s1 = input("Enter first word:")
s2 = input("Enter second word:")
a = sorted(s for s in s1.lower() if s.isalpha())
b = sorted(s for s in s2.lower() if s.isalpha())
if sorted(a) == sorted(b):
    print("The words are anagrams.")
else:
    print("The words aren't anagrams.")

【问题讨论】:

    标签: sorting


    【解决方案1】:

    我会在收集输入后进行检查。

        s1 = input("Enter first word:").lower().lower()
        s2 = input("Enter second word:")
        if s1 != s2:
            a = sorted(s for s in s1 if s.isalpha())
            b = sorted(s for s in s2 if s.isalpha())
            if sorted(a) == sorted(b):
                print("The words are anagrams.")
            else:
                print("The words aren't anagrams.")
        else:
            print("The words are anagrams.")
        ```
    

    【讨论】:

    • 无需再次对排序列表进行排序。
    • 简单点 if s1 != s2: 足以正确解决
    猜你喜欢
    • 2016-06-24
    • 2016-12-06
    • 2016-03-18
    • 2013-11-25
    • 2020-10-28
    • 2019-02-06
    • 2021-02-01
    • 2018-04-09
    • 1970-01-01
    相关资源
    最近更新 更多