Any fast Python code?

• Hi, I come up with a Python code using reduce.
It costs 75ms, but from the distribution detail, I can see someone get even faster Python code.
Can anyone share a faster implementation?

``````class Solution:
# @param s, a string
# @return an integer
def titleToNumber(self, s):
l = list(s)
l.insert(0,0)
return reduce(lambda x,y: 26*x+ord(y)-64, l)``````

• how about this: `return reduce(lambda x, y: 26*x+ord(y)-64, s, 0)`

• wonderful answer…but I can't find a faster way

• ``````def titleToNumber(self, s):
if len(s) == 1:
return ord(s) - 64
return ord(s[-1]) - 64 + self.titleToNumber(s[:-1]) * 26
``````

58ms

• ``````def titleToNumber(self, s):
def _map(ch):
chn = ord(ch)
assert chn >= ord('A') and chn <= ord('Z')
return chn - ord('A') + 1
base = 1
total = 0
constantbase = ord('Z') - ord('A') + 1
for i in range(len(s)):
total += _map(s[len(s) - i - 1]) * base
base *= constantbase
``````

52ms, but I don't think those measurements are good enough such that you can compare it on that level...

• ``````class Solution:
# @param s, a string
# @return an integer
def titleToNumber(self, s):
total=0
for i in range(0,len(s)):
total+=(ord(s[i])-64)*pow(26,len(s)-i-1)

• Why use l.insert(0,0)? It seemed would still work without it.

• ``````    s_len = len(s) - 1
ret = 0
for idx, char in enumerate(s):
ret += (ord(char) - 64) * 26 ** (s_len - idx)

return ret
``````

39 ms

• ``````    s_len = len(s) - 1
ret = 0
for idx, char in enumerate(s):
ret += (ord(char) - 64) * 26 ** (s_len - idx)

return ret
``````

39 ms

Second this. Runs slightly faster.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.