Showing posts with label Python Programming Skills. Show all posts
Showing posts with label Python Programming Skills. Show all posts

Python Program to Find the Sum of Natural Numbers


# Python program to find the sum of natural numbers up to n where n is provided by user

# take input from the user
num = int(input("Enter a number: "))

if num < 0:
   print("Enter a positive number")
else:
   sum = 0
   # use while loop to iterate un till zero
   while(num > 0):
       sum += num
       num -= 1
   print("The sum is",sum)
Output

Enter a number: 16
The sum is 136
Here, we ask the user for a number and display the sum of natural numbers up to that number. We use while loop to iterate until the number becomes zero.
We could have solved the above problem without using any loops. From mathematics, we know that sum of natural numbers is given by n*(n+1)/2. We could have used this formula directly. For example, if n = 16, the sum would be (16*17)/2 = 136.

Python Program to Check Armstrong Number

An Armstrong number, also known as narcissistic number, is a number that is equal to the sum of the cubes of its own digits. For example, 370 is an Armstrong number since 370 = 3*3*3 + 7*7*7 + 0*0*0.



# Python program to check if the number provided by the user is an Armstrong number or not

# take input from the user
num = int(input("Enter a number: "))

# initialise sum
sum = 0

# find the sum of the cube of each digit
temp = num
while temp > 0:
   digit = temp % 10
   sum += digit ** 3
   temp //= 10

# display the result
if num == sum:
   print(num,"is an Armstrong number")
else:
   print(num,"is not an Armstrong number")
Output 1

Enter a number: 663
663 is not an Armstrong number
Output 2

Enter a number: 407
407 is an Armstrong number

Here, we ask the user for a number and check if it is an Armstrong number. We need to calculate the sum of cube of each digit. So, we initialize the sum to 0 and obtain each digit number by using the modulus operator %. Remainder of a number when it is divide by 10 is the last digit of that number. We take the cubes using exponent operator. Finally, we compare the sum with the original number and conclude that it is Armstrong number if they are equal.

Python Program to Print the Fibonacci sequence

A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8.... The first two terms are 0 and 1. All other terms are obtained by adding the preceding two terms. This means to say the nth term is the sum of (n-1)th and (n-2)th term.



# Program to display the Fibonacci sequence up to n-th term where n is provided by the user

# take input from the user
nterms = int(input("How many terms? "))

# first two terms
n1 = 0
n2 = 1
count = 2

# check if the number of terms is valid
if nterms <= 0:
   print("Plese enter a positive integer")
elif nterms == 1:
   print("Fibonacci sequence:")
   print(n1)
else:
   print("Fibonacci sequence:")
   print(n1,",",n2,end=', ')
   while count < nterms:
       nth = n1 + n2
       print(nth,end=' , ')
       # update values
       n1 = n2
       n2 = nth
       count += 1
Output

How many terms? 10
Fibonacci sequence:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
Here, we ask the user for the number of terms in the sequence. We initialize the first term to 0 and the second term to 1. If the number of terms is more than 2, we use a while loop to find the next term in the sequence by adding the preceding two terms. We then interchange the variables (update it) and continue on with the process.

Python Program to Find the Factorial of a Number

The factorial of a number is the product of all the integers from 1 to that number. For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720. Factorial is not defined for negative numbers and the factorial of zero is one, 0! = 1.



# Python program to find the factorial of a number provided by the user.

# take input from the user
num = int(input("Enter a number: "))
factorial = 1

# check if the number is negative, positive or zero
if num < 0:
   print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
   print("The factorial of 0 is 1")
else:
   for i in range(1,num + 1):
       factorial = factorial*i
   print("The factorial of",num,"is",factorial)
Output 1

Enter a number: -2
Sorry, factorial does not exist for negative numbers
Output 2

Enter a number: 7
The factorial of 7 is 5040
Here, we take input from the user and check if the number is negative, zero or positive using if...elif...else statement. If the number is positive, we use for loop and range() function to calculate the factorial.

Python Program to Check Leap Year


# Python program to check if the input year is a leap year or not

year = int(input("Enter a year: "))
if (year % 4) == 0:
   if (year % 100) == 0:
       if (year % 400) == 0:
           print("{0} is a leap year".format(year))
       else:
           print("{0} is not a leap year".format(year))
   else:
       print("{0} is a leap year".format(year))
else:
   print("{0} is not a leap year".format(year))
Output 1

Enter a year: 2000
2000 is a leap year
Output 2

Enter a year: 1775
1775 is not a leap year
In this program, we ask the user to input a year and check if it is a leap year or not. Leap years are those divisible by 4. Except those that are divisible by 100 but not by 400. Thus 1900 is not a leap year as it is divisible by 100. But 2000 is a leap year because it if divisible by 400 as well.

Python Program to Check if a Number is Odd or Even


# Python program to check if the input number is odd or even.
# A number is even if division by 2 give a remainder of 0.
# If remainder is 1, it is odd number.

num = int(input("Enter a number: "))
if (num % 2) == 0:
   print("{0} is Even".format(num))
else:
   print("{0} is Odd".format(num))
Output 1

Enter a number: 43
43 is Odd
Output 2

Enter a number: 18
18 is Even

Swap two numbers in python


# Python program to swap two variables provided by the user

x = input('Enter value of x: ')
y = input('Enter value of y: ')

# create a temporary variable and swap the values
temp = x
x = y
y = temp

print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
Output

Enter value of x: 5
Enter value of y: 10
The value of x after swapping: 10
The value of y after swapping: 5

Quadratic Equation in python

Quadratic equation expression:
 
d = b square of 2 - 4 x a x c
 
(-b + square of d)/ 2 x a and (- b - square of d)/2 x a 
 
 
 
# Solve the quadratic equation ax**2 + bx + c = 0
# Coeffients a, b and c are provided by the user

# import complex math module
import cmath

a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))

# calculate the discriminant
d = (b**2) - (4*a*c)

# find two solutions
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)

print('The solution are {0} and {1}'.format(sol1,sol2))
Output

Enter a: 1
Enter b: 5
Enter c: 6
The solutions are (-3+0j) and (-2+0j)
In this program, we ask the user for the coefficients of the quadratic equation. We have imported the cmath module to perform complex square root. First we calculate the discriminant and then find the two solutions of the quadratic equation.

binary search tree in python

bst.py
--------


class Node:
    def __init__(self,val):
        self.value=val
        self.leftchild=None
        self.rightchild=None
    def insert(self,data):
        if self.value== data:
            return False
        elif self.value>data:
            if self.leftchild:
                return self.leftchild.insert(data)
            else:
                self.leftchld = Node(data)
                return True
        else:
            if self.rightchild:
                return self.rightchild.insert(data)
            else:
                self.rightchild = Node(data)
                return True
    def find(self,data):
        if(self.value == data):
            return True
        elif self.value>data:
            if self.leftchild:
                return self.leftchild.find(data)
            else:
                self.leftchild=Node(data)
                return False
        else:
            if self.rightchild:
                return self.rightchild.find(data)
            else:
                self.rightchild = Node(data)
                return False
   
    def preorder(self):
        if self:
            print (str(self.value))
            if self.leftchild:
                self.leftchild.preorder()
            if self.rightchild:
                self.rightchild.preorder()
             

    def postorder(self):
        if self:
            if self.leftchild:
                self.leftchild.postorder()
            if self.rightchild:
                self.rightchild.postorder()
            print (str(self.value))


    def inorder(self):
        if self:
            if self.leftchild:
                self.leftchild.inorder()
            print (str(self.value))

            if self.rightchild:
                self.rightchild.inorder()

class Tree:
    def __init__(self):
        self.root=None

    def insert(self,data):
        if self.root:
            return self.root.insert(data)
        else:
            self.root=Node(data)
            return True
       
    def find(self,data):
        if self.root:
            return self.root.find(data)
        else:
            return False

    def preorder(self):
        print("PreOrder")
        self.root.preorder()

    def postorder(self):
        print("PostOrder")
        self.root.postorder()

    def inorder(self):
        print("inOrder")
        self.root.inorder()

pyton shell

>>> from bst import Tree
>>> bst=Tree()
>>> bst.insert(10)
True
>>> bst
<bst.Tree instance at 0x02B42698>
>>> print bst
<bst.Tree instance at 0x02B42698>
>>> bst.insert(14)
True
>>> bst.preorder()
PreOrder
10
14
>>> bst.postorder()
PostOrder
14
10
>>> bst.inorder()
inOrder
10
14
>>>

single linked list reverse in python

 
 
class Node:
    def __init__(self,data):
        self.data = data
        self.next= None



class List:
    def __init__(self):
        self.firstNode = Node(None)

    def inserthead(self,newnode):
        if not self.firstNode.next:
            newnode.next = None
            self.firstNode.next = newnode
        else:
            newnode.next = self.firstNode.next
            self.firstNode.next= newnode


   def __show(self,start):
   if start:
       print start.data
       self.__show(start.next)
 
 
    def printlist(self):
        self.__show(self.firstNode)

    def __reverte_recursive(self,node):
        temp = None
        if not node.next: return node
        else:
            temp = self.__reverte_recursive(node.next)
            node.next.next= node
            node.next = None
        return temp

    def reverte_list1(self):
        self.firstNode=self.__reverte_recursive(self.firstNode)

    def __reverte_iterative(self,node):
        temp = None
        previous = None
        while node and node.next:
            temp = node.next
            node.next= previous
            previous = node
            node = temp
        return previous
    def reverte_iterative(self):
        self.firstNode=self.__reverte_iterative(self.firstNode)

nodeA = Node("A")
nodeB = Node("B")
nodeC = Node("C")
nodeD = Node("D")
nodeE = Node("E")


list1= List()

list1.inserthead(nodeA)
list1.inserthead(nodeB)
                           class Node:
    def __init__(self,data):
        self.data = data
        self.next= None



class List:
    def __init__(self):
        self.firstNode = Node(None)

    def inserthead(self,newnode):
        if not self.firstNode.next:
            newnode.next = None
            self.firstNode.next = newnode
        else:
            newnode.next = self.firstNode.next
            self.firstNode.next= newnode


    def __show(self,start):
        if start.next:
            print start.data
            self.__show(start.next)

    def printlist(self):
        self.__show(self.firstNode)

    def __reverte_recursive(self,node):
        temp = None
        if not node.next: return node
        else:
            temp = self.__reverte_recursive(node.next)
            node.next.next= node
            node.next = None
        return temp

    def reverte_list1(self):
        self.firstNode=self.__reverte_recursive(self.firstNode)

    def __reverte_iterative(self,node):
        temp = None
        previous = None
        while node and node.next:
            temp = node.next
            node.next= previous
            previous = node
            node = temp
        return previous
    def reverte_iterative(self):
        self.firstNode=self.__reverte_iterative(self.firstNode)

nodeA = Node("A")
nodeB = Node("B")
nodeC = Node("C")
nodeD = Node("D")
nodeE = Node("E")


list1= List()

list1.inserthead(nodeA)
list1.inserthead(nodeB)
list1.inserthead(nodeC)
list1.inserthead(nodeD)
list1.inserthead(nodeE)


print "list"
list1.printlist()
print "list reverse"
list1.reverte_list1()
list1.printlist()
list1.reverte_iterative()
print "list reverse reverse"
list1.printlist()
 
O/P

None
E
D
C
B
list reverse
A
B
C
D
E
list reverse reverse
E
D
C
B

Python Recursion

Recursion is the process of defining something in terms of itself. A physical world example would be to place two parallel mirrors facing each other. Any object in between them would be reflected recursively.

Python Recursive Function

We know that in Python, a function can call other functions. It is even possible for the function to call itself. These type of construct are termed as recursive functions.
Following is an example of recursive function to find the factorial of an integer. Factorial of a number is the product of all the integers from 1 to that number. For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.

Example of recursive function


# An example of a recursive function to
# find the factorial of a number

def recur_fact(x):
   """This is a recursive function
   to find the factorial of an integer"""

   if x == 1:
       return 1
   else:
       return (x * recur_fact(x-1))


num = int(input("Enter a number: "))
if num >= 1:
   print("The factorial of", num, "is", recur_fact(num))
Output

Enter a number: 4
The factorial of 4 is 24
Explanation
In the above example, recur_fact() is a recursive functions as it calls itself. When we call this function with a positive integer, it will recursively call itself by decreasing the number. Each function call multiples the number with the factorial of number-1 until the number is equal to one. This recursive call can be explained in the following steps.
recur_fact(4)              # 1st call with 4
4 * recur_fact(3)          # 2nd call with 3
4 * 3 * recur_fact(2)      # 3rd call with 2
4 * 3 * 2 * recur_fact(1)  # 4th call with 1
4 * 3 * 2 * 1              # retrun from 4th call as number=1
4 * 3 * 2                  # return from 3rd call
4 * 6                      # return from 2nd call
24                         # return from 1st call
Our recursion ends when the number reduces to 1. This is called the base condition. Every recursive function must have a base condition that stops the recursion or else the function calls itself infinitely. We must avoid infinite recursion.

Advantages of recursion

  1. Recursive functions make the code look clean and elegant.
  2. A complex task can be broken down into simpler sub-problems using recursion.
  3. Sequence generation is easier with recursion than using some nested iteration.

Disadvantages of recursion

  1. Sometimes the logic behind recursion is hard to follow through.
  2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
  3. Recursive functions are hard to debug.

Python Program to Check Prime Number

A positive integer greater than 1 which has no other factors except 1 and the number itself is called a prime number. 2, 3, 5, 7 etc. are prime numbers as they do not have any other factors. But 6 is not prime (it is composite) since, 2 x 3 = 6.

Source Code


# Python program to check if the input number is prime or not

# take input from the user
num = int(input("Enter a number: "))

# prime numbers are greater than 1
if num > 1:
   # check for factors
   for i in range(2,num):
       if (num % i) == 0:
           print(num,"is not a prime number")
           print(i,"times",num//i,"is",num)
           break
   else:
       print(num,"is a prime number")
       
# if input number is less than
# or equal to 1, it is not prime
else:
   print(num,"is not a prime number")
Output 1

Enter a number: 407
407 is not a prime number
11 times 37 is 407
Output 2

Enter a number: 853
853 is a prime number

In this program, user is asked to enter a number and this program check whether that number is prime or not. Numbers less than or equal to 1 are not prime numbers. Hence, we only proceed if the num is greater than 1. We check if num is exactly divisible by any number from 2 to num - 1. If we find a factor in that range, the number is not prime. Else the number is prime.
We can decrease the range of numbers where we look for factors. In the above program, our search range is from 2 to num - 1. We could have used the range, [2, num / 2] or [2, num ** 0.5]. The later range is based on the fact that a composite number must have a factor less than square root of that number. Otherwise the number is prime.