Write a recursive function that computes the reverse of a string
OO I like this one!!!
here's what I tried so far (Python): newS='' def reverse(s): if s=='': return newS else: newS=newS+s[-1] return reverse(s[:-1]) doesn't work, but maybe you can tweak it?
try with s[::-1]
Also what language?
I would assume you would do a character read and just call the function until it's in and out of an array. so you would do a for loop from 0 to string.length and then do it backwards.
mine doesn't work because newS is not defined in the function environment, so the recursive call registers that value as undefined the second time trough the loop.
here is my latest try: def rev(s): if len(s)!=0: newS='' newS=newS+s[-1] s=s[:-1] #print statement to illustrate what is happening to s and newS print newS, s return rev(s) I know what my problem is I just can't fix it. I don't know how or where to initiate the value newS. Where I have it it resets it to the empty string on every iteration. Still thinking how to fix that.
@Daniel_Añez your method, though it works, is not using iteration
@TuringTest I meant, within your function. Anyway, this works if you introduce the string like an object with quotation marks: def reverse(s): result =s[::-1] return result I couldn't figure out how to convert the input into a valid string within the function, str() doesn't work
#!/usr/bin/python def reverse( string ): if( len( string ) == 0 ): return string char = string[ 0 ] return( reverse( string[ 1: ] ) + char ) if( __name__ == "__main__" ): print reverse( "Hello World" )
Join our real-time social learning platform and learn together with your friends!