开发者

match two strings with letters in random order in python

if I have 2 strin开发者_如何转开发gs like:

a = "hello"
b = "olhel"

I want to use a regular expression (or something else?) to see if the two strings contain the same letters. In my example a would = b because they have the same letters. How can this be achieved?


a = "hello"
b = "olhel"
print sorted(a) == sorted(b)


An O(n) algorithm is to create a dictionary of counts of each letter and then compare the dictionaries.

In Python 2.7 or newer this can be done using collections.Counter:

>>> from collections import Counter
>>> Counter('hello') == Counter('olhel')
True
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜