I am try to write a function that allows me to line up two strings if the characters in both strings match.
for example Input:
output:
['H', 'o', 'u', 's', 'e'] ['H', 'o', 's']
desired output:
['H', 'o', 'u', 's', 'e']
['H', 'o', ,'0','s', '0']
I was thinking of doing this with something like bubble sort or using bigrams, but I don't have any experience with those. Does anyone have any suggestions ?
Quick and dirty approach:
l1 = ['H', 'o', 'u', 's', 'e']
l2 = ['H', 'o', 's']
l2, l1 = sorted((l1, l2), key=len)
l = len(l1)
j = 0
res = []
for i in range(l):
try:
if l1[i]==l2[j]:
res.append(l1[i])
j += 1
else:
res.append(None)
except IndexError:
res.extend([None] * (l-j))
break
print(res) # -> ['H', 'o', None, 's', None]
Note that clarifications are needed! (see @yatu's comment)
Also note that I changed your '0' to None. Using '0' is a bad idea since, at least in theory, your two initial lists might contain that and you will not be able to differentiate between a match and a non-match.
I am definitely looking forward to a more elegant approach to this interesting problem!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With