Checking if two strings are permutations of each other in Python

前端 未结 22 2499
旧时难觅i
旧时难觅i 2020-12-08 16:04

I\'m checking if two strings a and b are permutations of each other, and I\'m wondering what the ideal way to do this is in Python. From the Zen of

22条回答
  •  醉酒成梦
    2020-12-08 16:20

    Here are some timed executions on very small strings, using two different methods:
    1. sorting
    2. counting (specifically the original method by @namin).

    a, b, c = 'confused', 'unfocused', 'foncused'
    
    sort_method = lambda x,y: sorted(x) == sorted(y)
    
    def count_method(a, b):
        d = {}
        for x in a:
            d[x] = d.get(x, 0) + 1
        for x in b:
            d[x] = d.get(x, 0) - 1
        for v in d.itervalues():
            if v != 0:
                return False
        return True
    

    Average run times of the 2 methods over 100,000 loops are:

    non-match (string a and b)

    $ python -m timeit -s 'import temp' 'temp.sort_method(temp.a, temp.b)'
    100000 loops, best of 3: 9.72 usec per loop
    $ python -m timeit -s 'import temp' 'temp.count_method(temp.a, temp.b)'
    10000 loops, best of 3: 28.1 usec per loop
    

    match (string a and c)

    $ python -m timeit -s 'import temp' 'temp.sort_method(temp.a, temp.c)'
    100000 loops, best of 3: 9.47 usec per loop
    $ python -m timeit -s 'import temp' 'temp.count_method(temp.a, temp.c)'
    100000 loops, best of 3: 24.6 usec per loop
    

    Keep in mind that the strings used are very small. The time complexity of the methods are different, so you'll see different results with very large strings. Choose according to your data, you may even use a combination of the two.

提交回复
热议问题