Home > front end >  To make a recursive function with challenging constraints
To make a recursive function with challenging constraints

Time:08-09

I would like to make a function with an input string, and returns it in reverse order.

However, the challenge is that the function

  • must use a recursive function
  • is without using for-loop
  • is without any operators
  • is without list slicing

This is my attempt which does not work:

def reverse(s: str) -> str
    if len(s) == 0:
       return None

    return

How do I use the recursive function here to reverse order? I tried to think of it but i'm new to recursive calls

CodePudding user response:

"without using for loops or any operators or list slicing" seems like a weird requirement, but the following function will do:

>>> def reverse(s):
...     head, *tail = s
...     if tail:
...         return f'{reverse(tail)}{head}'
...     else:
...         return head
... 
>>> reverse('abcdef')
'fedcba'

In the scope of lexical analysis, * is regarded as an operator, so we can replace head, *tail = s with the following:

import re

def reverse(s):
    head, tail = re.split('(?!^)', s, maxsplit=1)
    [...]

Or, alternatively:

def reverse(s):
    __, head, tail = s.partition(next(iter(s))
    [...]

Or, yet another alternative:

def reverse(s):
    s = iter(s)
    head, tail = next(s), ''.join(s)
    [...]

CodePudding user response:

Edit: I have removed the ' ' operator, and also the lstrip() which does not work on repeated characters in the string (thanks @philosofool)

Here's one way to do it without list slicing. And to clarify s[0] is list indexing not list slicing, correct?

def reverse(s):
    if len(s)==1:
        return s
    else:
        s1 = list(s)
        del s1[0]
        return ''.join([reverse(''.join(s1)), s[0]])
    
reverse('abccdefg')

output is

'gfedccba'

CodePudding user response:

This is not actually a solution. It meets all the requirements except the recursive one. It's a nice, purely functional solution, but not what OP asked for. Leaving it up in case anyone is interested....

from functools import reduce

def reverse_string(string):
    return reduce(lambda x, y: f'{y}{x}', string)

CodePudding user response:

Using only functions

def reverse(strng, pos):
    if pos:
         next_pos = map(lambda x: x, range(pos,0,-1))
         next(next_pos) # skip first
         return ''.join((strng[pos],reverse(strng, next(next_pos)))
         
    else:
        return strng[pos]

Another one inspired by @Ecin

def reverse(strng : str):
   def inner(strng : list):
      return ''.join((strng.pop(), inner(strng) if strng else ''))
   return inner(list(strng))
  • Related