检查字谜的更优雅的方法是什么?
What's more elegant way to check for anagram?
我想不出比我的解决方案更好的检查字谜的方法:
def anagram(self,s,t):
if len(s) != len(t):
return False
else:
for elem1 in s:
current_looking = elem1
if current_looking in t:
current_index = t.index(current_looking)
t = t[:current_index] + t[current_index+1:]
else:
return False
return True
或者这样:
def anagram(s1,s2):
return sorted(s1) == sorted(s2)
或者也许还有另一个?
collections.Counter
比排序方法 (O(n) < O(n log(n))):
更简洁、更快
from collections import Counter
def anagram(a, b):
return Counter(a) == Counter(b)
您可以牺牲简洁性来提高性能:
def anagram(a, b):
return len(a) == len(b) and Counter(a) == Counter(b)
我想不出比我的解决方案更好的检查字谜的方法:
def anagram(self,s,t):
if len(s) != len(t):
return False
else:
for elem1 in s:
current_looking = elem1
if current_looking in t:
current_index = t.index(current_looking)
t = t[:current_index] + t[current_index+1:]
else:
return False
return True
或者这样:
def anagram(s1,s2):
return sorted(s1) == sorted(s2)
或者也许还有另一个?
collections.Counter
比排序方法 (O(n) < O(n log(n))):
from collections import Counter
def anagram(a, b):
return Counter(a) == Counter(b)
您可以牺牲简洁性来提高性能:
def anagram(a, b):
return len(a) == len(b) and Counter(a) == Counter(b)