Reputation: 21
The problem involves two strings. If the strings are the same or similar (so the letters look the same as listed in l), the answer will be true. If they are not the same or similar, the answer is false.
I have written the code and it passes all of the tests except 2. It says true for "BOX" vs "B0B" but it should say false. The same for "OXB" vs "0BX". I believe this is because when it starts looping, it returns "true" too early and doesn't loop properly through all the characters. I have tried using Python visualiser to see what's happening and tried different code but couldn't get these 2 tests to pass.
This is my code:
from array import *
def similar_license_plates(plate1: str, plate2: str) -> bool:
p1 = plate1.replace(" ","")
p2 = plate2.replace(" ","")
if p1 == p2:
return True
if len(p1) != len(p2):
return False
else:
l = [["0", "O", "Q"], ["1", "I", "T"], ["2", "Z"], ["5", "S"], ["8", "B"]]
x = list(zip(p1, p2))
for a, b in x:
if a == b:
continue
for c in l:
if a in c:
if b in c:
return True
return False
if a == b:
return True
return False
Upvotes: 0
Views: 90
Reputation: 13939
You can use str.translate
to regularize the inputs and simplify the task:
def similar_license_plates(plate1, plate2):
tr = str.maketrans('OQITZSB', '0011258', ' ')
return plate1.translate(tr) == plate2.translate(tr)
print(similar_license_plates('BOX', 'B0X')) # True
print(similar_license_plates('BOX', 'B0B')) # False
By maketrans(...)
, 'O'
is converted to '0'
, 'Q'
is converted to '0'
, and so on, and blanks are discarded (by the third argument).
To automatically generate the translation rule as above (to be provided to maketrans
), you can use the following:
l = [["0", "O", "Q"], ["1", "I", "T"], ["2", "Z"], ["5", "S"], ["8", "B"]]
to_chars, from_chars = map(''.join, zip(*[(sublst[0], to) for sublst in l for to in sublst[1:]]))
print(from_chars, to_chars) # OQITZSB 0011258
Upvotes: 3