【发布时间】:2015-02-05 20:48:10
【问题描述】:
interactivepython.org 提供的 Count and Compare Anagram solution 检查会遍历列表,最后一次检查每个 ASCII 值的计数是否相同。
j = 0
stillOK = True
while j<26 and stillOK:
if c1[j]==c2[j]:
j = j + 1
else:
stillOK = False
return stillOK
为什么不使用比较运算符?
return (c1 == c2)
完整代码:
def anagramSolution4(s1,s2):
c1 = [0]*26
c2 = [0]*26
for i in range(len(s1)):
pos = ord(s1[i])-ord('a')
c1[pos] = c1[pos] + 1
for i in range(len(s2)):
pos = ord(s2[i])-ord('a')
c2[pos] = c2[pos] + 1
j = 0
stillOK = True
while j<26 and stillOK:
if c1[j]==c2[j]:
j = j + 1
else:
stillOK = False
return stillOK
print(anagramSolution4('apple','pleap'))
编辑添加:
我已经测试过:
anagramSolution4('abc','cba') #returns True
anagramSolution4('abc','cbd') #returns False
anagramSolution4('abc','cbah') #returns False
..他们都通过了。显示 c1==c2 失败的适当测试是什么?
【问题讨论】:
-
你为什么不试试代码,看看它是否有效?
-
是的,这是必要的,因为没有这个循环就无法在输入之间进行比较......有更好的方法来完成整个事情,但目前需要这个循环。
-
@MattDMo 我做了,它通过了测试
anagramSolution4('abc','cba')和anagramSolution4('abc','cbd')和anagramSolution4('abc','cbah') -
这并不能回答您的问题,但是使用
collections.Counter、生成器表达式和字符串方法可以更简单地实现这一点。首先创建一个辅助函数def letter_counts(s):return Counter(c.lower() for c in s if c.isalpha()),然后比较letter_counts(s1) == letter_counts(s2)。如果您只比较没有标点或空格的小写单词,则可以省略辅助函数:Counter(s1) == Counter(s2)。 -
同样,解决方案 2 可以重新实现为
sorted(s1) == sorted(s2)。我怀疑这段冗长代码的目的是让初学者清楚所有步骤。
标签: python list list-comparison