Comparing strings from the back?

Peter Otten __peter__ at web.de
Wed Sep 5 11:45:55 EDT 2012


Oscar Benjamin wrote:

> On 5 September 2012 10:48, Peter Otten <__peter__ at web.de> wrote:

>> def count_common(a, b):

[sorry for seriously broken implementation]

> This function will return 1 if the first character differs. It does not
> count the number of common characters but rather the more relevant
> quantity which is the number of comparisons required to decide if the
> strings are equal.

I remember stumbling over the non-zero frequency for len(word) but somehow 
plodded on with beautifying the broken results :(

def count_common(a, b):
    """
    >>> count_common("alpha", "beta")
    0
    >>> count_common("", "")
    0
    >>> count_common("alpha", "argument")
    1
    >>> count_common("alpha", "alpha")
    5
    >>> count_common("alpha", "alphx")
    4
    """
    i = 0
    for x, y in zip(a, b):
        if x != y:
            break
        i += 1
    return i


$ python3 reverse_compare2.py compare /usr/share/dict/words
499500 combinations
average common chars (head) 0.0535
average common chars (tail) 0.322
comparing every pair in a sample of 1000 8-char words
taken from '/usr/share/dict/words'

head
0: 477371 ************************************************************
1:  18310 **
2:   3191 
3:    523 
4:     79 
5:     15 
6:     10 
7:      1 

tail
0: 385069 ************************************************************
1:  78742 ************
2:  26734 ****
3:   7462 *
4:   1297 
5:    168 
6:     22 
7:      6 





More information about the Python-list mailing list