Home > OS >  how to change an itteration to recursion and viseverse
how to change an itteration to recursion and viseverse

Time:12-11

i would like to change a function from itteration to recursion, here is the function

def differences(values):
    result = []
    for i in range(len(values) - 1):
        result.append(values [i 1] - values[i])
    return result

def palindrome(word):
    if len(word) <=1:
        return True
    if word[0] != word[-1]:
        return False
    return palindrome(word[1:-1])

CodePudding user response:

In pseudocode:

differences list =
  if list has < 2 elements result is empty list
  otherwise, 
      list = first, second, *rest
      result is [second - first]   differences([second, *rest])

Implementing this in python, you can elegantly use the new match statement.

Iteration:

palindrome str = 
   first = 0, last = len(str) - 1
   while first < last
       if str[first] != str[last] return false
       first  , last--
   return true

CodePudding user response:

The first function could be made recursive as follows:

def differences2(values, i = 1, res = []):
    if i < len(values):
        res.append(values[i] - values[i-1])
        return differences2(values, i   1, res)
    else:
        return res

The second could be made iterative like this:

def palindrome2(word):
    pointer = 0
    while 2 * pointer   1 <= len(word):
        if word[pointer] != word[-pointer-1]:
            return False
        pointer  = 1
    return True

The recursive implementation of this can be very compact:

def palindrome(word, i = 0):
    if 2 * i   1 <= len(word):
        return False if word[i] != word[-i-1] else palindrome(word, i = i   1)
    return True

As a side note: in general, while very elegant, I am always a little bit worried in implementing recursive solutions in Python - iterative one are more readable and robust (again, those are my 2 cents).

  • Related