Python 3 solutions: Recursive, Classic, Pythonic


  • 14
    class Solution(object):
        def reverseString(self, s):
            l = len(s)
            if l < 2:
                return s
            return self.reverseString(s[l/2:]) + self.reverseString(s[:l/2])
    
    
    class SolutionClassic(object):
        def reverseString(self, s):
            r = list(s)
            i, j  = 0, len(r) - 1
            while i < j:
                r[i], r[j] = r[j], r[i]
                i += 1
                j -= 1
    
            return "".join(r)
    
    class SolutionPythonic(object):
        def reverseString(self, s):
            return s[::-1]
    

  • 0
    G

    class Solution(object):
    def reverseString(self, s):
    l = len(s)
    if l < 2:
    return s
    return self.reverseString(s[l/2:]) + self.reverseString(s[:l/2])

    The last line may be "return self.reverseString(s[l//2:]) + self.reverseString(s[:l//2])"


  • 2

    @Gclalaboo
    Leetcode supports only python 2.7.12, so there is no "//" operator. If you was confused by topic title Python 3 solutions, 3 goes to solutions count :)


  • 0

    @viakondratiuk Even math.floor(l/2) isn't there in leetcode's python version ?


  • 1

    @hanumegowda
    I guess it should be here, but floor will return you float. It's not what we need, / is the best option. And using floor probably should be slower.


  • 0

    @viakondratiuk Ohh...yeah....typecasting it to int using int() is better ?


  • 0

    @hanumegowda
    Typecasting in this case is not what we need. It's too much action. / in python2 is an integer division if both inputs are integers, that' what we have in our case. Just compare 7 / 2 = 3 and int(math.floor(7/2)) . It even looks scary.


  • 0

    @viakondratiuk no, no...I only meant int(l/2) :)


  • 0

    I like the pythonic version :))))


  • 0
    K

    "pythonic" code should speak for itself. [::-1] doesn't seem that intuitive. (I guess I am talking about the same reason why python doesn't have ++ operator)
    why not just

    def pythonic(s):
        return "".join(list(reversed(s)))
    
    
    

    ?


Log in to reply
 

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