?

Log in

No account? Create an account

longest common prefix in python

« previous entry | next entry »
Aug. 14th, 2011 | 11:34 pm

from all_eq and longest_common_prefix in rpmkit/swapi.py:

# import itertools

def all_eq(xs):
    """Whether all items in xs (list or generator) equals each other.

    >>> all_eq(c for c in "")
    False
    >>> all_eq(c for c in "aaba")
    False
    >>> all_eq(c for c in "aaaa")
    True
    >>> all_eq([c for c in "aaaa"])
    True
    """
    if not isinstance(xs, list):
        xs = list(xs)  # xs may be a generator...

    return xs and all(x == xs[0] for x in xs[1:]) or False


def longest_common_prefix(*args):
    """Variant of LCS = Longest Common Sub-sequence.

    >>> longest_common_prefix("abc", "ab", "abcd")
    'ab'
    >>> longest_common_prefix("abc", "bc")
    ''
    """
    return "".join(x[0] for x in itertools.takewhile(all_eq, itertools.izip(*args)))

Link | Leave a comment | | Flag

Comments {0}