r/Python•
OhMoscow

How to write a simple recursive function?

removed: Learning

[removed]

Posted Oct 27, 2016, 3:19 PM UTC

07
KimPeek•

r/learnpython

>>> some_string = 'abcde'
>>> print(some_string[::-1])
edcba

I think you need to research the word 'recursion' a bit, enough to define it at least.

2
OhMoscowOP•

I get recursive functions call themselves and keep running until the process is complete. I'd like to learn how to reverse a string using recursion, i know how to use the [::-1], but that's not what I am looking for. We're going over it in class right now, and I don't really understand the logic of it so I thought seeing it on an example problem we were given would be useful

1
Nater5000•

This is an example of a recursive way of testing if a string is the same reversed or not. Try to work off of this:

def reverse(s):
  if len(s) == 1 or len(s) == 0:
    return True
  if s[0] == s[-1]:
    return reverse(s[1:-1])
  else:
    return False
2
OhMoscowOP•

this doesn't output anything, I think it is stuck in a loop. would removing the else retunr false fix the problem

1
Nater5000•

Sorry, the stopping conditions should have been if len(s) == 1 or 0. I made the edit.

I will also suggest you write out how this function works on paper or something. Removing the "else: return False" statement would destroy this function. The recursion occurs at the line

return reverse(s[1:-1])

So focus your attention on what is happening there.

1
rzzzwilson•

Ask this in r/learnpython. As the sidebar says:

If you are about to ask a question, please
consider [r/learnpython](/r/learnpython). Homework-style
questions will be removed, and you'll be
encouraged to post there instead.
1
aphoenixMODreticulated•

Hi there, from the r/Python mods.

We have removed this post as it is not suited to the r/Python subreddit proper, however it should be very appropriate for our sister subreddit r/LearnPython. We highly encourage you to re-submit your post over on there.

The reason for the removal is that r/Python is more-so dedicated to discussion of Python news, projects, uses and debates. It is not designed to act as Q&A or FAQ board. The regular community can get disenchanted with seeing the 'same, repetitive newbie' questions repeated on the sub, so you may not get the best responses over here.

However, on r/LearnPython the community is actively expecting questions from new members, and are looking to help. You can expect far more understanding, encouraging and insightful responses over there. Whatever your question happens to be getting help with Python, you should get good answers.

If you have a question to do with homework or an assignment of any kind, please make sure to read their sidebar rules before submitting your post. If you have any questions or doubts, feel free to reply or send a modmail to us with your concerns.

Warm regards, and best of luck with your Pythoneering!

1