4 ms·
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_p
by bastiaanus 13y ago
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.
- beat 13y agoI 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?
- bastiaanus 13y agoI don't know if it is against the rules, my approach was a recursive function.
- deleted 13y ago[deleted]
- beat 13y agoWell, 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.
- deleted 13y ago[deleted]
- btilly 13y agoYup.
- hiker 13y agoNot to mention, strings are immutable in Python.
- nerfhammer 13y agoYou can't even assign by index with strings str[0] = ... will trigger an exception
- gameguy43 13y agoWoops--yeah, that's pretty bad. Somehow this one made it through testing. Fixing!
- column 13y agoI would answer : def reverse(str): return str[::-1] Am I missing the point ?
- prezjordan 13y agoThat creates a new string (the one returned) :)
- freework 13y agoThats what I would do. Then again, I always get rejected when I do these type of interviews...
- eDice 13y agodef reverse(string='abc123'): for pos in xrange(-len(string)+1, 1): string += string[abs(pos)] return string[len(string)/2:] Fair?