views:

43

answers:

3

Hi experts,

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, and 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

+2  A: 

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.

ptman
It's easy to come up with *a* solution, but I'm looking for the fastest, most computationally efficient one!
Georgina
@Georgina: so where was your bad inefficient code?
SilentGhost
A: 
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])
singularity
you don't needs list comprehension there
SilentGhost
@SilentGhost: yes thanks, i should start thing more generator expression :)
singularity
Returns 3. OP wanted 0.6
eumiro
@eumiro: don't be anal.
SilentGhost
@eumiro: i think the change is trivial isn't it ? beside helping some one with a problem don't mean give in him all the answer, just given some indication to the right answer can help him too
singularity
@singularity - that's true. If OP is searching for 'computationally efficient' code, he could check itertools. But how to split() a string lazily?
eumiro
A: 
sum(f == s for f, s in zip(first, second)) / len(first)
SilentGhost
In Python 2.x returns 0 because of the integer division. some `float()` could be needed.
eumiro
@eumiro: might return 1 depending on the input
SilentGhost
@SilentGhost: yes, might return 1. But in the OP's example should return 0.6 and returns 0.
eumiro
why the downvote?
SilentGhost
@eumiro: it's completely besides the point. Accepter answer doesn't return 0.6 either.
SilentGhost