I was wondering what the most computationally efficient Python way of cracking this problem would be.
Say you have two strings (or lists from splitting those strings--doesn't matter), "this is the right string" vs. "this is right the string."
We're assuming that the first string is always right, an开发者_高级运维d a score will be assigned to the second string based on which words were sequenced in the right order. For the above two strings, we would assign a score of 0.6 (as only 3 of the 5 words are in the right position).
Best, Georgina
This sounds very much like homework. Try thinking about it for a bit. Would it suffice to traverse the list of correct words once, and check if the corresponding word in the second list is equal to the word in the correct list?
I would probably zip the lists in python and compare the pairs for equality.
a = "this is the right string"
b = "this is right the string"
sum([1 for i,v in zip(a.split(), b.split()) if i == v])
sum(f == s for f, s in zip(first, second)) / len(first)
Use ord()
to convert each character to an integer value (its ordinal value), and then XOR each character together using the bitwise operator ^
. If the characters are the same, the XOR operation will return 0
(zero), then use |=
to bitwise OR the returned value with result
and then save the result of the operation as result
. If result
is still zero after you iterate over all the characters, then the strings are equivalent.
a = "this is the right string"
b = "this is right the string"
result = 0
for x,y in zip(a,b):
result |= ord(x) ^ ord(b)
(if result == 0): print "Equivalent"
精彩评论