Showing posts with label Functions. Show all posts
Showing posts with label Functions. Show all posts

program to print all Prime numbers in an Interval

def prime(x, y):

prime_list = []

for i in range(x, y):

if i == 0 or i == 1:

continue

else:

for j in range(2, int(i/2)+1):

if i % j == 0:

break

else:

prime_list.append(i)

return prime_list

starting_range = 2

ending_range = 7

lst = prime(starting_range, ending_range)

if len(lst) == 0:

print("There are no prime numbers in this range")

else:

print("The prime numbers in this range are: ", lst)


Program for compound interest

def compound_interest(principle, rate, time):

Amount = principle * (pow((1 + rate / 100), time))

CI = Amount - principle

print("Compound interest is", CI)

compound_interest(10000, 10.25, 5)


Pattern Printing

def Pattern(line):

pat=""

for i in range(0,line):

for j in range(0,line):

if ((j == 1 and i != 0 and i != line-1) or ((i == 0 or

i == line-1) and j > 1 and j < line-2) or (i == ((line-1)/2)

and j > line-5 and j < line-1) or (j == line-2 and

i != 0 and i != line-1 and i >=((line-1)/2))):

pat=pat+"#"

else:

pat=pat+" "

pat=pat+"\n"

return pat

line = 7

print(Pattern(line))


Program for Number of stopping station problem

def stopping_station( p, n):

num = 1

dem = 1

s = p

while p != 1:

dem *= p

p-=1

t = n - s + 1

while t != (n-2 * s + 1):

num *= t

t-=1

if (n - s + 1) >= s:

return int(num/dem)

else:

return -1

num = stopping_station(4, 12)

if num != -1:

print(num)

else:

print("Not Possible")


Check if Binary representation is Palindrome

def binaryPallindrome(num):

binary = bin(num)

binary = binary[2:]

return binary == binary[-1::-1]

if __name__ == "__main__":

num = 9

print (binaryPallindrome(num))


Check whether a number has consecutive 0’s in the given base or not

def hasConsecutiveZeroes(N, K):

z = toK(N, K)

if (check(z)):

print("Yes")

else:

print("No")

def toK(N, K):

w = 1

s = 0

while (N != 0):

r = N % K

N = N//K

s = r * w + s

w = 10

return s

def check(N):

fl = False

while (N != 0):

r = N % 10

N = N//10

if (fl == True and r == 0):

return False

if (r > 0):

fl = False

continue

fl = True

return True

N, K = 15, 8

hasConsecutiveZeroes(N, K)


Program for Number of solutions to Modular Equations

import math

def calculateDivisors (A, B):

N = A - B

noOfDivisors = 0

a = math.sqrt(N)

for i in range(1, int(a + 1)):

if ((N % i == 0)):

if (i > B):

noOfDivisors +=1

if ((N / i) != i and (N / i) > B):

noOfDivisors += 1;

return noOfDivisors

def numberOfPossibleWaysUtil (A, B):

if (A == B):

return -1

if (A < B):

return 0

noOfDivisors = 0

noOfDivisors = calculateDivisors;

return noOfDivisors

def numberOfPossibleWays(A, B):

noOfSolutions = numberOfPossibleWaysUtil(A, B)

if (noOfSolutions == -1):

print ("For A = " , A , " and B = " , B

, ", X can take Infinitely many values"

, " greater than " , A)

else:

print ("For A = " , A , " and B = " , B

, ", X can take " , noOfSolutions

, " values")

A = 26

B = 2

numberOfPossibleWays(A, B)

A = 21

B = 5

numberOfPossibleWays(A, B)


Program for Print Number series without using loop

def PrintNumber(N, Original, K, flag):

print(N, end = " ")

if (N <= 0):

if(flag==0):

flag = 1

else:

flag = 0

if (N == Original and (not(flag))):

return


if (flag == True):

PrintNumber(N - K, Original, K, flag)

return

if (not(flag)):

PrintNumber(N + K, Original, K, flag);

return

N = 20

K = 6

PrintNumber(N, N, K, True)


Program for Maximum height when coins are arranged in a triangle

def squareRoot(n):

x = n

y = 1

e = 0.000001 

while (x - y > e):

x = (x + y) / 2

y = n/x

return x

def findMaximumHeight(N):

n = 1 + 8*N

maxh = (-1 + squareRoot(n)) / 2

return int(maxh)

N = 12

print(findMaximumHeight(N))


Program to print double sided stair-case pattern

def pattern(n):

for i in range(1,n+1):

k =i + 1 if(i % 2 != 0) else i

for g in range(k,n):

if g>=k:

print(end=" ")

for j in range(0,k):

if j == k - 1:

print(" * ")

else:

print(" * ", end = " ")

n = 10

pattern(n)


Program to display Zodiac sign for given date of birth

def zodiac_sign(day, month):

if month == 'december':

astro_sign = 'Sagittarius' if (day < 22) else 'capricorn'

elif month == 'january':

astro_sign = 'Capricorn' if (day < 20) else 'aquarius'

elif month == 'february':

astro_sign = 'Aquarius' if (day < 19) else 'pisces'

elif month == 'march':

astro_sign = 'Pisces' if (day < 21) else 'aries'

elif month == 'april':

astro_sign = 'Aries' if (day < 20) else 'taurus'

elif month == 'may':

astro_sign = 'Taurus' if (day < 21) else 'gemini'

elif month == 'june':

astro_sign = 'Gemini' if (day < 21) else 'cancer'

elif month == 'july':

astro_sign = 'Cancer' if (day < 23) else 'leo'

elif month == 'august':

astro_sign = 'Leo' if (day < 23) else 'virgo'

elif month == 'september':

astro_sign = 'Virgo' if (day < 23) else 'libra'

elif month == 'october':

astro_sign = 'Libra' if (day < 23) else 'scorpio'

elif month == 'november':

astro_sign = 'scorpio' if (day < 22) else 'sagittarius'

print(astro_sign)

if __name__ == '__main__':

day = 19

month = "may"

zodiac_sign(day, month)


Write a python code to print this pattern.

 


def pattern(n):

num = 65

for i in range(0,n):

for j in range(0,i+1):

ch = chr(num)

print(ch,end = " ")

num = num + 1

print("\r")

n = 5

pattern(n)

program to create a doubly linked list from a ternary tree

class Node:    

    def __init__(self,data):    

        self.data = data;    

        self.left = None;    

        self.middle = None;    

        self.right = None;    

class TernaryTreeToDLL:    

    def __init__(self):    

        self.root = None;    

        self.head = None;    

        self.tail = None;    

    def convertTernaryToDLL(self, node):    

        if(node == None):    

            return;    

        left = node.left;    

        middle = node.middle;    

        right = node.right;    

        if(self.head == None):    

            self.head = self.tail = node;    

            node.middle = None;    

            self.head.left = None;    

            self.tail.right = None;    

        else:    

            self.tail.right = node;    

            node.left = self.tail;    

            node.middle = None;    

            self.tail = node;    

            self.tail.right = None;    

        self.convertTernaryToDLL(left);    

        self.convertTernaryToDLL(middle);    

        self.convertTernaryToDLL(right);        

    def displayDLL(self):    

        current = self.head;    

        if(self.head == None):    

            print("List is empty");    

            return;    

        print("Nodes of generated doubly linked list: ");    

        while(current != None):    

            print(current.data),    

            current = current.right;    

tree = TernaryTreeToDLL();    

tree.root = Node(5);    

tree.root.left = Node(10);    

tree.root.middle = Node(12);    

tree.root.right = Node(15);    

tree.root.left.left = Node(20);    

tree.root.left.middle = Node(40);    

tree.root.left.right = Node(50);    

tree.root.middle.left = Node(24);    

tree.root.middle.middle = Node(36);    

tree.root.middle.right = Node(48);    

tree.root.right.left = Node(30);    

tree.root.right.middle = Node(45);    

tree.root.right.right = Node(60);    


tree.convertTernaryToDLL(tree.root);    

     

tree.displayDLL();

Program to Find HCF(Highest Common Factor)

def calculate_hcf(x, y):  

    if x > y:  

        smaller = y  

    else:  

        smaller = x  

    for i in range(1,smaller + 1):  

        if((x % i == 0) and (y % i == 0)):  

            hcf = i  

    return hcf  

num1 = int(input("Enter first number: "))  

num2 = int(input("Enter second number: "))  

print("The H.C.F. of", num1,"and", num2,"is", calculate_hcf(num1, num2))  

Program to find minimum cost path

R = 3

C = 3

def minCost(cost, m, n):

tc = [[0 for x in range(C)] for x in range(R)]


tc[0][0] = cost[0][0]

for i in range(1, m + 1):

tc[i][0] = tc[i-1][0] + cost[i][0]

for j in range(1, n + 1):

tc[0][j] = tc[0][j-1] + cost[0][j]

for i in range(1, m + 1):

for j in range(1, n + 1):

tc[i][j] = min(tc[i-1][j-1], tc[i-1][j],tc[i][j-1]) + cost[i][j]

return tc[m][n]

cost = [[1, 2, 3],

[4, 8, 2],

[1, 5, 3]]

print(minCost(cost, 2, 2))


Program to find LCM

def calculate_lcm(x, y):  

    if x > y:  

        greater = x  

    else:  

        greater = y  

    while(True):  

        if((greater % x == 0) and (greater % y == 0)):  

            lcm = greater  

            break  

        greater += 1  

    return lcm    

num1 = int(input("Enter first number: "))  

num2 = int(input("Enter second number: "))  

print("The L.C.M. of", num1,"and", num2,"is", calculate_lcm(num1, num2))  


Reverse of a number using functions

def intreverse(Number):
  Reverse = 0          # Initialize the reverse value to overcome garbage value storage
  while(Number > 0):
    Reminder = Number %10
    Reverse = (Reverse *10) + Reminder
    Number = Number//10
  return (Reverse)

Program to find even number using functions without return

def even(n):
      if  n%2==0:
            print 'Even number'
      else:
            print 'Odd Number'

n=int(raw_input('Enter the number to check even or not:'))
even(n)  # No return from function but the message is displayed inside the function itself

Simple Calculator using functions

def su(a,b):  
      c=a+b
      print 'Added value is:',c
     
def subt(a,b):
            if a>b:
                  c=a-b
                  print 'Subtracted value is:',c
            else:
                  c=b-a
                  print 'Subtracted value is:',c
                  
def mul(a,b):
      c=a*b
      print 'Multiplication value is:',c

def div(a,b):
      if b==0:         
            print 'Division by zero not defined'
      else:
            c=float(a)/b
            print 'Divison value is:',c

def exp(a,b):
      c=a**b
      print 'Exponent value is:',c


a=int(raw_input('Enter the value of a:'))
b=int(raw_input('Enter the value of b:'))
print ' 1. add  2.sub  3.mul  4. div  5.exp'
n=int(raw_input('Enter the choice:'))
if n==1:
      su(a,b)        # Function call
elif n==2:
      subt(a,b)    # Function call
elif n==3:
      mul(a,b)          # Function call
elif n==4:
      div(a,b)    # Function call
elif n==5:
      exp(a,b)    # Function call
else:
      print 'Invalid options'

Factorial using Recursion



def recur_factorial(n):
   if n == 1:
       return n
   else:
       return n*recur_factorial(n-1)


num = int(input("Enter a number: "))

if num < 0:
   print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
   print("The factorial of 0 is 1")
else:
   print("The factorial of",num,"is",recur_factorial(num))