Define a function called reverse that takes a string textand returns that string in reverse. For example: reverse("abcd") should return "dcba". You may not use reversed or [::-1] to help you with this. You may get a string containing special characters (for example, !, @, or #). Above is a problem I saw at codeacademy.com This is the code dat I wrote. Can any1 tell me what is wrong def reverse(text): reversed_string = "" for i in range(len(text)-1,0): reversed_string += text[i] print reversed_string return reversed_string reverse("sdgsdfsdf")
What's the output of your code? Are you getting an error?
for i in range(len(text)-1,0): Should probably have a third argument, the step value, -1. BTW, recursion will do this nicely.
yes you could probably get some extra credit by using recursion or implementing a LIFO stack
thanks the -1 step worked
Recursive solution: reverse(xs) = if (empty(xs)) return nothing else return reverse(rest(xs)) + head(xs) Note: head(xs) = xs[0] rest(xs) = xs[1] + xs[2] + ... + xs[size(xs)-1], e.g., in C++: xs.substr(1) Of course, this is a bad use of recursion. A loop-based solution: reverse(xs) = result = nothing for x in xs result = x + result return result Note how the above simple loop solution is similar to the recursive solution; the "plux x" part is like the "+ head(x)", and the body of the loop is like the "recursive(rest(xs))" part. A possibly more efficient solution: reverse(xs) = size = len(xs) half = size/2 for i = 0 to half-1 swap(xs[i], size-i-1)
thanks
Join our real-time social learning platform and learn together with your friends!