Hacker Newsnew | past | comments | ask | show | jobs | submit | bastiaanus's commentslogin

I am at the "write a function that reverses a string without creating a new string" question and this is the answer on the site:

  def reverse(str):
    left_ptr = 0
    right_ptr = len(str) - 1
    middle = len(str) / 2
    while left_ptr <= middle:
        # swap
        temp = str[left_ptr]
        str[left_ptr] = str[right_ptr]
        str[right_ptr]= temp
wouldn't this create an infinite loop? You're never incrementing / decrementing left_ptr or right_ptr.


Not to mention, strings are immutable in Python.


You can't even assign by index with strings

str[0] = ... will trigger an exception


I see that and want to do it by appending backwards off the end of the string, then move the pointer to the new beginning. Is that "creating a new string"? Or just making a poopy on the floor for the garbage collector?

"Double the length of the old string and then cut it in half" isn't against the rules, right?


I don't know if it is against the rules, my approach was a recursive function.


[deleted]


Well, yeah. That's the expected way to do it.

My way has the benefit of bending the rule without breaking it. After all, we weren't told to not allocate memory, we were told to not create another string.


I would answer :

    def reverse(str):
        return str[::-1]
Am I missing the point ?


That creates a new string (the one returned) :)


Thats what I would do. Then again, I always get rejected when I do these type of interviews...


    def reverse(string='abc123'):
        for pos in xrange(-len(string)+1, 1):
            string += string[abs(pos)]

        return string[len(string)/2:]
Fair?


Woops--yeah, that's pretty bad. Somehow this one made it through testing. Fixing!


Yup.


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: