Any fast Python code?


  • 4
    Y

    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)

  • 6
    S

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


  • 0
    E

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


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

    58ms


  • 0
    L
    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
        return total
    

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


  • 0
    R
    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)
            return total

  • 0
    Y

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


  • 1
    A
        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


  • 0
    S

    @Alpha.Monkey said in Any fast Python code?:

        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.


Log in to reply
 

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