Sunday, 15 April 2018

Python - scope and recursive function - Day 25(4 days later)

  • this will explain the variable's scope.
  •   
    #take way:read the document related to local,nonlocal,global
    #know what is LEGB - Local Enclosing Global Builtins
    #below example will illustrate the variable and the scope of it
    
    
    # def spam1():
    #     def spam2():
    #         def spam3():
    #             z = ' even more spam'
    #             print('3 {}'.format(locals()))
    #             return z
    #         y = 'more spam '
    #         y+= spam3()
    #         print('2 {}'.format(locals()))
    #         return y
    #     x = 'spam '
    #     x+= spam2()
    #     print('1 {}'.format(locals()))
    #     print(x)
    
    def spam1():
        def spam2():
            def spam3():
                # y = 'test'
                z = ' even' + y
                print('3 {}'.format(locals()))
                return z
            y = ' more'+x
            y+= spam3()
            print('2 {}'.format(locals()))
            return y
        x = 'spam'
        x+= spam2()
        # we can't write like this x = 'spam' + spam2(),since spam2 function first expects x
        # it will throw unreferenced variable error if we code like that
        print('1 {}'.format(locals()))
        print(x)
    
    print(spam1())
    print(locals())
    print(globals())
     
    
  • this will explain how the recursive funtion can be made use of
  •   
    #recursive function,function that calls itself again and again
    #factorial
    
    def factorial(n):
        result = 1
        if n>1:
            for i in range (1,n+1):
                result = result * i
        return result
    
    def factorialrec(n):
        #n factorial can also be defined as n * (n-1)!
        if n<=1:
            return 1
        else:
            return n * factorialrec(n-1)
    
    def fibonaccirec(n):
        # Fn = Fn-1 + Fn-2
        if n<2:
            return n
        else:
            return fibonaccirec(n-1)+fibonaccirec(n-2)
    
    def fibonacci(n):
        if n == 0:
            return 0
        if n == 1:
            return 1
        elif n==2:
            return 1
        else:
            n_minus1 = 1
            n_minus2 = 0
            for i in range(1,n):
                result = n_minus1+n_minus2
                n_minus2 = n_minus1
                n_minus1 = result
            return result
    
    
    
    
    # for x in range (1,130):
    #     print(x , factorial(x))
    
    # for x in range (1,130):
    #     print(x , factorialrec(x))
    
    # here use of the recursive funtion in calculating the fibonaaci
    #might slow downb the process,so we can go for direct method
    
    # for x in range (1,36):
    #     print(x , fibonaccirec(x))
    
    #below direct method will be fast
    for x in range (1,36):
        print(x , fibonacci(x))
     
    

    No comments:

    Post a Comment