Determine the common prefix of two strings. Args: text1: First string. text2: Second string. Returns: The number of characters common to the start of each string.
(text1, text2)
| 571 | |
| 572 | |
| 573 | def common_prefix(text1, text2): |
| 574 | """ |
| 575 | Determine the common prefix of two strings. |
| 576 | |
| 577 | Args: |
| 578 | text1: First string. |
| 579 | text2: Second string. |
| 580 | |
| 581 | Returns: |
| 582 | The number of characters common to the start of each string. |
| 583 | """ |
| 584 | # Quick check for common null cases. |
| 585 | if not text1 or not text2 or text1[0] != text2[0]: |
| 586 | return 0 |
| 587 | # Binary search. |
| 588 | # Performance analysis: https://neil.fraser.name/news/2007/10/09/ |
| 589 | pointermin = 0 |
| 590 | |
| 591 | # TODO: move as args |
| 592 | len_text1 = len(text1) |
| 593 | len_text2 = len(text2) |
| 594 | |
| 595 | pointermax = min(len_text1, len_text2) |
| 596 | pointermid = pointermax |
| 597 | pointerstart = 0 |
| 598 | |
| 599 | while pointermin < pointermid: |
| 600 | if text1[pointerstart:pointermid] == text2[pointerstart:pointermid]: |
| 601 | pointermin = pointermid |
| 602 | pointerstart = pointermin |
| 603 | else: |
| 604 | pointermax = pointermid |
| 605 | |
| 606 | pointermid = (pointermax - pointermin) // 2 + pointermin |
| 607 | |
| 608 | return pointermid |
| 609 | |
| 610 | |
| 611 | def common_suffix(text1, text2): |
no outgoing calls
no test coverage detected