Saturday, June 25, 2011

Sample Python Programs

In this post I wish to add some basic and simple programs in Python which are experimented by me. This will be helpful to beginners of Python language. This examples are for script mode execution.

Before directly go to the program, I want to explain about assert function. Its a function generally used to check the correctness of another function. Programmers generally use this function to check the return value of a function. It checks the expression, and if the expression is true it doesn't perform any action. Otherwise if the expression is false, we get assertion error.

In my sample programs, I used the assertion function. If you run this program it will not display anything,because the code returns expected values. If you want to experiment on it insert print() in the functions and you can understand what is happening inside the programs. After modification,if you get an assertion error it means the code returns wrong values.

Sample 1 :  This program checks whether a given number is a factorial of any number.


def is_factorial(n):
    i=1
    f=1
    while i<=n:
        f=f*i
        if f==n:
            return 1
        if f>n:
            break
        i=i+1 
    return 0
  
def main():
    assert(is_factorial(6))
    assert(not is_factorial(100))
    assert(is_factorial(1307674368000L))
    assert(is_factorial(120))
if __name__=='__main__':
    main()

Sample 2 : This program checks whether the given tuple is in ascending order. Don't use sort/sorted functions.

def is_sorted(a):
   x=a
   i=1
   while i<len(x):
       if x[i-1]>x[i]:
           return 0
       i=i+1
   return 1 

def main():
    assert(is_sorted((10, 20, 30, 32, 33)))
    assert(is_sorted((1,)))
    assert(is_sorted((1,2)))
    assert(not is_sorted((2, 1)))
    assert(not is_sorted((1, 4, 7, 8, 6)))
    assert(not is_sorted((10, 20, 30, 25, 34, 45, 67)))
if __name__=='__main__':
    main()

Note that these are not professional codes and you can find out more simple and efficient codes for these problems. Five more samples will be published in my next post.

Thanks

AJAY

No comments:

Post a Comment

Comments with advertisement links will not be published. Thank you.