8FC21 PP&A Key

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 13

Python Key

Date of Exam: 3 March 2023

1) Mention the features of Python.


Python is a multi-paradigm programming language.
Object-oriented programming and structured programming.
Python uses dynamic typing.
2) What is a string and how to declare a string in Python?
Python string is the collection of the characters surrounded by single quotes, double quotes, or
triple quotes.
str1 = 'Hello'
print(str1)
3) Define class and object.
Class:-
In python everything is an object.

To create objects we required some Model or Plan or Blue print, which is nothing but class.
We can write a class to represent properties (attributes) and actions (behaviour) of object.
Properties can be represented by variables
Actions can be represented by Methods.
Hence class contains both variables and methods.
Object:-
Physical existence of a class is nothing but object.
We can create any number of objects for a class.
4) List any 4 functions of Numpy.
NumPy is a Python library used for working with arrays. It also has functions for working in
domain of linear algebra, Fourier transform, and matrices.
5) Define Algorithm?
The name 'Algorithm' refers to the sequence of instruction that must be followed to clarify a
problem.
The logical description of the instructions which may be executed to perform an essential
function.
Algorithms are usually generated independent of primary languages, i.e., an algorithm can
be achieved in more than one programming language.
6) What is a Spanning Tree?
A tree is a spanning tree for a linked graph if its set of vertices is the same as the graph's set
of vertices and its edges are a subgroup of the graph's edge set.
A spanning tree is a component of every linked graph. The sum of the weights of each edge
in a spanning tree is the tree's weight, denoted by the symbol w (T). The Minimum Spanning
Tree, abbreviated MST, is a spanning tree with the least amount of weight that is practically
possible.
7) What are the advantages of Python List?
The important characteristics of Python lists are as follows:
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.
8) What is overloading?
Function overloading or method overloading is the ability to create multiple functions of the
same name with different implementations.
9) Why we use Omega notation?
The notation Ω(n) is the formal way to express the lower bound of an algorithm's running
time.
10) Tell about exception handling in Python?
In general, when a Python script encounters a situation that it cannot cope with, it raises an
exception. An exception is a Python object that represents an error. When a Python script
raises an exception, it must either handle the exception immediately otherwise it terminates
and quits.

Part – B

11) a) List the data types used in Python with an example.


Data types: -

The data stored in memory can be of many types. For example, a student roll number is
stored as a numeric value and his or her address is stored as alphanumeric characters.
Python
has various standard data types that are used to define the operations possible on them and
the storage method for each of them.
Int:
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited
length.
>>> print(24656354687654+2)
24656354687656
>>> print(20)
20
>>> print(0b10)
2
>>> print(0B10)
2
>>> print(0X20)
32
>>> 20
20
>>> 0b10
2
>>> a=10
>>> print(a)
10
# To verify the type of any object in Python, use the type() function:
>>> type(10)
<class 'int'>
>>> a=11
>>> print(type(a))
<class 'int'>
Float:
Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.
Float can also be scientific numbers with an "e" to indicate the power of 10.
>>> y=2.8
>>> y
2.8
>>> y=2.8
>>> print(type(y))
<class 'float'>
>>> type(.4)
<class 'float'>
>>> 2.
2.0
Example:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'float'>
<class 'float'>
<class 'float'>
Boolean:
Objects of Boolean type may have one of two values, True or False:
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
String:
1. Strings in Python are identified as a contiguous set of characters represented in the
quotation marks. Python allows for either pairs of single or double quotes.
• 'hello' is the same as "hello".
• Strings can be output to screen using the print function. For example: print("hello").
>>> print("hello")
hello
>>> type("hello")
<class 'str'>
>>> print('hello')
hello
>>> " "
''
11) b) What are the different types of functions used in Python?

Functions and its use: Function is a group of related statements that perform a specific task.
Functions help break our program into smaller and modular chunks. As our program grows
larger and larger, functions make it more organized and manageable. It avoids repetition and
makes code reusable.
Basically, we can divide functions into the following two types:
1. Built-in functions - Functions that are built into Python.
Ex: abs(),all().ascii(),bool()………so on….
integer = -20
print('Absolute value of -20 is:', abs(integer))
Output:
Absolute value of -20 is: 20
2. User-defined functions - Functions defined by the users themselves.
def add_numbers(x,y):
sum = x + y
return sum
print("The sum is", add_numbers(5, 20))
Output:
The sum is 25

12) a) How can we access the values using the concept of dictionaries in Python?

The dictionary is an unordered collection that contains key : value pairs separated by commas
inside curly brackets.
Dictionaries are optimized to retrieve values when the key is known.
Access Dictionary:-
Dictionary is an unordered collection, so a value cannot be accessed using an index; instead, a
key must be specified in the square brackets, as shown below.
>>> capitals = {"USA":"Washington DC", "France":"Paris", "India":"New Delhi"}
>>>capitals["USA"]
'Washington DC'
>>> capitals["France"]
'Paris'
>>> capitals = {"USA":"Washington DC", "France":"Paris", "Japan":"Tokyo", "India":"New Delhi"}
>>> capitals.get("USA")
'Washington DC'
>>> capitals.get("France")
'Paris'
>>> capitals.get("usa")
>>> capitals.get("Japan")

12) b) Give the advantages of importing and using modules in Python with a suitable example.
Any text file with the .py extension containing Python code is basically a module.
Different Python objects such as functions, classes, variables, constants, etc., defined in one module
can be made available to an interpreter session or another Python script by using the import
statement.
Functions defined in built-in modules need to be imported before use.
Creating a Module:-
We can now import this module and execute the sum() function in the Python shell.

Example: Importing a Module

>>> import calc


>>> calc.sum(5, 5)
10

13) a) Mention the concept of inheriting classes with an example.


Python Inheritance:
Inheritance is an important aspect of the object-oriented paradigm.
Inheritance provides code reusability to the program because we can use an existing class to
create a new class instead of creating it from scratch.
In inheritance, the child class acquires the properties and can access all the data members and
functions defined in the parent class.
A child class can also provide its specific implementation to the functions of the parent class.
In python, a derived class can inherit base class by just mentioning the base in the bracket after
the derived class name.
13 b) How can we use regular expressions with Python? Give an example.
A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern.
RegEx can be used to check if a string contains the specified search pattern.
RegEx Module
Python has a built-in package called re, which can be used to work with Regular Expressions.
Import the re module:
import re
RegEx in Python
When you have imported the re module, you can start using regular expressions:
ExampleGet your own Python Server
Search the string to see if it starts with "The" and ends with "Spain":
import re
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
14) a) How to create GUI applications using Tkinter in Python?

Python provides the standard library Tkinter for creating the graphical user interface for desktop
based applications.
Developing desktop based applications with python Tkinter is not a complex task. An empty Tkinter
top-level window can be created by using the following steps.
1. import the Tkinter module.
2. Create the main application window.
3. Add the widgets like labels, buttons, frames, etc. to the window.
4. Call the main event loop so that the actions can take place on the user's computer screen.
Example
from tkinter import *
#creating the application main window.
top = Tk()
#Entering the event main loop
top.mainloop()

14) b) Write the advantages of Numpy package usage in python.


NumPy (also called Numerical Python) is a highly flexible, optimized, open-source package meant for
array processing. It provides tools for delivering high-end performance while dealing with N-
dimensional powerful array objects. It is also beneficial for performing scientific computations,
mathematical, and logical operations, sorting operations, I/O functions, basic statistical and linear
algebra-based operations along with random simulation and broadcasting functionalities. Due to the
vast range of capabilities, NumPy has become very popular and is the most preferred package. The
following image represents the uses of NumPy.
15) a) write about space and time complexity of an algorithm with an example.
The space complexity of an algorithm is the amount of memory it needs to run to
completion. The time complexity of an algorithm is the amount of computer time it needs
to run to completion.
multi ← 1
i ← 2
while i ≤ n do
multi ← multi ∗ i
i ← i + 1
end while
The Time Complexity of the above multiplication function can be calculated as follows:
The time complexity of lines 1 and 2 would be O(1)
Line number 3 shows the while loop.
Therefore, lines 4 and 5 repeats (n -1) times.
Hence, the time complexity for lines 4 and 5 would be O(n)
Finally, combine all the time complexities of all lines to get the overall time complexity
of the multiplication function.
Therefore, T(n)=O(n).
int sum, i
while i ≤ n do
sum ← sum + a[i]
i ← i + 1
end while
return sum
The Space Complexity of the above sum of elements of an array function can be
calculated as follows:
Space complexity would be the number of allocated bytes and generally integer takes a
space of 4 bytes in the memory.
Line 1 allocates memory space for two integers therefore, space complexity for line 1 is
4 bytes×2=8 bytes
Line 2 shows the while loop.
Lines 3 and 4, allocates values to an existent variable therefore, memory space is not
allocated here.
Line 6, returns the statement therefore it will allocate one more memory space as
4 bytes×2+4 bytes=12 bytes
Finally, combine all the space complexities of all lines to get the overall space complexity
of the sum of elements of an array function and also consider the array is allocating n
cases of integers in the function.
Therefore, S(n)=n+12=O(n).
15) b) Explain Quick sort using an example.

Quick sort is a fast sorting algorithm used to sort a list of elements.


The quick sort algorithm attempts to separate the list of elements into two parts and then
sort each part recursively. That means it use divide and conquer strategy. In quick sort,
the partition of the list is performed based on the element called pivot. Here pivot element
is one of the elements in the list.
16) a) What do you analyze about knapsack problem? Explain.

A bag or sack is given capacity and n objects are given. Each object has weight
wi and profit pi .
Fraction of object is considered as xi (i.e) 0<=xi<=1 .
If fraction is 1 then entire object is put into sack.
When we place this fraction into the sack we get
wixi and pixi.
Given a set of items, each with a weight and a value, determine a subset of items to
include in a collection so that the total weight is less than or equal to a given limit and the
total value is as large as possible.
The knapsack problem is in combinatorial optimization problem. It appears as a sub
problem in many, more complex mathematical models of real-world problems. One
general approach to difficult problems is to identify the most restrictive constraint, ignore
the others, solve a knapsack problem, and somehow adjust the solution to satisfy the
ignored constraints.
Applications
In many cases of resource allocation along with some constraint, the problem can be
derived in a similar way of Knapsack problem. Following is a set of example.
 Finding the least wasteful way to cut raw materials
 portfolio optimization
 Cutting stock problems
16) b) Mention the advantages of dynamic programming with a suitable example.
One of the main advantages of using dynamic programming is that it speeds up processing,
since references that were previously calculated are used. As it is a recursive programming
technique, it reduces the lines of code in the program.
Dynamic programming is an effective method of solving problems that might
otherwise seem extremely difficult to solve in a reasonable amount of time.
Algorithms based on the dynamic programming paradigm are used in many areas of
science, including many examples in artificial intelligence, from planning problem
solving to speech recognition.
17) a) Give an example for if, Nested – if – else conditional statements.
The if statement: -
• The if statement is used to test a particular condition and if the condition is true, it executes
a block of code known as if-block.
• The condition of if statement can be any valid logical expression which can be either
evaluated to true or false.
Example: -
Program to print the largest of the three numbers.
a = int(input("Enter a? "));
b = int(input("Enter b? "));
c = int(input("Enter c? "));
if a>b and a>c:
print("a is largest");
if b>a and b>c:
print("b is largest");
if c>a and c>b:
print("c is largest");
Nested if-else statements: -
if(condition):
#Statements to execute if condition is true
if(condition):
#Statements to execute if condition is true
#end of nested if
#end of if
17) b) Write about tuples in Python with example.

• Tuple is an immutable (unchangeable) collection of elements of different data types. It is an


ordered collection, so it preserves the order of elements in which they were defined.
• Tuples are defined by enclosing elements in parentheses (), separated by a comma.
• The following declares a tuple type variable.
tpl=() # empty tuple
print(tpl)
names = ('Jeff', 'Bill', 'Steve', 'Yash') # string tuple
print(names)
nums = (1, 2, 3, 4, 5) # int tuple
print(nums)
employee=(1, 'Steve', True, 25, 12000) # heterogeneous data tuple
print(employee)
17) c) What is the advantage of Data Hiding?
Data hiding is a part of object-oriented programming, which is generally used to hide
the data information from the user. It includes internal object details such as data
members, internal working. It maintained the data integrity and restricted access to the
class member. The main working of data hiding is that it combines the data and
functions into a single unit to conceal data within a class. We cannot directly access
the data from outside the class.
This process is also known as the data encapsulation. It is done by hiding the
working information to user. In the process, we declare class members as private so
that no other class can access these data members. It is accessible only within the
class.
We can perform data hiding in Python using the __ double underscore before prefix. This
makes the class members private and inaccessible to the other classes.
18) a) Give an example for Plotpy.
Matplotlib is a low level graph plotting library in python that serves as a visualization
utility.
• Matplotlib is open source and we can use it freely.
• Most of the Matplotlib utilities lies under the pyplot submodule, and are usually
imported under the plt alias:
import matplotlib.pyplot as plt
• Now the Pyplot package can be referred to as plt.
Example:-
Draw a line in a diagram from position (0,0) to position (6,250):
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([0, 6])
ypoints = np.array([0, 250])
plt.plot(xpoints, ypoints)
plt.show()
18) b) Write few applications of binary search.
This algorithm is used to search element in a given sorted array with more efficiency.
It could also be used for few other additional operations like- to find the smallest
element in the array or to find the largest element in the array.
18) c) Write the concept of travelling sales person problem.
TSP is the travelling salesman problem consists of a salesperson and his travel to various
cities. The salesperson must travel to each of the cities, beginning and ending in the same.
The problem's challenge is that the travelling salesman wishes to minimize the trip's total
length.

*****

You might also like