0

I am trying to reverse a list using a recursive function. Unfortunatley I am fairly new to recursion. Is this possible? That is my code thus far

def stringRev (word):
    worLen = len(word)
    if worLen == 1:
        return word
    return (word[-1]) + stringRev(word[:-1])

listWord = ["hey", "there", "jim"]
print(stringRev(listWord))
1
  • 3
    Your function works. It's the input to the function which is wrong. Commented Mar 1, 2013 at 17:07

3 Answers 3

4

Your problem is that (word[-1]) is a string, not a list. So you are trying to add/concatenate a string and a list. I changed that expression to [word[-1]] to create a list.

>>> def stringRev (word):
...     worLen = len(word)
...     if worLen == 1:
...         return word
...     return [word[-1]] + stringRev(word[:-1])
... 
>>> listWord = ["hey", "there", "jim"]
>>> print(stringRev(listWord))
['jim', 'there', 'hey']
>>> 

PS. It would be helpful if you included the error you received when running your code: TypeError: Can't convert 'list' object to str implicitly

Sign up to request clarification or add additional context in comments.

Comments

3

To reverse the order of the elements of the list, change:

return (word[-1]) + stringRev(word[:-1])

to

return [word[-1]] + stringRev(word[:-1])

(note the square brackets).

The problem is that you are trying to concatenate a string (word[-1]) with a list (word[:-1]).

The problem is that your function is expecting a single word, yet you're calling it with a list of words.

If you call it as follows, you'll see that it works just fine:

for word in ["hey", "there", "jim"]:
    print(stringRev(word))

Or, if you wish to store the reversed strings in a list:

l = [stringRev(w) for w in ["hey", "there", "jim"]]

The one corner case where your function would fail is the empty string. I don't know whether that's a valid input, so it could be a non-issue (but trivial to fix nonetheless).

1 Comment

Im trying to reverse the order of the elements
1

If you want it done in Python:

reversed(listWord)

assuming word is a list or a tuple

http://docs.python.org/2/library/functions.html#reversed

And to get a list:

list(reversed(listWord))

should work

But if you want an algorithm, I guess reversed is not your friend !

1 Comment

Note that reversed doesn't return a string. It gives you an iterable object. For that reason, you'll often see s[::-1] to reverse a sequence as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.