efficiently checking for string.maketrans conflicts?

Saketh saketh.bhamidipati at gmail.com
Wed Apr 22 21:41:13 EDT 2009


On Apr 20, 11:35 pm, Michael Spencer <m... at telcopartners.com> wrote:
> Saketh wrote:
> > Hi everyone:
>
> > I'm using "translation" in the sense ofstring.maketranshere.
>
> > 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

Thank you, Peter and Michael, for your solutions! I think that
Michael's is what I was edging towards, but Peter's has demonstrated
to me how efficient Python's set functions are. I have a lot more to
learn about optimizing algorithms in Python... :)



More information about the Python-list mailing list