Tuesday, 28 January 2020

Recursive program

def fib(n1,n2,n):
    if n==0:
        return
    res=n1+n2
    print(res)
    fib(n2,res,n-1)
def r_fact(n):
    if n==1:
        return n
    else:
        return n*r_fact(n-1)

def is_palindrome(s):
    if len(s) < 1:
        return True
    else:
        if s[0] == s[-1]:
            return is_palindrome(s[1:-1])
        else:
            return False


print("\n  a- fibonacci \n b- factorial \n c- palindrome")
ch=input("enter choice a,b,c")
if ch=='a':
    a=0
    b=1
    n=int(input("How many numbers to be printed: "))
    print(a)
    print(b)
    fib(a,b,n-2)
elif ch=='b':
    #Main program
    n=int(input("enter n"))
    if n==0:
        print("factorial is 1")
    elif n<0:
        print("factorial does not exist")
    else:
        print("factorial is :",r_fact(n))
elif  ch=='c':
    a=str(input("Enter string:"))
    if(is_palindrome(a)==True):
        print("String is a palindrome!")
    else:
        print("String isn't a palindrome!")


1 comment: