Ask your own question, for FREE!
Computer Science 18 Online
OpenStudy (anonymous):

Write a recursive function that computes the reverse of a string

OpenStudy (konradzuse):

OO I like this one!!!

OpenStudy (turingtest):

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?

OpenStudy (anonymous):

try with s[::-1]

OpenStudy (konradzuse):

Also what language?

OpenStudy (konradzuse):

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.

OpenStudy (turingtest):

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.

OpenStudy (turingtest):

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.

OpenStudy (turingtest):

@Daniel_Añez your method, though it works, is not using iteration

OpenStudy (anonymous):

@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

OpenStudy (rsmith6559):

#!/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" )

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!