How to test translation symmetry in Python? -
we 2 character values user define mapping (character translation), such 'a' -> 'p'
. how test other pairs of strings see if same mapping/translation holds across characters in strings. example:
'abcd', 'pqrs' returns true 'aaa', 'ppp' returns true 'acb', 'pqr' returns false 'aab', 'pqr' returns false
we want confirm offset (shift) of characters 1 string consistent. make sure target strings of same length; calculate offset , use all()
, generator expression combination try ensure logic completes on first miss, if any, rather continue checking:
def test(first, second, third, fourth): if len(third) != len(fourth): return false offset = ord(first) - ord(second) return all((ord(x) - ord(y)) == offset x, y in zip(third, fourth)) >>> test('a', 'p', 'abcd', 'pqrs') true >>> test('a', 'p', 'aaa', 'ppp') true >>> test('a', 'p', 'acb', 'pqr') false >>> test('a', 'p', 'aab', 'pqr') false
Comments
Post a Comment