Interview-Prep icon indicating copy to clipboard operation
Interview-Prep copied to clipboard

Error on reverse string exercise

Open ZuZuD opened this issue 8 years ago • 0 comments

There's an error with your code reversed

def reverse(s):
    new_str = ""
    for i in range(len(s)):
        new_str += s[i*-1]
    return new_str

This return

reverse('choco')
'cocoh'
reverse('cats')
'csta'

And it's wrong because python Index start at 0 and 0*-1 = 0

A workaround could be

def reverse(s):
     new_str = ""
     for i in range(len(s)):
         if i == 0:
             new_str += s[-1]
         else:
             new_str += s[(i+1)*-1]         
     return new_str

ZuZuD avatar Jan 31 '17 16:01 ZuZuD