Skip to content

k3pattern

Action-CI Documentation Status Package

Find common prefix of strings, tuples, and nested structures.

k3pattern is a component of pykit3 project: a python3 toolkit set.

Installation

pip install k3pattern

Quick Start

from k3pattern import common_prefix

# Find common prefix of strings
common_prefix("abc", "abd")
# 'ab'

# Find common prefix of tuples
common_prefix(("a", "b", "c"), ("a", "b", "d"))
# ('a', 'b')

# Nested structures (recursive by default)
common_prefix(("a", "bc", "x"), ("a", "bd", "y"))
# ('a', 'b')

# Disable recursive mode
common_prefix(("a", "bc", "x"), ("a", "bd", "y"), recursive=False)
# ('a',)

API Reference

k3pattern

Find common prefix of several string, tuples of string, or other nested structure, recursively by default. It returns the shortest prefix: empty string or empty tuple is removed.

common_prefix(a, *others, recursive=True)

Find common prefix of several strings, tuples of string, or other nested structure, recursively by default. It returns the shortest prefix: empty string or empty tuple is removed. :param a: a and element in others: are string, tuple or list to find common prefix of them. :param recursive: if it is False, it will run non-recursively. :return: a common prefix of the same type of a.

Source code in k3pattern/strutil.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
def common_prefix(a, *others, recursive=True):
    """
    Find common prefix of several `string`s, tuples of string, or other nested
    structure, recursively by default.
    It returns the shortest prefix: empty string or empty tuple is removed.
    :param a: `a` and element in `others`: are `string`, `tuple` or `list` to find common prefix of them.
    :param recursive: if it is `False`, it will run non-recursively.
    :return: a common prefix of the same type of `a`.
    """
    for b in others:
        if type(a) is not type(b):
            raise TypeError("a and b has different type: " + repr((a, b)))
        a = _common_prefix(a, b, recursive)

    return a

License

The MIT License (MIT) - Copyright (c) 2015 Zhang Yanpo (张炎泼)