Python Tutorial: CS-Python Functions Exercises

Sunday, 9 July 2023

CS-Python Functions Exercises

DHANPAT RAI 

1.      Write a function that takes amount-in-dollars and dollar-to-rupee conversion price; it then returns the amount converted to rupees. Create the function in both void and non-void forms.

Ans: #Dollar to Rupees Conversion

#Non-void Function

global Rs

def dollar_to_rupee(amount):

    return amount * Rs

 

#Void Function

def dollar_to_rup(amount):

    print(amount * Rs)

 

Rs=float(input("Recent Dollar into rupee : "))

print("Dollar to Rupee :: ", dollar_to_rupee(5))

dollar_to_rup(10)

Output:

Recent 1 Dollar into rupee : 82.62

Dollar to Rupee ::  413.1

826.2

2. Write a function to calculate volume of a box with appropriate default values for its parameters. Your function should have the following input parameters:

(a) length of box;    (b) width of box;                     (c) height of box.

      Test it by writing complete program to invoke it.

Ans: # Calculate box volume

def calc_box_volume(length = 6, width = 7, height = 8):

    return length * width * height

 

print("calc_box_volume(): ",calc_box_volume())

print("calc_box_volume(2, 4, 6): ",calc_box_volume(2, 4, 6))

print("calc_box_volume(height = 12) : ",calc_box_volume(height = 10.5))

print("calc_box_volume(10): ",calc_box_volume(10))

Output:

calc_box_volume():  336

calc_box_volume(2, 4, 6):  48

calc_box_volume(height = 12) :  441.0

calc_box_volume(10):  560

3. Write a program to have following functions:

(i) function that takes a number as argument and calculates cube for it. The function does not return a value. If there is no value passed to the function in function call, the function should calculate cube of 2.

(ii) a function that takes two char arguments and returns True if both the arguments are equal otherwise False. Test both these functions by giving appropriate function call statements.

Ans. #Cube of a number

 

def cube(n = 4):

    print(n * n * n)

 

#Compare two characters

 

def compare(lt1, lt2):

    if lt1 == lt2:

        return True

    else:

        return False

 

print("cube() =>")

cube()

print("cube(10) =>")

cube(10)

 

print("compare('a', 'b') : ", compare('a', 'b'))

print("compare('a', 'a') :",compare('a', 'a'))

Output:

cube() =>

64

cube(10) =>

1000

compare('a', 'b') :  False

compare('a', 'a') : True

4. Write a function that receives two numbers and generates a random number from that range. Using this function, the main program should be able to print three numbers randomly.

Ans:

import random

def generate_random(a, b):

    return random.randint(a,b)

 

print("First Random Number :: ",generate_random(1,10))

print("Second Random Number :: ",generate_random(10,100))

print("Third Random Number :: ",generate_random(1, 25))

Output:

First Random Number ::  1

Second Random Number ::  10

Third Random Number ::  16

5. Write a function that receives two string arguments and checks whether they are same-length strings (returns True in this case otherwise False).

Ans:# Compare length of string

def CompLen(st1, st2):

    if len(st1) == len(st2):

        return True

    else:

        return False

print('CompLen("CBSE","Code")\t: ', CompLen("CBSE", "Code"))

print('compare_length("Python", "Ruby")\t:',CompLen("Python", "Ruby"))

Output:

CompLen("CBSE","Code")    :  True

compare_length("Python", "Ruby")   : False

6. Write a function namely nthRoot() that receives two parameters x and n and returns nth root of x i.e.  . The default value of n is 2

def nthRoot(x, n = 2):

    return x**(1/n)

 

#main program

print("nthroot(4) :",nthRoot(4))

print("nthroot(7,4) :", nthRoot(7, 4))

Output:

nthroot(4) : 2.0

nthroot(7,4) : 1.6265765616977856

7. Write a function that takes a number n and then returns a randomly generated number having exactly n digits (not starting with zero) e.g., if n is 2 then function can randomly return a number 10-99 but 07, 02 etc. are not valid two digits numbers.

import random

def generate_random(num):

    start = 10 **(num-1)

    end = 10**num - 1

    return random.randint(start, end)

 

#main program

print("generate_random(1): ", generate_random(1))

print("generate_random(2) : ", generate_random(2))

print("generate_random(3) : ", generate_random(3))

Output:

generate_random(1):  8

generate_random(2) :  25

generate_random(3) :  620

8. Write a function that takes two numbers and returns the number that has minimum one's digit [For example, if numbers passed are 491 and 278, then the function will return 491 because it has got minimum one's digit out of two given numbers (491's 1 is <278's 8)].

def comp_min_oneDigit(n1,n2):

    if(n1%10)<(n2%10):

        return n1

    else:

        return n2

print("569,374\t:",comp_min_oneDigit(569,374))

print("56,37\t:",comp_min_oneDigit(56,37))

print("562,178\t:",comp_min_oneDigit(562,178))

Output:

569, 374          : 374

56, 37              : 56

562, 178          : 562

9. Write a program that generates a series using a function which takes first and last values of the series and then generates four terms that are equidistant eg, if two numbers passed are 1 and 7 then function returns 1 3 5 7.

def equidistant_fourTerms(a,b):

    d=((b-a)//3)

    print("Series are\t:",a,a+d,a+2*d,b)

 

#main program

firstNum=int(input('Enter first Term : '))

lastNum=int(input('Enter last Term : '))

equidistant_fourTerms(firstNum,lastNum)

Output:

Enter first Term : 1

Enter last Term : 7

Series are                  : 1 3 5 7

APC BOOKS

10. Write a  Python code to accept two numbers. Check and display whether they are twin prime or not by using function. The function returns 1 if a numbers is prime, otherwise return 0. Twin prime numbers are a pair of prime numbers whose difference is 2. 

[Hint : (5, 7),(11, 13), (17, 19)..................... are twin primes.]

def is_prime(n):

   for i in range(2, n):

      if n % i == 0:

         return False

   return True

 

def generate_twins(start, end):

   for i in range(start, end):

      j = i + 2

      if(is_prime(i) and is_prime(j)):

         print('(',i,',',j,')', end=',')

#Main Program

generate_twins(2, 100)

11.  Write a Python code to accept a number and check whether the number is a palindrome or not. Use a function def Palin(n)  which returns after reversing its digits.

Sample Input : 343

Sample Output: It is Palindrome Number

def Palind(num):

    temp = num

    reverse = 0

    while temp > 0:

        remainder = temp % 10

        reverse = (reverse * 10) + remainder

        temp = temp // 10

    if num == reverse:

      print('Palindrome')

    else:

      print("Not Palindrome")

 

 

#Main Program

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

Palind(num)

# OR

def Palind(num):

    reverse = int(str(num)[::-1])

    print(reverse)

    if num == reverse:

      print('Palindrome')

    else:

      print("Not Palindrome")

 

# Main Program

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

Palind(num)

12. Write a Python code to input a number and use a function def Armstrong() to receive the number. The method will return 1 if the number is Armstrong, otherwise it will return 0.

For Example: 153 is an Armstrong number because 13+53+33=1+125+27=153

def Armstrong(num):

    reminder=Sum=0

    temp=num

    while(num>0):

        reminder=num%10

        Sum=Sum+reminder**3

        num=num//10

    if(temp == Sum):

        return 1

    else:

        return 0

 

 

#Main Program

n=int(input("Enter any number :"))

r=Armstrong(n)

if r==1:

    print("It is Armstrong")

else:

    print("It is not Armstrong")

13. Write a Python to accept a string  in a mixed case. Pass the string to a function def Freq (String). The function should find and the frequency of each vowel.

Sample Input: Understanding Computer Science

Sample Output:      Frequency of 'a' or 'A' =  1

Frequency of 'e' or 'E' =  4

Frequency of 'i' or 'I' =  2

Frequency of 'o' or 'O' =  1

Frequency of 'u' or 'U' =  2

def Freq(String):

    l=len(String)

    aC=eC=iC=oC=uC=0

    for i in range(l):

        if String[i] in 'aA':

            aC+=1

        if String[i] in 'eE':

            eC+=1

        if String[i] in 'iI':

            iC+=1

        if String[i] in 'oO':

            oC+=1

        if String[i] in 'uU':

            uC+=1

    return aC,eC,iC,oC,uC

 

#Main Program

String="Understanding Computer Science"

aC,eC,iC,oC,uC=Freq(String)

print("Frequency of 'a' or 'A' = ",aC)

print("Frequency of 'e' or 'E' = ",eC)

print("Frequency of 'i' or 'I' = ",iC)

print("Frequency of 'o' or 'O' = ",oC)

print("Frequency of 'u' or 'U' = ",uC)

14. Write a Python to store twenty different numbers in a list. Pass the list to a function def Prime(MyList) and display only the numbers which are prime. The function doesn’t return any value to the main function.

def Prime(MyList):

    prime=[]

    for i in MyList :

        c=0

        for j in range(1,i):

            if i%j==0:

                c+=1

        if c==1:

            prime.append(i)

    print (prime)

   

 

#main program

MyList=[1,4, 67,89,34,56,2,6,7,17,24,27,29,34,54,53,19,28,22,12]

Prime(MyList)

Output:

[67, 89, 2, 7, 17, 29, 53, 19]

15. The standard form of a quadratic equation is given by:

ax2 + bx + c = 0

where a and b are the coefficients of x2 and x respectively, and c is constant

          d = b2 - 4ac, where d is known as discriminant

          if d>=0 then roots are possible,

          if d<0 then roots are imaginary

import math

# function for finding roots

def equationroots( a, b, c):

          # calculating discriminant using formula

          dis = b * b - 4 * a * c

          sqrt_val = math.sqrt(abs(dis))

          # checking condition for discriminant

          if dis > 0:

                   print("real and different roots")

                   print((-b + sqrt_val)/(2 * a))

                   print((-b - sqrt_val)/(2 * a))

          elif dis == 0:

                   print("real and same roots")

                   print(-b / (2 * a))

          # when discriminant is less than 0

          else:

                   print("Complex Roots")

                   print(- b / (2 * a), + i, sqrt_val)

                   print(- b / (2 * a), - i, sqrt_val)

 

# Driver Program

a = 1

b = 10

c = -24

 

# If a is 0, then incorrect equation

if a == 0:

                   print("Input correct in  quadratic equation")

 

else:

          equationroots(a, b, c)

16. Write a Python code to accept ten different temperatures in Celsius in a list. Pass each temperature to a function which returns the temperature converted into Fahrenheit.  Display only those temperatures, which are more than the normal body temperature, i.e. 98.6 oF.

def showTemp(lst):

    fahren=[]

    for c in lst:

        if c>=98.6:

            F = (c * 9/5) + 32

            fahren.append(c)

    return fahren

 

#Main Program

lst=[98.6,56.34,65.23,89.65,99.9,102.2,99.88]

print(showTemp(lst))

Output:

[98.6, 99.9, 102.2, 99.88]

17. Write a Python code to accept a string from the user. Pass the string to a function def Display(str) which displays the constants present in the string.

Sample Input: COMPUTER

Sample Output :     C

                             M

                             P       

                             T      

                             R

def Display(str):

    L=len(str)

    for i in range(L):

        if st[i] not in 'AEIOUaeiou':

            print(st[i])

 

#Main Program

str='COMPUTER'

Display(str)

18. Write a Python code to accept a string from the user. Pass the string to a function def Change(str) which display the first character of each word after changing the case (lower to upper and vice-versa).

Sample Input : Doon International School

Sample Output :     d

I

S

def Change(str):

    words=str.split()

    L=len(words)

    for i in range(L):

        if words[i][0].isupper():

            print(words[i][0].lower())

        else:

            print(words[i][0].upper())

 

#Main Program

Change('Doon international school')

19. A automorphic number is the number which contains itself in the last digit(s) of its square. Write a Python code to enter a number. Check and display whether it is an digits contained in the last digit(s) of its square, available in the number.

Sample Input : 25

Sample Output  :  625

So, the function returns last two digits as 25 to check an automorphic number. Thus, the input number 25 is an automorphic number.

def Automorphic(num):

            a = str(num)

            num1 = num ** 2

            b = str(num1)

             if b.endswith(a):

                   print("It's an Automorphic Number")

            else:

                   print("It's not an Automorphic Number")

 

Automorphic(25)

OR

def Automorphic(num):

          #find number of digits in num

          n = len(str(num))

         #compute square

         sqr = num**2

         #Extract last n digits from the square

         last = sqr%pow(10,n)

        #compare last n digits with the input number

       if last == num:

                print("Automorphic Number")

       else:

               print("Not an Automorphic Number")

 

 Automorphic(36)

 20. Write a Python function SmallestDigit(n), input a number and find the smallest digit of the input number.

def smallestDigit(n):

    mn=n%10

    while n>0:

        rem=n%10;

        if rem<mn:

            mn=rem

        n//=10

    print("Smallest digit :",mn)


#main

n=int(input("Enter a number and find smallest digit :"))

smallestDigit(n)    

    21. Write a Python  function nextPrime(n) code to input a number and check whether it is a prime number or not. If it is not a prime then display the next number that is prime.

Sample Input: 14        Sample output: 17

def nextPrime(n):

    c=c1=m=0

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

        if n%a==0:

            c=c+1

    if c==2:

        print(n, " is a prime number")

    else:

        a=n

        m=n

        while(c1!=2):

            a=a+1

            c1=0

            for p in range(1,a+1):

                if a%p==0:

                    c1=c1+1

        print("Next prime number to ",m," is",a)

#main

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

nextPrime(n)


 


No comments:

Post a Comment