【发布时间】:2019-09-20 15:43:46
【问题描述】:
我正在处理一个简单的问题:
- 检查两个字符串是否是字谜。
我写了一个简单的代码,可以检查两个字符串,比如 'abcd' 和 'dcba' 是字谜,但我不知道如何处理更复杂的字谜,例如“Astronomer”和“Moon starter”。
line1 = input('Enter the first word: ')
line2 = input('Enter the second word: ')
def deleteSpaces(s):
s_new = s.replace(" ","")
return s_new
def anagramSolution2(s1,s2):
alist1 = list(deleteSpaces(s1))
alist2 = list(deleteSpaces(s2))
print(alist1)
print(alist2)
alist1.sort()
alist2.sort()
pos = 0
matches = True
while pos < len(deleteSpaces(s1)) and matches:
if alist1[pos]==alist2[pos]:
pos = pos + 1
else:
matches = False
return matches
首先我认为问题在于使用空格,但后来我明白如果字符串大小不同,我的算法就不起作用。
我不知道在这种情况下该怎么办。
在这里我找到了一个漂亮的解决方案,但它也不起作用:
def anagrams(s1,s2):
return [False, True][sum([ord(x) for x in s1]) == sum([ord(x) for x in s2])]
如果我运行这个函数并在两个字符串上测试它,我会得到这样的输出:
Examples:
First Word: apple
Second Word: pleap
output: True
First Word: Moon starter
Second Word: Astronomer
output: False //however it should should be True because this words are anagrams
【问题讨论】:
-
不起作用是什么意思?
-
我的意思是它返回False,而它应该是True
-
请举例说明清楚。
-
另外,我猜你的程序的问题在于案例。但我不太确定,因为没有足够的例子。
-
@MagnusBuvarp No. 例如
"aabc"和"abcc"在这种情况下是正确的,这是错误的。