python - Why is S == S[::-1] faster than looping? -
why pythonic way of checking if string, s
, palindrome -- s == s[::-1]
-- faster following implementation?
i = 0 j = len(s) - 1 while < j: if s[i] != s[j]: return false += 1 j -= 1 return true
because python code compiled bytecode, interpreted. that's going lot slower creating new reversed string in c code, comparing string string more c code.
note both algorithms o(n) complexity; python code executes @ 1/2 n iterations, , string reversal version makes @ 2 n iterations, asymptotically speaking doesn't make difference.
since both algorithms o(n) linear approaches, matters constant cost, how time each iteration takes. fixed cost vastly lower s == s[::-1]
.
Comments
Post a Comment