python - How to find a particular string within another string as quickly as possible? -


i'd know if there better/nicer/faster way solve following problem.

return true if given string contains appearance of "abc" abc not directly preceded period (.). "qabc" counts "r.abc" not count.

my solution was:

def abc_there(string):     tmp = 0     in xrange(len(string)):         if string[i:i+3] == "abc" , string[i-1] != ".":             tmp += 1     return tmp > 0 

edit:

just clarify:

".abc" --> false

".abcabc" --> true

only instance next right of period gets erased.

there less straight-forward way problem , it's faster too. code:

def xyz_there(string):     return string.count(".abc") != string.count("abc") 

this works because if there string passed "abc.abc", ".abc" count 1 abc count 2 if string "fd.abc.abc" example. return false.

to prove it's faster, headed on ipython.

in [1]: def abc_there(string):  ...:       tmp = 0  ...:       in xrange(len(string)):  ...:           if string[i:i+3] == "abc" , string[i-1] != ".":  ...:               tmp += 1  ...:       return tmp > 0  in [2]: timeit abc_there("nghkabc") out[2]: 1000000 loops, best of 3: 310 ns per loop  in [3]: def abc_there(string): ...:        return string.count(".abc") != string.count("abc")  in [4]: timeit abc_there("nghkabc") out[4]: 1000000 loops, best of 3: 296 ns per loop 

296ns < 310ns solution bit faster.


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -