Are the words isomorphs? (Code-Golf)
This is my non-golfed, readable and linear (quasi-linear?) in complexity take of the above problem. For completeness I include the description:
Two words are isomorphs if they have the same pattern of letter repetitions. For example, both ESTATE and DUELED have pattern abcdca
ESTATE DUELED abcdca
because letters 1 and 6 are the same, letters 3 and 5 are the same, and nothing further. This also means the words are related by a substitution cipher, here with the matching
E <-> D, S <-> U, T <-> E, A <-> L
.Write code that takes two words and checks whether they are isomorphs.
As always tests are included for easier understanding and modification.
def repetition_pattern(text):
"""
Same letters get same numbers, small numbers are used first.
Note: two-digits or higher numbers may be used if the the text is too long.
>>> repetition_pattern('estate')
'012320'
>>> repetition_pattern('dueled')
'012320'
>>> repetition_pattern('longer example')
'012345647891004'
# ^ ^ ^ 4 stands for 'e' because 'e' is at 4-th position.
# ^^ Note the use of 10 after 9.
"""
for index, unique_letter in enumerate(sorted(set(text), key=text.index)):
text = text.replace(unique_letter, str(index))
return text
def are_isomorph(word_1, word_2):
"""
Have the words (or string of arbitrary characters)
the same the same `repetition_pattern` of letter repetitions?
All the words with all different letters are trivially isomorphs to each other.
>>> are_isomorph('estate', 'dueled')
True
>>> are_isomorph('estate'*10**4, 'dueled'*10**4)
True
>>> are_isomorph('foo', 'bar')
False
"""
return repetition_pattern(word_1) == repetition_pattern(word_2)
repetition_pattern
to return a string? \$\endgroup\$