Reputation: 1705
I'm looking for the fastest way to compare if a string has one of two lengths. This string must be either one letter longer or shorter, and I feel that the if statement below might not be the fastest and I don't see much of an improvement in time with it, or without it.
I'm comparing between two string, if my_word
length is more than 1 character less or more than compare_word
then I shall continue my loop.
if (len(compare_word) > (len(my_word)+1)) and (len(compare_word) < (len(my_word)-1)):
continue
Upvotes: 2
Views: 1222
Reputation: 188164
Example:
s = "Hello"
t = "Worl"
if abs(len(s) - len(t)) > 1:
print("string lengths differ by more than 1")
Update: With ipython's timeit
there are almost no speed gain, however:
In [10]: s = str(range(100000))
In [11]: t = str(range(100001))
In [12]: %timeit len(s) > len(t) + 1 and len(s) < len(t) - 1
10000000 loops, best of 3: 106 ns per loop
In [13]: %timeit abs(len(s) - len(t)) > 1
10000000 loops, best of 3: 115 ns per loop
In [14]: %timeit 1 >= len(s) - len(t) >= -1
10000000 loops, best of 3: 113 ns per loop
Here's another run with shorter strings, but about the same result: https://gist.github.com/miku/6904419.
Nevertheless, in the context of OPs code, abs(len(s) - len(t)) > 1
really is faster.
Upvotes: 4
Reputation: 10667
It seems that the fastest way is
if 1 >= len(s) - len(t) >= -1:
print("string lengths differ by more than 1")
Indeed:
>>> %timeit abs(a) <= 1
1000000 loops, best of 3: 283 ns per loop
>>> %timeit 1 >= a >= -1
10000000 loops, best of 3: 198 ns per loop
Upvotes: 1