简体   繁体   English

如何在 Python 中区分大小写的同时测试两个字符串是否是字谜?

[英]How to test if two strings are anagrams while being case sensitive in Python?

Okay so I have two functions, one that checks how many times a character appears in a string and another that is supposed to check if the two strings the user inputs are anagrams:好的,所以我有两个函数,一个检查字符在字符串中出现的次数,另一个检查用户输入的两个字符串是否为字谜:

def function_one(s, ch):
    count = 0
    for c in s:
        if c == ch:
            count = count + 1
    return count

def function_two(s, t):
    while len(s) == len(t):
        y = function_one(s, t)
        if y == 0:
            return True
        else:
            return False

Right now function_two will return True if the two strings are anagrams, but it will also return True if they are anagrams but have different letters capitalized, and will return nothing if they aren't anagrams at all.现在,如果两个字符串是变位词,function_two 将返回 True,但如果它们是变位词但大写不同的字母,它也会返回 True,如果它们根本不是变位词,则不会返回任何内容。 What do I do?我该怎么办?

There's a lot of ways of doing this.有很多方法可以做到这一点。 I think you're complicating things a bit by writing these functions.我认为您通过编写这些函数使事情变得有点复杂。

The first way of solving this that came in my mind was generating a list with all the letters in each string, sorting them and comparing both lists:我想到的第一种解决方法是生成一个包含每个字符串中所有字母的列表,对它们进行排序并比较两个列表:

def check_for_anagrams(string1, string2):
    list1 = list(string1.lower())
    list2 = list(string2.lower())
    list1.sort()
    list2.sort()

    return list1 == list2

it might not be the most elegant way to do it, but it's a quick solution.这可能不是最优雅的方法,但它是一个快速的解决方案。 the lower() function turns strings into lowercase the sort() function for lists sorts the list. lower() 函数将字符串转换为小写 列表的 sort() 函数对列表进行排序。

if two strings are anagrams, the result of these operations will be two equal lists.如果两个字符串是字谜,这些操作的结果将是两个相等的列表。

EDIT: Check the possible duplicate thread, there's some nice solutions there!编辑:检查可能的重复线程,那里有一些不错的解决方案!

You can sort out pairs of string that are no anagrams by checking the length of both strings first.您可以通过首先检查两个字符串的长度来整理出没有字谜的字符串对。 In a second stage you can compare the set of characters.在第二阶段,您可以比较字符集。 This is very fast in Python.这在 Python 中非常快。 In the last stage you have to count the occurences of the single characters in the set to be very sure the strings are anagrams.在最后一个阶段,您必须计算集合中单个字符的出现次数,以确保字符串是字谜。

CODE代码

from __future__ import print_function

def isAnagram(s1, s2) :
    s1, s2 = s1.lower(), s2.lower()

    if len(s1) == len(s2) :
        if set(s1) == set(s2) :
            return all([s1.count(c) == s2.count(c) for c in set(s1)])

    return False

string1 = 'Hello'
string2 = 'Hell'    # No anagram of string1
string3 = 'Holle'   # Anagram of string1    

print(isAnagram(string1, string2))
print(isAnagram(string1, string3))

OUTPUT输出

False
True

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM