Home > Enterprise >  I want to make a recursive function without using for loops or any operators or list slicing that re
I want to make a recursive function without using for loops or any operators or list slicing that re

Time:08-08

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'

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]

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'
  • Related