efficiently checking for string.maketrans conflicts?

Michael Spencer mahs at telcopartners.com
Mon Apr 20 23:35:37 EDT 2009


Saketh wrote:
> Hi everyone:
> 
> I'm using "translation" in the sense of string.maketrans here.
> 
> I am trying to efficiently compare if two string translations
> "conflict" -- that is, either they differently translate the same
> letter, or they translate two different letters to the same one. 
...

Another solution, similar to Peter's...


def conflicts(from1,to1,from2,to2):
     '''returns True for 'conflicting translations'

      >>> conflicts('ab','cd','ab','cd')
      False
      >>> conflicts('ab','cd','ab','ce')
      True
      >>> conflicts('ab','cd','xy','cd')
      True
      >>> conflicts('ab','cd','cd','ab')
      False
     '''
     # forward translations
     trans1 = dict(zip(from1,to1))
     trans2 = dict(zip(from2,to2))

     for char in set(trans1).intersection(trans2):
         if trans1[char] != trans2[char]:
             return True

     # reverse translations
     revtrans1 = dict(zip(to1,from1))
     revtrans2 = dict(zip(to2,from2))

     for char in set(revtrans1).intersection(revtrans2):
         if revtrans1[char] != revtrans2[char]:
             return True

     return False

HTH
Michael




More information about the Python-list mailing list