efficiently checking for string.maketrans conflicts?
saketh.bhamidipati at gmail.com
Thu Apr 23 03:41:13 CEST 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')
> >>> conflicts('ab','cd','ab','ce')
> >>> conflicts('ab','cd','xy','cd')
> >>> conflicts('ab','cd','cd','ab')
> # 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
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