检查两个字符串是否是字谜。编写一个函数anagrams(s1,s2),给定两个字符串s1和s2,如果它们是,则返回True 字谜,否则为False,否则使用字典
代码:
magick convert map.png -negate -morphology open disk:5 -negate result.png
答案 0 :(得分:1)
您可以对每个字符串使用字典来计算每个不同字符的出现次数:
def anagrams(s1, s2):
d = {}
for s in s1, s2:
d[s] = {}
for c in s:
d[s][c] = d[s].get(c, 0) + 1
return d[s1] == d[s2]
答案 1 :(得分:0)
如果要使用字典,请检查下面的代码
def anagrams(s1,s2):
s = s1+s2 #for example s = asd + dsa = asddsa
l = list(s) #[a,s,d,d,s,a]
dic = dict(enumerate(l)) # {0: 'a', 1: 's', 2: 'd', 3: 'd', 4: 's', 5: 'a'}
if len(dic)%2 == 1: #if the two strings are anagrams, the length of the combined strings should be even number
return False
else: # now we just compare the two ends of all keys, in the above example, we compare 0 and 5 / 1 and 4 / 2 and 3
# Notice: the sum of i and the its corresponding party is the len of dic
i = 0
while i < len(dic)/2:
if dic[i] != dic[len(dic)-1-i]:
return False
break
else:
i += 1
return True
或者,您可以使用满足相同目的的双端队列功能。简单的逻辑是将拖车绳加在一起并比较两端
from collections import deque
def anagrams(s1,s2):
s = s1+s2 # put them into one string and now we can simply compare if the far left and far right one is the same
dq = deque(s) # apply deque function to it
while len(dq) > 1: #if it equals to one
if dq.popleft() != dq.pop():
return False
if len(dq) == 1:
return False
else:
return True
答案 2 :(得分:0)
您可以将单词加载到词典中并比较字典的排序值。
D1={}
D2={}
def anagrams(s1,s2):
if len(s1)!=len(s2):
return False
else:
elementNumber = 0
for char in s1: #Load s1 into dictionary
D1[elementNumber] = char
elementNumber = elementNumber + 1
elementNumber = 0
for char in s2: #Load s2 into dictionary
D2[elementNumber] = char
elementNumber = elementNumber + 1
print(sorted(D1.values())) #Example output
print(sorted(D2.values())) #Example output
if sorted(D1.values())==sorted(D2.values()): #Sort and compare
return True
else:
return False
print("Anagrams: "+str(anagrams("Hello", "oHlel"))) #Returns True
print("Anagrams: "+str(anagrams("Hello", "xyzlo"))) #Returns False
答案 3 :(得分:0)
如果您只是检查一个字谜,请尝试使用python的Counter
对象。您只需要一行即可。
# Python code to check if two strings are
# anagram
from collections import Counter
def anagram(input1, input2):
# Counter() returns a dictionary data
# structure which contains characters
# of input as key and their frequencies
# as it's corresponding value
return Counter(input1) == Counter(input2)