| 2 | |
| 3 | |
| 4 | def SOUNDEX(TERM: str): |
| 5 | # Step 0: Covert the TERM to UpperCase |
| 6 | TERM = TERM.upper() |
| 7 | TERM_LETTERS = [char for char in TERM if char.isalpha()] |
| 8 | |
| 9 | # List the Remove occurrences of A, E, I, O, U, Y, H, W. |
| 10 | Remove_List = ("A", "E", "I", "O", "U", "Y", "H", "W") |
| 11 | # Save the first letter |
| 12 | first_letter = TERM_LETTERS[0] |
| 13 | # Take the Other letters instead of First_Letter |
| 14 | Characters = TERM_LETTERS[1:] |
| 15 | # Remove items from Character using Remove_List |
| 16 | Characters = [ |
| 17 | To_Characters |
| 18 | for To_Characters in Characters |
| 19 | if To_Characters not in Remove_List |
| 20 | ] |
| 21 | |
| 22 | # if len(Characters) == 0: |
| 23 | # return first_letter + "000" |
| 24 | |
| 25 | # Replace all the Characters with Numeric Values (instead of the first letter) with digits according to Soundex Algorythem Ruels |
| 26 | Replace_List = { |
| 27 | ("B", "F", "P", "V"): 1, |
| 28 | ("C", "G", "J", "K", "Q", "S", "X", "Z"): 2, |
| 29 | ("D", "T"): 3, |
| 30 | ("L"): 4, |
| 31 | ("M", "N"): 5, |
| 32 | ("R"): 6, |
| 33 | } |
| 34 | Characters = [ |
| 35 | value if char else char |
| 36 | for char in Characters |
| 37 | for group, value in Replace_List.items() |
| 38 | if char in group |
| 39 | ] |
| 40 | |
| 41 | # Step 3: Replace all adjacent same number with one number |
| 42 | Characters = [ |
| 43 | char |
| 44 | for Letter_Count, char in enumerate(Characters) |
| 45 | if ( |
| 46 | Letter_Count == len(Characters) - 1 |
| 47 | or ( |
| 48 | Letter_Count + 1 < len(Characters) |
| 49 | and char != Characters[Letter_Count + 1] |
| 50 | ) |
| 51 | ) |
| 52 | ] |
| 53 | |
| 54 | # If the saved Characters’s Number is the same the resulting First Letter,keep the First Letter AND remove the Number |
| 55 | if len(TERM_LETTERS) != 1: |
| 56 | if first_letter == TERM_LETTERS[1]: |
| 57 | Characters[0] = TERM[0] |
| 58 | else: |
| 59 | Characters.insert(0, first_letter) |
| 60 | |
| 61 | # If the Number of Characters are less than 4 insert 3 zeros to Characters |