Dibrugarh University 3 SEM TDC (CBCS) - Paper : GE-3B | Python Solve paper Computer Science Generic elective

Loying
0

 Dibrugarh University 3 SEM TDC (CBCS) | Programming in Python Paper Solve 2020 | Paper : GE-3B

Programming in Python Paper : GE-3B Paper Solved 2020 | Dibrugarh University 3 SEM TDC (CBCS) Computer Science Programming in Python | Here you can get Dibrugarh University Generic Elective (Computer Science) programming in python 3 SEM TDC (CBCS)  2020 Paper : GE-3B solved question paper | Dibrugarh University paper solved


Paper : GE-3B

(Programming in Python)

1. Answer the following as directed : 1×7=7

 (a) Raw facts or figures are called _____. ( Fill in the blank )

Ans. Data

(b) Define algorithm. 

Ans.In computer programming terms, an algorithm is a set of well-defined instructions to solve a particular problem. It takes a set of input and produces a desired output.

(c) What is linker error? 

Ans: These error occurs when after compilation we link the different object files with main’s object using Ctrl+F9 key(RUN). These are errors generated when the executable of the program cannot be generated. This may be due to wrong function prototyping, incorrect header files.

(d) Python has been derived from C language. 

( State True or False )

Ans: True

(e) The step argument in range( ) can be zero. 

( State True or False )

Ans: False

 (f) What is the output of the following code? 

import random as r 

print (random.randomint (1, 10) )

 (i) An error occurs 

(ii) 1

 (iii) 10

 (iv) Any random value 

( Choose the correct option )

Ans :  (i) An error occurs 

 (g) What does PyPI stand for?

Ans: Python Package Index

2. Answer any three of the following : 2×3=6

 (a) Differentiate between logical errors and syntax errors. 

Ans:

Syntax ErrorLogical Error
Syntax Errors occur when we violate the rules of writing the statements of the programming language.Logical Errors occur due to our mistakes in programming logic.
Program fails to compile and execute.Program compiles and executes but doesn't give the desired output.
Syntax Errors are caught by the compiler.Logical errors need to be found and corrected by people working on the program.

(b) Differentiate between local variable and global variable.

Ans:

Local variable

It is generally declared inside a function.

If it isn’t initialized, a garbage value is stored inside it.

It is created when the function begins its execution.

It is lost when the function is terminated.

Global variable
It is declared outside the function.

If it isn’t initialized, the value of zero is stored in it as default.

It is created before the global execution of the program.

It is lost when the program terminates.

Data sharing is possible since multiple functions can access the global variable.

 (c) What will happen when the strip( ) is used with a string argument? 

Ans:

(d) Write the properties of list. 

Ans: 

Lists are ordered.

Lists can contain any arbitrary objects.

List elements can be accessed by index.

Lists can be nested to arbitrary depth.

Lists are mutable.

Lists are dynamic.

Answer any four of the following : 

3. (a) Write a short note on special class method. 5 

Ans: Special Methods

4 special methods that you will be likely to use in  classes

1. __init__

The __init__ special method is automatically executed when an instance of class is created. It is also called class constructor. The parameters of the __init__ represent the data attributes of a class.

Let’s create a class called Book.

class Book():

    def __init__(self, name, writer, pages):

       self.name = name

       self.writer = writer

       self.pages = pages

The self refers to the instance itself. The Book class has 3 data attributes that need to be specified when creating a Book instance.

b = Book("Moby Dick", "Herman Melville", "378")

type(b)

__main__.Book

The variable b is an instance of the Book class.

2. __str__

We use the __str__ special method to implement the built-in print function within our class. Without the __str__, here is what print function does.

print(b)

<__main__.Book object at 0x7f9ed5b1d590>

Let’s define the __str__ method in our class definition.

def __str__(self):

   return f"The title of the book is {self.name}"

Now the print function will return the title of the name. It accesses the name of the book through the name attribute. You can customize it in any way you’d like.

print(b)

The title of the book is Moby Dick

3. __len__

The len function returns the length of an object. For strings, it returns the number of characters. For a Pandas data frame, it returns the number of row.

We can customize its behavior by implementing the __len__ special method in our class definition. Let’s make it to return the number of pages of a book object.

If the __len__ is not implemented in the class definition, you will get an error if you try to use it on an object of your class. It does not have a default behavior like the print function.

def __len__(self):

   return int(self.pages)

len(b)

378

4. __eq__

The __eq__ special method allows for comparing two instances of a class. If it is defined in  class, we can check if an instance is equal to another instance. The equality condition is specified using the __eq__ method.

 we can declare two books being equal if the names and writers of the book are the same. They might have different number of pages.

def __eq__(self, other):

   return (self.name == other.name) & (self.writer == other.writer)

The “==” operator will return True if both names and writes are the same for two instances. Let’s create two books and check if they are equal.

b = Book("Moby Dick", "Herman Melville", "378")

a = Book("Moby Dick", "Herman Melville", "410")

b == a

True

If either names or writes is different, the equality operator returns False.

b = Book("Moby Dick", "Herman Melville", "378")

a = Book("Moby Dick", "Melville", "410")

b == a

False

(b) What is class instantiation? How is it done? 5 

Ans: Inheritance

Being an Object Oriented language, Python supports inheritance, it even supports multiple inheritance. Classes can inherit from other classes. A class can inherit attributes and behaviour methods from another class, called the superclass. A class which inherits from a superclass is called a subclass, also called heir class or child class. In other words inheritance refers to defining a new class with little or no modification to an existing class.


class A:        # define your class A

pass

class B:         # define your class B

pass

class C(A, B):   # subclass of A and B

Instantiation

Instantiating a class is creating a copy of the class which inherits all class variables and methods. Instantiating a class in Python is simple. To instantiate a class, we simply call the class as if it were a function, passing the arguments that the __init__ method defines. The return value will be the newly created object.


Example

class Foo():

        def __init__(self,x,y):

            print x+y

f = Foo(3,4)

Output

7

4. (a) Create a tupple that has just one element which in turn may have three elements a, b and c. Print the length of this tupple.

Ans:

(b) Write a program to calculate simple interest. 5 

Ans: 

#Python program to calculate simple interest
 
P = float(input("Enter the principal amount : "))
 
N = float(input("Enter the number of years : "))
 
R = float(input("Enter the rate of interest : "))
 
#calculate simple interest by using this formula
SI = (P * N * R)/100
 
#print
print("Simple interest : {}".format(SI))

OUTPUT:
Enter the principal amount :  1000 
Enter the number of years :  2 
Enter the rate of interest :  5 
Simple interest : 100.0 

5. (a) Differentiate between counter-controlled loops and sentinel-controlled loops. 5 

Ans:

No.TopicsCounter controlled loopSentinel controlled loop
01Number of executionPreviously known number of executions take placeUnknown number of executions take place
02Condition variableCondition variable is known as counter variable. As because, it counts the total number of executions against the max number of executionsCondition variable is known as sentinel variable, which means a guard. This variable waits for a decision made inside the loop to let another cycle take place or break the loop
03Value and limitation of variableThe value of the variable and the limitation of the condition for the variable both are strict.The limitation for the condition variable is strict but the value of the variable varies in this case.
Differences between counter & controlled loops

Example

Counter controlled loop

int sum = 0;
int n = 1;

while (n <= 10)
{
sum = sum + n*n;
n = n+ 1;
}

In this example. we can see that the while loop will only execute 10 times. The value and the limit both are fixed.

Sentinel controlled loop

do
{
printf("Input a number.n");
scanf("%d", &num);
}
while(num>0);

In this example, we can see that the loop execution depends on user’s input. If the input is greater than 0, the loop continues. When the user inputs 0 or less than 0, the loop breaks.


(b) What are variable-length arguments? Explain with the help of a code. 5

6. (a) What is slice operation? Explain with an example. 5

Ans: Python slice() function is used to get a slice of elements from the collection of elements. Python provides two overloaded slice functions. The first function takes a single argument while the second function takes three arguments and returns a slice object. This slice object can be used to get a subsection of the collection. 

Python slice() Function Example 1

# Python slice() function example  

# Calling function  

result = slice(5) # returns slice object  

result2 = slice(0,5,3) # returns slice object  

# Displaying result  

print(result)  

print(result2)  

Output:


slice(None, 5, None)

slice(0, 5, 3)

 (b) Write a program to calculate GCD using recursive functions. 5 

Ans: 

Python Program to find the GCD of two numbers using recursion. 


def gcd(a,b):

    if(b==0):

        return a

    else:

        return gcd(b,a%b)

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

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

GCD=gcd(a,b)

print("GCD is: ")

print(GCD)

Program Explanation

1. User must enter two numbers.

2. The two numbers are passed as arguments to a recursive function.

3. When the second number becomes 0, the first number is returned.

4. Else the function is recursively called with the arguments as the second number and the remainder when the first number is divided by the second number.

5. The first number is then returned which is the GCD of the two numbers.

6. The GCD is then printed.

OUTPUT:

Case 1:
Enter first number:5
Enter second number:15
GCD is: 
5
 
Case 2:
Enter first number:30
Enter second number:12
GCD is: 
6

7. (a) Explain binary search with the help of an example. 5 

Ans: 

Binary search is a searching algorithm which is used to search an element from a sorted array. It cannot be used to search from an unsorted array. Binary search is an efficient algorithm and is better than linear search in terms of time complexity.


The time complexity of linear search is O(n). Whereas the time complexity of binary search is O(log n). Hence, binary search is efficient and faster-searching algorithm but can be used only for searching from a sorted array.


Example

Let us take the following sorted array and we need to search element 6.

25681011131516

L=0 H=8 Mid=4

25681011131516

6<10, therefore take the first half.

H=Mid-1

L=0 H=3 Mid=1

25681011131516

6>5, therefore choose the second half.

L=Mid+1

L=2 H=3 Mid=2

25681011131516

6==6, an element found

Hence the element 6 is found at index 2.


Example: 

def binary_search(arr,x):

    l=0

    r=len(arr)-1

    while(l<=r):

        mid=(l+r)//2

        if(arr[mid]==x):

            return mid

        elif(x<arr[mid]):

            r=mid-1

        elif(x>arr[mid]):

            l=mid+1

    return -1

array=[1,2,3,4,5,6,7,8,9,10]

a=7

print(binary_search(array,a))

b=15

print(binary_search(array,b))


OUTPUT: 

6

-1

(b) With the help of an example, explain the significance of the _init_( ) method. 5

Tags

Post a Comment

0 Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !
To Top