如何检查两个字符串是否是彼此的字谜?

问题描述 投票:0回答:27

我正在尝试编写一个接受用户的两个字符串的程序:

s1 = input("Please enter a word:")
s2 = input("Please enter another word:")

如果这两个是字谜词,我如何输出

True
,否则如何输出
False


如果您从搜索引擎中发现此问题,并且想要在列表中查找可能的多个字谜词:比较每对元素是“可能的,但不是最佳的”。请参阅使用 Python,查找单词列表的字谜词以获取更具体的建议。

python anagram
27个回答
46
投票

>>> sorted('anagram') ['a', 'a', 'a', 'g', 'm', 'n', 'r'] >>> sorted('nagaram') ['a', 'a', 'a', 'g', 'm', 'n', 'r'] >>> sorted('anagram') == sorted('nagaram') True



18
投票
collections

库中的神奇Counter。 来自文档:

它是一个无序集合,其中元素存储为字典键,它们的计数存储为字典值

因此,您可以使用字符串(可迭代)初始化 Counter 对象,并与字符串中的另一个 Counter 进行比较

from collections import Counter def is_anagram(str1, str2): return Counter(str1) == Counter(str2)



5
投票
break

跳出此循环并打印“False”语句。考虑使用像

all_s1_in_s2 = True
这样的变量,然后如果发现不匹配的字母,则将其设置为 false。

其他一些提示:

  • for l in s1

    将循环遍历字符串 s1,让您按

    l
    的顺序访问每个字母 - 您根本不需要
    range
    len
    
    

  • if .. in

    语句可以帮助测试字符串中是否存在字母,例如

    if letter in mystring:
    是一个有效的陈述,这可以对您有很大帮助,同样不需要
    range
    len
    
    

  • 您应该尽可能避免在变量名称中使用数字 - 更好的是
  • word_one

    word_two
    ,例如
    
    


3
投票

def anagram(s): string_list = [] for ch in s.lower(): string_list.append(ch) string_dict = {} for ch in string_list: if ch not in string_dict: string_dict[ch] = 1 else: string_dict[ch] = string_dict[ch] + 1 return string_dict s1 = "master" s2 = "stream" a = anagram(s1) b = anagram(s2) if a == b: print "Anagram" else: print "Not Anagram"



3
投票


1
投票


1
投票

#An anagram is the result of rearranging the letters of a word to produce a new word. Anagrams are case insensitive #Examples: # foefet is an anagram of toffee # Buckethead is an anagram of DeathCubeK # The shortest my function style *************************************** def is_anagram1(test, original): """Сhecks 'test' is anagram of 'original' strings based on: 1. length of the both string and length of the sets made from the strings is equivalent 2. then checks equivalents of sorted lists created from test and original strings >>> is_anagram1('Same','same') False >>> is_anagram1('toffee','foeftt') False >>> is_anagram1('foefet','toffee') True >>> is_anagram1("Buuckk",'kkkcuB') False >>> is_anagram1('Buckethead','DeathCubeK') True >>> is_anagram1('DeathCubeK','Buckethead') True """ # check the length of the both string if len(test) != len(original): return False # check is the strings are the same t,o = test.lower(), original.lower() if t == o: return False # check the sorted lists return sorted(t) == sorted(o) # The final my one line code ************************************** def is_anagram(test, original): """Сhecks 'test' is anagram of 'original' in one line of code >>> is_anagram('Same','same') False >>> is_anagram('toffee','foeftt') False >>> is_anagram('foefet','toffee') True >>> is_anagram("Buuckk",'kkkcuB') False >>> is_anagram('Buckethead','DeathCubeK') True >>> is_anagram('DeathCubeK','Buckethead') True """ return False if len(test) != len(original) or test.lower() == original.lower() else sorted(test.lower()) == sorted(original.lower()) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) ### 2 items passed all tests: ### 6 tests in __main__.is_anagram ### 6 tests in __main__.is_anagram1 ### 12 tests in 3 items. ### 12 passed and 0 failed. ### Test passed



1
投票

text = input('Enter a string: ') text1 = input('Enter a string: ') text,text1 = text.lower(),text1.lower() count = 0 count1=0 for i in range(97,123): if chr(i) in text and chr(i) in text1: count1+=1 if text.count(chr(i)) == text1.count(chr(i)): count +=1 if len(text) >= len(text1): num1 = len(text) else: num1 = len(text1) if count == count1: print("they are anagrams") else : print("they are not anagrams")



1
投票

使用理解创建字典,并使用简单的

==

运算符比较两个单词的字典。


def isanagram2(wrd1, wrd2): wrd1_dict = {k: 0 for k in wrd1} wrd2_dict = {k: 0 for k in wrd2} for c1, c2 in zip(wrd1, wrd2): wrd1_dict[c1] += 1 wrd2_dict[c2] += 1 if wrd1_dict == wrd2_dict: return True return False



1
投票

s1 = "listen" s2 = "silent" s1=list(s1);s1.sort() s2 = list(s2);s2.sort() if s1 == s2: print ("Given Strings are Anagram") else: print ("Given String are not anagrams")
    


1
投票

def is_anagram(a, b): return sorted(a.lower()) == sorted(b.lower())



0
投票

def check_(arg): mark = hash(str(set(sorted(arg)))) return mark def ana(s1, s2): if check_(s1) != check_(s2): pass elif len(s1) != len(s2): pass else: print("{0} could be anagram of {1}".format(s1, s2))



0
投票

str1="abcd" str2="bcad" word1=[] word2=[] for x in range(len(str1)): word1.append(str1[x]) for x in range(len(str2)): word2.append(str2[x]) if(len(word1)==len(word2)): for letter in word1: if letter in word2: word2.remove(letter) if len(word2)==0: print "anagram" else: print "not anagram"



0
投票

解释:在下面的代码中,我们可以回答两个问题:1)两个字符串是否是字谜词,2)如果w2是w1子序列的字谜词。我们使用 O(1) 空间(常数)和 O(n) 时间。字典 d0 可以扩展为包含任何字符,并且我们保持在 O(1) 空间范围内。

def anagrams(w1,w2): d0={chr(i):0 for i in range(ord('a'),ord('z'))} for char in w1: d0[char]+=1 for char in w2: if d0[char]==0: return False else: d0[char]-=1 return sum([d0[x] for x in d0])==0 #return True (for subseqence anagram)



0
投票

def anagram(word1, word2): return sorted(word1) == sorted(word2)

检查

print(anagram("xyz","zyx")) >>True print(anagram("xyz","zyy")) >>False



0
投票

def anagram(s1, s2): """ (str, str) -> bool Return True if s1 and s2 are anagrams >>> anagram(s1, s2) True """ s1 = s1.replace(" ", "") s2 = s2.replace(" ", "") s1_new = list(s1) s2_new = list(s2) if len(s1_new) == len(s2_new): dupe_found = True while dupe_found: dupe_found = False for i in s1_new: for j in s2_new: if i == j: s1_new.remove(i) s2_new.remove(j) dupe_found = True break break return s1_new == s2_new



0
投票
字谜(a,b)


0
投票

static void anagram(String s1,String s2){ if(s1.length()!=s2.length()){ System.out.println("not anagram"); return; } else{ int []arr=new int[256]; int size=s1.length(); for(int i=0;i<size;i++){ arr[s1.charAt(i)]++; arr[s2.charAt(i)]--; } for(int i=0;i<256;i++){ if(arr[i]!=0){ System.out.println("not anagram"); return; } } System.out.println("anagram"); } }



0
投票

def is_anagram(s1, s2): return {c:s1.count(c) for c in s1} == {c:s2.count(c) for c in s2}



0
投票


-1
投票

查看给定的两个单词或句子是否是字谜的一个好方法是设置一个大小为 256 的计数器数组,并最初将所有值设置为 0。(如果输入更大,至少比几个单词)现在开始读取第一个字符串(单词或句子),并将其在数组中相应的 ASCII 位置加一。对完整的字符串重复此操作。 现在开始读取第二个字符串,并不断减少数组中每个字母对应的 ASCII 计数器。 最后,解析数组;如果所有值都为零,则输入是字谜词,否则不是。 以下是注释代码,以便更好地理解。

#include<iostream> #include<string> using namespace std; bool is_anagram(string s1, string s2) { //Following statement chechs the base condition; if either of the strings is empty, //return False if(s1.length() == 0 || s2.length() == 0) return false; //initializing the counter array and setting it's values to 0 int counter[256] = {0}; //Calculating the lengths of both the strings int len1 = s1.length(); int len2 = s2.length(); //Following is also a base condition that checks whether the strings are equal in //length, if not we return False if(len1 != len2) return false; //Following for loop increments the values of the counter array for the first //string for(int i = 0; i < len1; i++) { counter[s1[i]]++; } //This for loop decrements the values of the counter array for the second string for(int i = 0; i < len2; i--) { counter[s2[i]]--; } //Now we check whether the counter array is empty/(or as it was initialized); if //yes then the two strings are anagrams for(int i = 0; i < 256; i++) { if(counter[i] != 0) return false; } return true; }



-1
投票

def anagram(s1, s2): str1 = '' str2 = '' for i in s1: str1 += i for j in s2: str2 += j if str1 == str2: return True return False



-1
投票


-2
投票

s1 = "aaabbbccc" s2 = "abcabcabc" def are_anagram1(s1, s2): return [False, True][sum([ord(x) for x in s1]) == sum([ord(x) for x in s2])] print are_anagram1(s1,s2)

注意:这只适用于字母,不适用于数字


-2
投票


-2
投票

print('Strings are anagrams' if sorted(input("Enter 1st string: "))== sorted(input("Enter 2nd string: ")) else 'Strings are not anagrams')



-2
投票

are_anagrams = lambda str1, str2: sorted(str1) == sorted(str2) result = are_anagrams("debit card", "bad credit") print(result)

© www.soinside.com 2019 - 2024. All rights reserved.