Showing posts with label recursion. Show all posts
Showing posts with label recursion. Show all posts

Mar 24, 2020

Python Palindrome

Using Recursion

def isPalindrome(testVariable):
  print(testVariable)
  if len(testVariable) <= 1:
    return True
  
  length = len(testVariable)
  if testVariable[0] == testVariable[length-1]:
      return isPalindrome(testVariable[1:length-1])

  return False

a = isPalindrome('MADAM')
print(a)  ## True

Using normal way

def isPalindrome(testVariable):
  if testVariable == testVariable[::-1]:
    return True
  return False

a = isPalindrome('MADAM')
print(a)  ## True

Python recursion

def factorial(num):
    if num == 1:
       return num
    else:
       return num * factorial(num-1)

target = factorial(5)
print(target)  ## 120


def square(num):
    if num == 1:
      return num
    else:
      return square(num-1) + 2*num - 1

target = square(6)

print(target)  ## 36