0

If I need to implement string reverse by myself in Python 2.7 other than using system library, wondering if any more efficient solutions? I tried my code runs slow for a very long string (e.g. a few thousand characters). Thanks.

For string reverse I mean, for example, given s = "hello", return "olleh".

def reverseString(self, s):
    """
    :type s: str
    :rtype: str
    """
    if not s:
        return ''
    temp = []
    result=''
    for i in range(len(s)-1,-1,-1):
        result += s[i]
    return result

regards, Lin

5
  • 1
    I understand that this is the reason why you try to avoid explicit loops in python. Commented Sep 18, 2016 at 4:57
  • 1
    I'm curious as to why you would need to implement this yourself, what's your reason? Commented Sep 18, 2016 at 5:02
  • 1
    When you say slow, how slow do you mean? I'm getting reasonable performance up to 50,000 length strings (less than a quarter of a second). Commented Sep 18, 2016 at 5:39
  • 1
    Also, try using xrange instead of range Commented Sep 18, 2016 at 6:04
  • 1
    Has anybody tried with generators? Commented Sep 18, 2016 at 6:20

3 Answers 3

6

Try this:

def reverseString(self, s):
    return s[::-1]
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Ian, your solution is pretty cool, I think the issue of my code is when executing result += s[i], a new string will be created other than appending to existing string, since Python str object is constant?
Likely? Why not completely? :)
The 'ol double colon one-liner... A timeless Python classic! Does seem to copy the string.
3

Try recursion

def reverse(str):
    if str == "":
        return str
    else:
        return reverse(str[1:]) + str[0]

2 Comments

This could be very slow depending on the size of the string and could end up breaking the max recursion limit given the inputs could be thousands of characters long.
@shuttle87, agree with you. :)
2

EDIT: Actually, I was mistaken

I did a rough-and-dirty test comparing the two functions and the complexity looks to be the same: linear

enter image description here

It seems that since Python 2.4, for CPython, there has been an optimisation avoiding the quadratic behavior. See the following answer to a similar question:

https://stackoverflow.com/a/37133870/5014455

What I said below is outdated for Python 2.7.

This is going to be O(n^2) because strings are immutable in Python so:

result += s[i]

Will touch ever element in the resulting string every iteration in the loop. It will be faster to build up a mutable container (e.g. a list) of individual characters and then "".join them at the end.

def reverseString(s):
    """
    :type s: str
    :rtype: str
    """
    if not s:
        return ''
    result = []
    for i in xrange(len(s)-1,-1,-1):
        result.append(s[i])
    return "".join(result)

3 Comments

Thanks juanpa.arrivillaga, your solution is pretty cool, I think the issue of my code is when executing result += s[i], a new string will be created other than appending to existing string, since Python str object is constant?
@LinMa The most Pythonic solution is using slice notation (string[::-1]) But I'm not sure what restrictions you are putting on yourself for making this function. If using reversed is "cheating" then maybe slice notation would be too.
Thanks for all the help juanpa.arrivillaga, mark your reply as answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.