word pattern python

Solutions on MaxInterview for word pattern python by the best coders in the world

showing results for - "word pattern python"
Malena
12 Nov 2017
1import string
2
3def word_to_pattern(word):
4    # Stores actual-letter to pattern-placeholder mapping
5    mapping = {}
6
7    # ZYXW... so we cap pop letters starting with A from the end
8    available_pattern_letters = list(string.ascii_uppercase)[::-1]
9
10    pattern = []
11    for letter in word.upper():
12        if letter not in string.ascii_uppercase:
13            # for punctuation etc
14            pattern.append(letter)
15            continue
16        if letter not in mapping:
17            # new letter we haven't seen yet in this word
18            mapping[letter] = available_pattern_letters.pop()
19        pattern.append(mapping[letter])
20    return pattern.join("")
21