# Python (3 solutions: Recursive, Classic, Pythonic)

• 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]

• 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])"

• @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 :)

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

• @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.

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

• @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.

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

• I like the pythonic version :))))

• "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)))

?

• @keonkim

def reverse(s):

index = len(s)
words = []
while index:
index -=1
words.append(s[index])

return "".join(words)

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