You are on page 1of 59

Subject: Programming for Scientific Computing (CE0525/CS0525/IT0525)

Question Bank

UNIT-1
1. Explain branching in context of python. (if, else, else..if,break)

Ans) Branching is an all important concept to learn when programming in Python. If,
Else and Elif statements enable your program to be smart and make decisions.

We've looked at a lot of Python programs lately, and our programs have been slowly
getting more powerful. We’ve learned to run instructions in procedural order, replaced
parts of our program with variables, and looped over the code.

1. Python provides three branching statements break, continue and return.

2. In Python pass also a branching statement, but it is a null statement.

3. Branching statements in Python are used to change the normal flow of

execution based on some condition.

4. The return branching statement is used to explicitly return from a method.

5. break branching statement is used to break the loop and transfer control

to the line immediate outside of loop.

6. continue branching statement is used to escape current execution and

transfers control back to the start of the loop.

7. Python branching statements break and continue statements have two

forms: the labeled form and the unlabeled form.

2. Discuss control structure in context of python.


Ans. Loop control structures include for, while ,do while etc. Here a
piece of code is repeated multiple times in a row. In simple language
loops means repetition of a block of code.

While Loop: this is entry controlled loop where it is firstly initialized


then condition is checked and then incremented or decremented

# prints Hello Geek 3 Times

count = 0

while (count < 3):

count = count+1

print("Hello Geek")

For loop: A for loop is used for iterating over a sequence (that is either a list, a
tuple, a dictionary, a set, or a string).

# Iterating over a list

print("List Iteration")

l = ["geeks", "for", "geeks"]

for i in l:

print(i)

# Iterating over a tuple (immutable)

print("\nTuple Iteration")

t = ("geeks", "for", "geeks")

for i in t:

print(i)
# Iterating over a String

print("\nString Iteration")

s = "Geeks"

for i in s :

print(i)

# Iterating over dictionary

print("\nDictionary Iteration")

d = dict()

d['xyz'] = 123

d['abc'] = 345

for i in d :

print("%s %d" %(i, d[i]))*


3.Explain strings and operations on string type. (slicing, indexing, stride, etc..)

Ans 3)

Indexing” means referring to an element of an iterable by its position within the iterable.

Python slicing is about obtaining a sub-string from the given string by slicing it
respectively from start to end. Python slicing can be done in two ways.
String slicing can also accept a third parameter, the stride , which refers to how many characters
you want to move forward after the first character is retrieved from the string. The value of
stride is set to 1 by default.

Q4. Explain User Defined Functions in python.


A function is a block of program statements which can be used repetitively in a
program. In Python, a user-defined function's declaration begins with the keyword def and
followed by the function name. The function may take arguments(s) as input within the opening and
closing parentheses, just after the function name followed by a colon. After defining the function
name and arguments(s) a block of program statement(s) start at the next line and these statement(s)
must be indented. Syntax:

def function_name(argument1, argument2, ...) :


statement_1
statement_2
....

Example:

def avg_number(x, y):

print("Average of ",x," and ",y, " is ",(x+y)/2)

avg_number(3, 4)

1. Lines 1-2 : Details (definition) of the function.


2. Line 3 : Call the function.
3. Line 1 : Pass parameters : x = 3, y = 4
4. Line 2 : Print the value of two parameters as well as their
average value

5. 1. default arguments:
Default arguments are values that are provided while defining functions.
The assignment operator = is used to assign a default value to the argument.
Default arguments become optional during the function calls.
If we provide a value to the default arguments during function calls, it
overrides the default value.
The function can have any number of default arguments
Default arguments should follow non-default arguments.

Example:
In the below example, the default value is given to argument band c
def add(a,b=5,c=10):
return (a+b+c)
This function can be called in 3 ways
Giving only the mandatory argument
print(add(3))
#Output:18
2. Giving one of the optional arguments.
3 is assigned to a, 4 is assigned to b.
print(add(3,4))
#Output:17
3. Giving all the arguments
print(add(2,3,4))
#Output:9

2. Keyword Arguments:
Functions can also be called using keyword arguments of the form
kwarg=value.
During a function call, values passed through arguments need not be in the
order of parameters in the function definition. This can be achieved by
keyword arguments. But all the keyword arguments should match the
parameters in the function definition.
Example:
def add(a,b=5,c=10):
return (a+b+c)
Calling the function add by giving keyword arguments
All parameters are given as keyword arguments, so no need to maintain the
same order.
print (add(b=10,c=15,a=20))
#Output:45

2. During a function call, only giving mandatory argument as a keyword


argument. Optional default arguments are skipped.
print (add(a=10))
#Output:25

3. Positional Arguments
During a function call, values passed through arguments should be in the
order of parameters in the function definition. This is called positional
arguments.
Keyword arguments should follow positional arguments only.
Example:
def add(a,b,c):
return (a+b+c)
The above function can be called in two ways:
During the function call, all arguments are given as positional arguments.
Values passed through arguments are passed to parameters by their position.
10 is assigned to a, 20 is assigned to b and 30 is assigned to c.
print (add(10,20,30))
#Output:60
2. Giving a mix of positional and keyword arguments, keyword arguments
should always follow positional arguments
print (add(10,c=30,b=20))
#Output:60

4. Variable-length Arguments
Sometimes you may need more arguments to process function then you
mentioned in the definition. If we don’t know in advance about the arguments
needed in function, we can use variable-length arguments also called arbitrary
arguments.

For this an asterisk () is placed before a parameter in function definition which


can hold non-keyworded variable-length arguments and a double asterisk (*)
is placed before a parameter in function which can hold keyworded variable-
length arguments.

If we use one asterisk () like *var, then all the positional arguments from that
point till the end are collected as a tuple called ‘var’ and if we use two
asterisks (*) before a variable like **var, then all the positional arguments
from that point till the end are collected as a dictionary called ‘var’.

Here is an example.

def display(*name, **address):


for items in name:
print (items)

for items in address.items():


print (items)

#Calling the function


display('john','Mary','Nina',John='LA',Mary='NY',Nina='DC')
Output

John
Mary
Nina
('John', 'LA')
('Mary', 'NY')
('Nina', 'DC')

6. Discuss scoping in terms of functions with sample code.

The scope of a variable in python is that part of the code where it is


visible.
b=8
def func():
a=7
print(a)

print(b)
func()

we define a variable ‘a’ in a function ‘func’. So, ‘a’ is local to


Local Scope:
‘func’. Hence, we can read/write it in func, but not outside it.

>>> def func(a=0):


a+=1
print(a)
>>> func()

Here a is the local variable .

Global Scope:We also declare a variable ‘b’ outside any other python Variable scope,
this makes it global scope.

Consequently, we can read it anywhere in the program.


>>> a=1
>>> def counter():
a=2
print(a)
>>> counter()

Q7. Recursion

Python also accepts function recursion, which means a defined function can call itself.

Recursion is a common mathematical and programming concept. It means that a


function calls itself. This has the benefit of meaning that you can loop through data to
reach a result.

The developer should be very careful with recursion as it can be quite easy to slip into
writing a function which never terminates, or one that uses excess amounts of memory
or processor power. However, when written correctly recursion can be a very efficient
and mathematically-elegant approach to programming.

In this example, tri_recursion() is a function that we have defined to call itself


("recurse"). We use the k variable as the data, which decrements (-1) every time we
recu…

output Recursion Example Results


1

10

15

21

8. What is Module? Give detailed description of it with example.

A module is a file containing Python definitions and statements. A module can define
functions, classes, and variables. A module can also include runnable code. Grouping
related code into a module makes the code easier to understand and use. It also makes
the code logically organized.
# A simple module, calc.py
def add(x, y):
return (x+y)

def subtract(x, y):


return (x-y)

The import statement


We can use any Python source file as a module by executing an import
statement in some other Python source file.
When the interpreter encounters an import statement, it imports the module if
the module is present in the search path. A search path is a list of directories
that the interpreter searches for importing a module. For example, to import the
module calc.py, we need to put the following command at the top of the script :

# importing module calc.py


import calc

print(add(10, 2))

The from import Statement


Python’s from statement lets you import specific attributes from a module.
The from .. import .. has the following syntax
# importing sqrt() and factorial from the
# module math
from math import sqrt, factorial

# if we simply do "import math", then


# math.sqrt(16) and math.factorial()
# are required.
print(sqrt(16))
print(factorial(6))

The from import * Statement

The * symbol used with the from import the statement is used to import all the
names from a module to a current namespace.
Syntax:
from module_name import *
The use of * has it’s advantages and disadvantages. If you know exactly what
you will be needing from the module, it is not recommended to use *, else do
so.
9. File Handling

The key function for working with files in Python is the open() function.

The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:

"r" - Read - Default value. Opens a file for reading, error if the file does not exist

"a" - Append - Opens a file for appending, creates the file if it does not exist

"w" - Write - Opens a file for writing, creates the file if it does not exist

"x" - Create - Creates the specified file, returns an error if the file exists

In addition you can specify if the file should be handled as binary or text mode

"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (e.g. images)

Syntax

To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")

The code above is the same as:

f = open("demofile.txt", "rt")

Because "r" for read, and "t" for text are the default values, you do not need to specify
them.

Q 10.
Q11. Q13.(PIC)

Q14.

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the item with the specified value

reverse() Reverses the order of the list

sort()

Sets

add() Adds an element to the set

clear() Removes all the elements from the set

copy() Returns a copy of the set

difference() Returns a set containing the difference between two or more sets

difference_update() Removes the items in this set that are also included in another, spec

discard() Remove the specified item

intersection() Returns a set, that is the intersection of two other sets


intersection_update() Removes the items in this set that are not present in other, specified

isdisjoint() Returns whether two sets have a intersection or not

issubset() Returns whether another set contains this set or not

issuperset() Returns whether this set contains another set or not

pop() Removes an element from the set

remove() Removes the specified element

symmetric_difference() Returns a set with the symmetric differences of two sets

symmetric_difference_update() inserts the symmetric differences from this set and another

union() Return a set containing the union of sets

update() Update the set with the union of this set and others

Dict

clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary


fromkeys() Returns a dictionary with the specified keys and value

get() Returns the value of the specified key

items() Returns a list containing a tuple for each key value pair

keys() Returns a list containing the dictionary's keys

pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair

setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified v

update() Updates the dictionary with the specified key-value pairs

values() Returns a list of all the values in the dictionary

16. Membership operators

The membership operators in Python are used to test whether a value is found within a sequence. For example,
you can use the membership operators to test for the presence of a substring in a string. Two membership
operators exist in Python:

in – evaluates to True if the value in the left operand appears in the sequence found in the right operand. For
example, ‘Hello’ in ‘Hello world’ returns True because the substring Hello is present in the string Hello
world!.
not in – evaluates to True if the value in the left operand doesn’t appear in the sequence found in the right
operand. For example, ‘house’ in ‘Hello world’ returns True because the substring house is not present in the
string Hello world!.

Here are a couple of examples:

>>> 'Hello' in 'Hello world!'

True

>>>

>>> 'Hello' in 'Hello world!'

True

>>> 'house' in 'Hello world!'

False

>>> 'hello' in 'Hello world!'

False // note that Python is case sensitive

>>> 'orld' in 'Hello world!'

True

>>> 'Hello' not in 'Hello world!'

False

>>> 'car' not in 'Hello world!'

True

>>> 'house' not in 'Hello world!'

True
>>>

15.I.Using slicing technique


This is the easiest and the fastest way to clone a list. This method is considered when
we want to modify a list and also keep a copy of the original. In this we make a copy of
the list itself, along with the reference. This process is also called cloning. This
technique takes about 0.039 seconds and is the fastest technique.
Attention geek! Strengthen your foundations with the Python Programming
Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts
with the Python DS Course. And to begin with your Machine Learning Journey,
join the Machine Learning - Basic Level Course

# Python program to copy or clone a list

# Using the Slice Operator

def Cloning(li1):

li_copy = li1[:]

return li_copy

# Driver Code

li1 = [4, 8, 2, 10, 15, 18]

li2 = Cloning(li1)

print("Original List:", li1)

print("After Cloning:", li2)

Output:
Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]

(II)Using the extend() method


The lists can be copied into a new list by using the extend() function. This appends each
element of the iterable object (e.g., anothre list) to the end of the new list. This takes
around 0.053 second to complete.
Example:
# Python code to clone or copy a list

# Using the in-built function extend()

def Cloning(li1):

li_copy = []

li_copy.extend(li1)

return li_copy

# Driver Code

li1 = [4, 8, 2, 10, 15, 18]

li2 = Cloning(li1)

print("Original List:", li1)

print("After Cloning:", li2)

Output:
Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]

III. Using the list() method


This is the simplest method of cloning a list by using the builtin function list(). This takes
about 0.075 seconds to complete.
Example:

# Python code to clone or copy a list

# Using the in-built function list()

def Cloning(li1):

li_copy = list(li1)
return li_copy

# Driver Code

li1 = [4, 8, 2, 10, 15, 18]

li2 = Cloning(li1)

print("Original List:", li1)

print("After Cloning:", li2)

Output:
Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]

1. Using the method of Shallow Copy


This method of copying using copy.copy is well explained in the article Shallow
Copy. This takes around 0.186 seconds to complete.

2. Using list comprehension


The method of list comprehension can be used to copy all the elements individually
from one list to another. This takes around 0.217 seconds to complete.

# Python code to clone or copy a list

# Using list comprehension

def Cloning(li1):

li_copy = [i for i in li1]

return li_copy

# Driver Code

li1 = [4, 8, 2, 10, 15, 18]


# Python code to clone or copy a list

# Using list comprehension

def Cloning(li1):

li_copy = [i for i in li1]

return li_copy

# Driver Code

li1 = [4, 8, 2, 10, 15, 18]

li2 = Cloning(li1)

print("Original List:", li1)

print("After Cloning:", li2)

Output:
Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]

IV. Using the append() method


This can be used for appending and adding elements to list or copying them to a new list.
It is used to add elements to the last position of list. This takes around 0.325 seconds to
complete and is the slowest method of cloning.

# Python code to clone or copy a list

# Using append()

def Cloning(li1):

li_copy =[]

for item in li1: li_copy.append(item)


return li_copy

# Driver Code

li1 = [4, 8, 2, 10, 15, 18]

li2 = Cloning(li1)

print("Original List:", li1)

print("After Cloning:", li2)

Output:
Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]
V. Using the copy() method
The inbuilt method copy is used to copy all the elements from one list to another. This
takes around 1.488 seconds to complete.
Example:

# Python code to clone or copy a list

# Using bilt-in method copy()

def Cloning(li1):

li_copy =[]

li_copy = li1.copy()

return li_copy

# Driver Code

li1 = [4, 8, 2, 10, 15, 18]

li2 = Cloning(li1)

print("Original List:", li1)


print("After Cloning:", li2)

Output:
Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]
VI. Using the method of Deep Copy
This method of copying is well explained in the article Deep Copy. This takes around
10.59 seconds to complete and is the slowest method of cloning.
Referred to Stack Overflow.

Unit II
17. List and explain types of Inheritance in python with example.

ANS:-Inheritance – Types of Inheritance in Python


What is Inheritance in Python: Inheritance in python programming is the concept of deriving a
new class from an existing class. Using the concept of inheritance we can inherit the properties
of the existing class to our new class. The new derived class is called the child class and the
existing class is called the parent class. Hierarchical inheritance in python, Multilevel inheritance
in python including Single and Multiple inheritances are the types of inheritance.

Syntax to implement inheritance:

#syntax_of_inheritance
class parent_class:
#parent_class members
pass
class child_class(parent_class):
#child_class members
pass

obj = child_class()

Example 1:

#Inheritance Example
class A:
x = "Parent class variable"
class B(A):
pass

c1 = A()
obj = B()print(obj.x)
Output:#OutputParent class variable

Explanation: Here you can easily observe that we have created the object of class B. And we do
not have any class members in our class B. But we inherited the properties of class A into class
B. The class variable in class A is inherited from class B. Hence it is called using the object of
class B.
Types of Inheritance in Python Programming

Types of inheritance: There are five types of inheritance in python programming:

1). Single inheritance


2). Multiple inheritances
3). Multilevel inheritance
4). Hierarchical inheritance
5). Hybrid inheritance

(i). Single inheritance: When child class is derived from only one parent class. This is called
single inheritance. The example we did above is the best example for single inheritance in
python programming.

Flow Diagram of single inheritance in python programming

Syntax of single inheritance:

#syntax_of_single_inheritance
class class1: #parent_class
pass
class class2(class1): #child_class
pass

obj_name = class2()

Example 2:

#syntax_of_single_inheritance
class Brands: #parent_class
brand_name_1 = "Amazon"
brand_name_2 = "Ebay"
brand_name_3 = "OLX"
class Products(Brands): #child_class
prod_1 = "Online Ecommerce Store"
prod_2 = "Online Store"
prod_3 = "Online Buy Sell Store"

obj_1 = Products() #Object_creationprint(obj_1.brand_name_1+" is an "+obj_1.prod_1)print(obj_1.brand_name_2+" is an


"+obj_1.prod_2)print(obj_1.brand_name_3+" is an "+obj_1.prod_3)

Output:

#Output#Amazon is an Online Ecommerce Store#Ebay is an Online Store#OLX is an Online Buy Sell Store

(ii). Multiple Inheritance: When child class is derived or inherited from the more than one parent
class. This is called multiple inheritance. In multiple inheritance, we have two parent
classes/base classes and one child class that inherits both parent classes’ properties.

Diagram of Multiple Inheritance

Syntax of multiple inheritance:

#syntax_of_multiple_inheritance
class parent_1:
pass
class parent_2:
pass
class child(parent_1,parent_2):
pass

obj = child()
Example 3:

#example_of_multiple_inheritance
class Brands: #parent_class
brand_name_1 = "Amazon"
brand_name_2 = "Ebay"
brand_name_3 = "OLX"
class Products: #child_class
prod_1 = "Online Ecommerce Store"
prod_2 = "Online Store"
prod_3 = "Online Buy Sell Store"
class Popularity(Brands,Products):
prod_1_popularity = 100
prod_2_popularity = 70
prod_3_popularity = 60

obj_1 = Popularity() #Object_creationprint(obj_1.brand_name_1+" is an "+obj_1.prod_1)print(obj_1.brand_name_2+" is an


"+obj_1.prod_2)print(obj_1.brand_name_3+" is an "+obj_1.prod_3)

Output

#Output#Amazon is an Online Ecommerce Store popularity of 100#Ebay is an Online Store popularity of 70#OLX is an Online Buy Sell Store popularity of 60

(iii). Multilevel Inheritance: In multilevel inheritance, we have one parent class and child class
that is derived or inherited from that parent class. We have a grand-child class that is derived
from the child class. See the below-given flow diagram to understand more clearly.

Syntax of multilevel inheritance:

#Syntax_of_multilevel_inheritance
class A:
pass
class B(A):
pass
class C(B):
pass

obj = C()

Example 4:

#example_of_multilevel_inheritance
class Brands: #parent_class
brand_name_1 = "Amazon"
brand_name_2 = "Ebay"
brand_name_3 = "OLX"
class Products(Brands): #child_class
prod_1 = "Online Ecommerce Store"
prod_2 = "Online Store"
prod_3 = "Online Buy Sell Store"
class Popularity(Products): #grand_child_class
prod_1_popularity = 100
prod_2_popularity = 70
prod_3_popularity = 60

obj_1 = Popularity() #Object_creationprint(obj_1.brand_name_1+" is an "+obj_1.prod_1+" popularity of


"+str(obj_1.prod_1_popularity))print(obj_1.brand_name_2+" is an "+obj_1.prod_2+" popularity of "+str(obj_1.prod_2_popularity))print(obj_1.brand_name_3+" is an
"+obj_1.prod_3+" popularity of "+str(obj_1.prod_3_popularity))
#Output#Amazon is an Online Ecommerce Store popularity of 100#Ebay is an Online Store popularity of 70#OLX is an Online Buy Sell Store popularity of 60

4). Hierarchical inheritance: When we derive or inherit more than one child class from
one(same) parent class. Then this type of inheritance is called hierarchical inheritance.

Flow Diagram of Hierarchical Inheritance in Python Programming

Syntax of Hierarchical Inheritance:

#syntax_of_hierarchical_inheritance
class A: #parent_class
pass
class B(A): #child_class
pass
class C(A): #child_class
pass
class D(A): #child_class
pass

obj_1 = B() #Object_creation


obj_2 = C()
obj_3 = D()

Example 5:

#example
class Brands: #parent_class
brand_name_1 = "Amazon"
brand_name_2 = "Ebay"
brand_name_3 = "OLX"
class Products(Brands): #child_class
prod_1 = "Online Ecommerce Store"
prod_2 = "Online Store"
prod_3 = "Online Buy Sell Store"
class Popularity(Brands): #grand_child_class
prod_1_popularity = 100
prod_2_popularity = 70
prod_3_popularity = 60
class Value(Brands):
prod_1_value = "Excellent Value"
prod_2_value = "Better Value"
prod_3_value = "Good Value"

obj_1 = Products() #Object_creation


obj_2 = Popularity()
obj_3 = Value()print(obj_1.brand_name_1+" is an "+obj_1.prod_1)print(obj_1.brand_name_1+" is an "+obj_1.prod_1)print(obj_1.brand_name_1+" is an
"+obj_1.prod_1)

Output:

#Output#Amazon is an Online Ecommerce Store#Ebay is an Online Store#OLX is an Online Buy Sell Store

5). Hybrid Inheritance: Hybrid inheritance satisfies more than one form of inheritance ie. It may
be consists of all types of inheritance that we have done above. It is not wrong if we say Hybrid
Inheritance is the combination of simple, multiple, multilevel and hierarchical inheritance. This
type of inheritance is very helpful if we want to use concepts of inheritance without any
limitations according to our requirements.

Syntax of Hybrid Inheritance:

#Syntax_Hybrid_inheritance
class PC:
pass
class Laptop(PC):
pass
class Mouse(Laptop):
pass
class Student3(Mouse, Laptop):
pass
# Driver's code
obj = Student3()

Note: There is no sequence in Hybrid inheritance that which class will inherit which particular
class. You can use it according to your requirements.

Example 6:

#Example_Hybrid_inheritanceclass PC:def fun1(self):print(“This is PC class”)


class Laptop(PC):def fun2(self):print(“This is Laptop class inheriting PC class”)
class Mouse(Laptop):def fun3(self):print(“This is Mouse class inheriting Laptop class”)
class Student(Mouse, Laptop):def fun4(self):print(“This is Student class inheriting PC and Laptop”)
# Driver’s code
obj = Student()
obj1 = Mouse()
obj.fun4()
obj.fun3()

OR
https://www.geeksforgeeks.org/types-of-inheritance-python/

18.Explain Operator Overloading in python with example.


Python Operator Overloading
Python operators work for built-in classes. But the same operator behaves differently with different types. For example,
the + operator will perform arithmetic addition on two numbers, merge two lists, or concatenate two strings.

This feature in Python that allows the same operator to have different meaning according to the context is called operator
overloading.

So what happens when we use them with objects of a user-defined class? Let us consider the following class, which tries to
simulate a point in 2-D coordinate system.

class Point:

def __init__(self, x=0, y=0):

self.x = x

self.y = y

p1 = Point(1, 2)

p2 = Point(2, 3)print(p1+p2)

Output

Traceback (most recent call last):

File "<string>", line 9, in <module>

print(p1+p2)

TypeError: unsupported operand type(s) for +: 'Point' and 'Point'

Here, we can see that a TypeError was raised, since Python didn't know how to add two Point objects together.

However, we can achieve this task in Python through operator overloading. But first, let's get a notion about special functions.

Python Special Functions


Class functions that begin with double underscore __ are called special functions in Python.

These functions are not the typical functions that we define for a class. The __init__() function we defined above is one of them. It
gets called every time we create a new object of that class.

There are numerous other special functions in Python. Visit Python Special Functions to learn more about them.

Using special functions, we can make our class compatible with built-in functions.

>>> p1 = Point(2,3)>>> print(p1)

<__main__.Point object at 0x00000000031F8CC0>


Suppose we want the print() function to print the coordinates of the Point object instead of what we got. We can define
a __str__() method in our class that controls how the object gets printed. Let's look at how we can achieve this:

class Point:

def __init__(self, x = 0, y = 0):

self.x = x

self.y = y

def __str__(self):

return "({0},{1})".format(self.x,self.y)

Now let's try the print() function again.

class Point:

def __init__(self, x=0, y=0):

self.x = x

self.y = y

def __str__(self):

return "({0}, {1})".format(self.x, self.y)

p1 = Point(2, 3)print(p1)

Output

(2, 3)

That's better. Turns out, that this same method is invoked when we use the built-in function str() or format() .

>>> str(p1)'(2,3)'

>>> format(p1)'(2,3)'

So, when you use str(p1) or format(p1) , Python internally calls the p1.__str__() method. Hence the name, special functions.

Now let's go back to operator overloading.

Overloading the + Operator


To overload the + operator, we will need to implement __add__() function in the class. With great power comes great
responsibility. We can do whatever we like, inside this function. But it is more sensible to return a Point object of the coordinate
sum.

class Point:

def __init__(self, x=0, y=0):


self.x = x

self.y = y

def __str__(self):

return "({0},{1})".format(self.x, self.y)

def __add__(self, other):

x = self.x + other.x

y = self.y + other.y

return Point(x, y)

Now let's try the addition operation again:

class Point:

def __init__(self, x=0, y=0):

self.x = x

self.y = y

def __str__(self):

return "({0},{1})".format(self.x, self.y)

def __add__(self, other):

x = self.x + other.x

y = self.y + other.y

return Point(x, y)

p1 = Point(1, 2)

p2 = Point(2, 3)

print(p1+p2)

Output

(3,5)

What actually happens is that, when you use p1 + p2 , Python calls p1.__add__(p2) which in turn is Point.__add__(p1,p2) . After this, the
addition operation is carried out the way we specified.

Similarly, we can overload other operators as well. The special function that we need to implement is tabulated below.

Operator Expression Internally

Addition p1 + p2 p1.__add__(p2)
Subtraction p1 - p2 p1.__sub__(p2)

Multiplication p1 * p2 p1.__mul__(p2)

Power p1 ** p2 p1.__pow__(p2)

Division p1 / p2 p1.__truediv__(p2)

Floor Division p1 // p2 p1.__floordiv__(p2)

Remainder (modulo) p1 % p2 p1.__mod__(p2)

Bitwise Left Shift p1 << p2 p1.__lshift__(p2)

Bitwise Right Shift p1 >> p2 p1.__rshift__(p2)

Bitwise AND p1 & p2 p1.__and__(p2)

Bitwise OR p1 | p2 p1.__or__(p2)

Bitwise XOR p1 ^ p2 p1.__xor__(p2)

Bitwise NOT ~p1 p1.__invert__()

Overloading Comparison Operators


Python does not limit operator overloading to arithmetic operators only. We can overload comparison operators as well.

Suppose we wanted to implement the less than symbol < symbol in our Point class.

Let us compare the magnitude of these points from the origin and return the result for this purpose. It can be implemented as
follows.

# overloading the less than operatorclass Point:

def __init__(self, x=0, y=0):

self.x = x

self.y = y

def __str__(self):

return "({0},{1})".format(self.x, self.y)

def __lt__(self, other):

self_mag = (self.x ** 2) + (self.y ** 2)

other_mag = (other.x ** 2) + (other.y ** 2)

return self_mag < other_mag


p1 = Point(1,1)

p2 = Point(-2,-3)

p3 = Point(1,-1)

# use less thanprint(p1<p2)print(p2<p3)print(p1<p3)

Output

True

False

False

Similarly, the special functions that we need to implement, to overload other comparison operators are tabulated below.

Operator Expression Internally

Less than p1 < p2 p1.__lt__(p2)

Less than or equal to p1 <= p2 p1.__le__(p2)

Equal to p1 == p2 p1.__eq__(p2)

Not equal to p1 != p2 p1.__ne__(p2)

Greater than p1 > p2 p1.__gt__(p2)

Greater than or equal to p1 >= p2 p1.__ge__(p2)

19.Explain Data abstraction/Data hiding.


---Abstraction is used to hide the internal functionality of the function from the users. The users only interact
with the basic implementation of the function, but inner working is hidden. User is familiar with that "what
function does" but they don't know "how it does."
---Data Hiding in Python

An object's attributes may or may not be visible outside the class definition. You need to name attributes with a
double underscore prefix, and those attributes then are not be directly visible to outsiders.

Advantages of Data Hiding


 The objects within the class are disconnected from irrelevant data.
 It heightens the security against hackers that are unable to access confidential data.
 It prevents programmers from accidental linkage to incorrect data. If the programmer links this
data in the code, it will only return an error by indicating corrections in the mistake.
 It isolates objects as the basic concept of OOP.
 It helps to prevent damage to volatile data by hiding it from the public.
Disadvantages of Data Hiding
 It may sometimes force the programmer to use extra coding.
 The link between the visible and invisible data makes the objects work faster, but data hiding
prevents this linkage.
 Data hiding can make it harder for a programmer and need to write lengthy codes to create
effects in the hidden data.
Thus, data hiding is helpful in Python when it comes to privacy and security to specific
information within the application. It increases work for programmers while linking hidden data
in the code. But, the advantages it offers are truly unavoidable.

20.Explain isinstance() method.

Python isinstance() Method


The isinstance() method checks if the object is an instance of the specified class or any of its subclass.

Syntax:
isinstance(object, classinfo)

Parameters:

1. object: An object to be checked.


2. classinfo: The class name or a tuple of class names.

Return Value:
Returns True if object is an instance of the specified classinfo, otherwise returns False.

In the following example, the isinstance() method checks for the built-in class instances.

Example: isinstance()
mystr = 'Hello World'
num = 100
flt = 10.2
print(isinstance(mystr, str)) # Trueprint(isinstance(mystr, int)) # False
print(isinstance(num, int)) # Trueprint(isinstance(num, str)) # False
print(isinstance(flt, float)) # Trueprint(isinstance(flt, int)) # False
Output
True
Flase
True
False
True
Flase

The following example checks the instances of the user-defined class.

Example: isinstance() with User-Defined Class

class student:
name = 'Elon'

std = student()
print(isinstance(std, student))print(isinstance(std, (student, list, str))) # tuple with class
namesprint(isinstance(std, list))
Output
True
True
False

In the above example, isinstance(std, (student, list, str)) specifies a tuple with three classes, student, list, and
'str'. It returns True because the specified instance is one of the classes in a tuple.

The following shows the working of isinstance() method with native data types.

Example: isinstance()

cities = ['Mumbai','Chicago','New York']


print(isinstance(cities,list)) print(isinstance(cities,(tuple, set))) print(isinstance(cities,tuple))
Output
True
False
False

21.Explain Method overriding.


ANS:- Overriding is the property of a class to change the implementation of a method provided by one of its base
classes.
Overriding is a very important part of OOP since it makes inheritance utilize its full power. By using method
overriding a class may "copy" another class, avoiding duplicated code, and at the same time enhance or customize
part of it. Method overriding is thus a part of the inheritance mechanism.
In Python method overriding occurs by simply defining in the child class a method with the same name of a method
in the parent class. When you define a method in the object you make this latter able to satisfy that method call, so
the implementations of its ancestors do not come in play.

class Parent(object):
def __init__(self):
self.value = 4
def get_value(self):
return self.value
class Child(Parent):
def get_value(self):
return self.value + 1

Now Child objects behave differently


>>> c = Child()
>>> c.get_value()
5

22.Explain issubclass() method


Python issubclass()
The issubclass() function checks if the class argument (first argument) is a subclass of classinfo
class (second argument).
The syntax of issubclass() is:

issubclass(class, classinfo)

issubclass() Parameters
issubclass() takes two parameters:

 class - class to be checked


 classinfo - class, type, or tuple of classes and types

Return Value from issubclass()


issubclass() returns:

 True if class is subclass of a class, or any element of the tuple

 False otherwise

Example: How issubclass() works?


class Polygon:
def __init__(polygonType):
print('Polygon is a ', polygonType)
class Triangle(Polygon):
def __init__(self):

Polygon.__init__('triangle')
print(issubclass(Triangle, Polygon))print(issubclass(Triangle, list))print(issubclass(Triangle, (list,
Polygon)))print(issubclass(Polygon, (list, Polygon)))

Output

True
False
True
True

23.Discuss Encapsulation.
24.Implementation of data structure in python.

Stack

Unlike an array structure, which allows random access at all the positions, a stack limits the
inserting and removing operation to only one side of the data sequence. A stack follows the last
in, first out (LIFO) principle.

In Python, stack can be implemented using a list. To follow the LIFO principle, inserting and
removing operations both occur at the tail of the list.

Python implementation of a stack

class
stack:

# by default pass in [] as inivial value

def __init__(self,initialVal=[]):

self.stack = initialVal

# push is to append to the tail of the list

def push(self,ele):

self.stack.append(ele)

return self.stack

# pop is to remove from the tail of the list

def pop(self):

return self.stack.pop(-1)

def checkStack(self):

print(self.stack)
def checkTop(self):

print(self.stack[-1])

Queue

Similar to a stack, the queue also limits the position for inserting and removing am operation on
a sequence of data. However, unlike a stack, a queue follows the first in, first out (FIFO)
principle.

In Python, a queue can also be implemented using a list. To follow the FIFO principle, the
inserting operation occurs at the tail of the list, while the removing operation occurs at the head
of the list.

Python implementation of a queue


class
queue:

# by default pass in [] as inivial value

def __init__(self,initialVal=[]):

self.queue = initialVal

# enqueue is to append to the tail of the list

def enqueue(self,ele):

self.queue.append(ele)

return self.queue

# dequeue is to remove from the head of the list

def dequeue(self):

return self.queue.pop(0)

def checkQueue(self):

print(self.queue)

def checkHead(self):

print(self.queue[0])
def checkTail(self):

print(self.queue[-1])

Python code for operations on one set


myset1
=
{1,2,3}

myset2 = {1,2,4,5}

# union

myset = myset1.union(myset2)

# intersection

myset = myset1.intersection(myset2)

# difference

myset = myset1.difference(myset2)

Set

A set object is an unordered collection of distinct hashable objects. It’s one of Python’s built-in
types and allows the dynamic adding and removing of elements, iteration, and operations with
another set objects.

Python code for operations on one setPython code for operations on two sets
# set
initialization
by passing
in a list

myset = set([1,2,3,3,3])

# set initialization using {}

myset = {1,2,3,3,3}

# iteration of set

for ele in myset:


print(ele)

# check if ele in set:

print(True if ele in myset else False)

# add an element to set:

myset.add(ele)

# remove an element from set

myset.remove(ele)

# get length of the set

print(len(myset))

Dictionary

A dictionary contains mapping information of (key, value) pairs. Given a key, the corresponding
value can be found in the dictionary. It’s also one of Python’s built-in types. The (key, value)
pairs can be dynamically added, removed, and modified. A dictionary also allows iteration
through the keys, values, and (key, value) pairs.

Python code for operations on a dictionary


# dictionary
initialization
using {}

mydict = {'a':1,'b':2}

# add new (key,value) pair

mydict['c'] = 3

# modify existing (key,value) pair

mydict['a'] = 5

# remove (key,value) pair


mydict.pop('a')

# get length of the dictionary

print(len(mydict))

# iteration through keys

for key in mydict.keys():

print(key)

# iteration through values

for value in mydict.values():

print(value)

# iteration through (key,value) pairs

for key,value in mydict.items():

print(key,value)

Linked List

A linked list is a linear data structure, with the previous node pointing to the next node. It can be
implemented by defining a ListNode class.

class
ListNode:

def _init_(self,val):

self.val = val

self.next = None

# initiation of linked list

headNode = ListNode(1)

secondNode = ListNode(2)

thirdNode = ListNode(3)
headNode.next = secondNode

secondNode.next = thirdNode

# iterate through the linked list

curNode = headNode

while curNode:

print(curNode.val)

curNode = curNode.next

# insert new listnode with value of 5 in between the secondNode and thirdNode

curNode = headNode

while curNode.val != 2:

curNode = curNode.next

newNode = ListNode(5)

newNode.next = curNode.next

curNode.next = newNode

# remove the listnode with value of 5

curNode = headNode

while curNode.next.val != 5:

curNode = curNode.next

curNode.next = curNode.next.next

25. Implementation of linear search/binary search (Recursive/Non-Recursive).

Linear search:-
def linearsearch(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
arr = ['t','u','t','o','r','i','a','l']
x = 'a'print("element found at index "+str(linearsearch(arr,x)))
Here we linearly scan the list with the help of for loop.

Output
element found at index 6

BINARY SEARCH:-
Python 3 program for recursive binary search.
# Modifications needed for the older Python 2 are found in comments.

# Returns index of x in arr if present, else -1


def binary_search(arr, low, high, x):

# Check base case


if high >= low:

mid = (high + low) // 2

# If element is present at the middle itself


if arr[mid] == x:
return mid

# If element is smaller than mid, then it can only


# be present in left subarray
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)

# Else the element can only be present in right subarray


else:
return binary_search(arr, mid + 1, high, x)

else:
# Element is not present in the array
return -1

# Test array
arr = [ 2, 3, 4, 10, 40 ]
x = 10

# Function call
result = binary_search(arr, 0, len(arr)-1, x)

if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")

Output: Element is present at index 3

Iterative:
 Python3

# Iterative Binary Search Function


# It returns index of x in given array arr if present,
# else returns -1
def binary_search(arr, x):
low = 0
high = len(arr) - 1
mid = 0

while low <= high:

mid = (high + low) // 2

# If x is greater, ignore left half


if arr[mid] < x:
low = mid + 1

# If x is smaller, ignore right half


elif arr[mid] > x:
high = mid - 1

# means x is present at mid


else:
return mid

# If we reach here, then the element was not present


return -1

# Test array
arr = [ 2, 3, 4, 10, 40 ]
x = 10

# Function call
result = binary_search(arr, x)

if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")

Output: Element is present at index 3

26.Explain Wrappers Function.


---Wrappers around the functions are also knows as decorators which are a very powerful and
useful tool in Python since it allows programmers to modify the behavior of function or class.
Decorators allow us to wrap another function in order to extend the behavior of the wrapped
function, without permanently modifying it. In Decorators, functions are taken as the argument
into another function and then called inside the wrapper function.
Syntax:
@wrapper
def function(n):
statements(s)
function = wrapper(function)

27.Write a code to implement divide and conquer /merge sort/selection sort.

divide and conquer:-


def bsearch(list, val):
list_size = len(list) - 1
idx0 = 0
idxn = list_size# Find the middle most value
while idx0 <= idxn:
midval = (idx0 + idxn)// 2
if list[midval] == val:
return midval# Compare the value the middle most value
if val > list[midval]:
idx0 = midval + 1
else:
idxn = midval - 1
if idx0 > idxn:
return None# Initialize the sorted list
list = [2,7,19,34,53,72]
# Print the search resultprint(bsearch(list,72))print(bsearch(list,11))

Output

When the above code is executed, it produces the following result −


5
None
--SELECTION SORT

. def selectionSort(X):
. for i in range(len(X)):
. min_index = i
. for j in range(i+1, len(X)):
. if X[min_index] > X[j]:
. min_index = j
. X[i], X[min_index] = X[min_index], X[i]
. return X
. X = [36, 21, 12, 19, 5]
. sorted_X = selectionSort(X)
. print(sorted_X)

---Merge sort:-
def mergeSort(arr):

if len(arr) > 1:

a = len(arr)//2

l = arr[:a]

r = arr[a:]

# Sort the two halves


mergeSort(l)

mergeSort(r)

b=c=d=0

while b < len(l) and c < len(r):

if l[b] < r[c]:

arr[d] = l[b]

b += 1

else:

arr[d] = r[c]

c += 1

d += 1

while b < len(l):

arr[d] = l[b]

b += 1

d += 1

while c < len(r):

arr[d] = r[c]

c += 1

d += 1

def printList(arr):

for i in range(len(arr)):

print(arr[i], end=" ")

print()

# Driver program
if __name__ == '__main__':

arr = [0,1,3,5,7,9,2,4,6,8]

mergeSort(arr)

print("Sorted array is: ")

printList(arr)

Output
0,1,2,3,4,5,6,7,8,9

28.Write a code to implement time sort.


29.Linked list concept in python.
A linked list is a sequence of data elements, which are connected together via links. Each data element
contains a connection to another data element in form of a pointer. Python does not have linked lists in its
standard library. We implement the concept of linked lists using the concept of nodes as discussed in the
previous chapter.
We have already seen how we create a node class and how to traverse the elements of a node.In this chapter
we are going to study the types of linked lists known as singly linked lists. In this type of data structure there
is only one link between any two data elements. We create such a list and create additional methods to insert,
update and remove elements from the list.

Creation of Linked list


A linked list is created by using the node class we studied in the last chapter. We create a Node object and
create another class to use this ode object. We pass the appropriate values through the node object to point the
to the next data elements. The below program creates the linked list with three data elements. In the next
section we will see how to traverse the linked list.

Traversing a Linked List


Singly linked lists can be traversed in only forward direction starting form the first data element. We simply
print the value of the next data element by assigning the pointer of the next node to the current data element.

Insertion in a Linked List


Inserting element in the linked list involves reassigning the pointers from the existing nodes to the newly
inserted node. Depending on whether the new data element is getting inserted at the beginning or at the
middle or at the end of the linked list, we have the below scenarios.

Inserting at the Beginning

This involves pointing the next pointer of the new data node to the current head of the linked list. So the
current head of the linked list becomes the second data element and the new node becomes the head of the
linked list.

Inserting at the End

This involves pointing the next pointer of the the current last node of the linked list to the new data node. So
the current last node of the linked list becomes the second last data node and the new node becomes the last
node of the linked list.

Inserting in between two Data Nodes

This involves changing the pointer of a specific node to point to the new node. That is possible by passing in
both the new node and the existing node after which the new node will be inserted. So we define an additional
class which will change the next pointer of the new node to the next pointer of middle node. Then assign the
new node to next pointer of the middle node.

Removing an Item
We can remove an existing node using the key for that node. In the below program we locate the previous
node of the node which is to be deleted.Then, point the next pointer of this node to the next node of the node
to be deleted.

30.Explain Hashing/hash table.


Hash tables are a type of data structure in which the address or the index value of the data element is
generated from a hash function. That makes accessing the data faster as the index value behaves as a key for
the data value. In other words Hash table stores key-value pairs but the key is generated through a hashing
function.
So the search and insertion function of a data element becomes much faster as the key values themselves
become the index of the array which stores the data.
In Python, the Dictionary data types represent the implementation of hash tables. The Keys in the dictionary
satisfy the following requirements.
----The keys of the dictionary are hashable i.e. the are generated by hashing function which generates unique
result for each unique value supplied to the hash function.
----The order of data elements in a dictionary is not fixed.
So we see the implementation of hash table by using the dictionary data types as below.

Accessing Values in Dictionary


To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value.

Example

# Declare a dictionary
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
# Accessing the dictionary with its keyprint "dict['Name']: ", dict['Name']print "dict['Age']: ", dict['Age']

Output

When the above code is executed, it produces the following result −


dict['Name']: Zara
dict['Age']: 7

Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or
deleting an existing entry as shown below in the simple example −

Example

# Declare a dictionary
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entryprint "dict['Age']: ", dict['Age']print "dict['School']: ", dict['School']

Output

When the above code is executed, it produces the following result −


dict['Age']: 8
dict['School']: DPS School

Delete Dictionary Elements


You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can
also delete entire dictionary in a single operation.To explicitly remove an entire dictionary, just use the del
statement.

Example

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dictdel dict ; # delete entire dictionary
print "dict['Age']: ", dict['Age']print "dict['School']: ", dict['School']
Output

This produces the following result. Note that an exception is raised because after del dict dictionary does not
exist anymore.
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable

31.Describe methods of regular expression.


32.Expressions based on RE.
Note: Multiple choice questions/ fill in the blanks/ Finding output, type of questions can be asked.

Unit III

1)Describe methods to create an array using numpy.

I. Numpy arrays can be created very easily by passing a list to the


function numpy.array(). The python list when passed to this function gives us a Numpy
array.

import numpy as np

# making a python list li


li = [8,5,6,9,4,2]

# creating array out of it

numpy_array = np.array(li)

print(numpy_array)

numpy_array = np.array([5,7,4,1,5,6])

II

numpy_array = np.array([1,8,5,59,8,98], dtype = 'float')

print(numpy_array)

# let's try Numpy array with string as input

str = ['the','air','after','summer','rain']

arr = np.array(str, dtype = 'str')

print(arr)

(III.)The arange() function is one of the Numpy's most used method for creating an
array within a specified range. The first argument takes the starting point of the
array you want to create, second is the stop point and the third is the step
arange_array = np.arange(0,11,2) # writing 11 instead of 10 since range is exclusive

print("First array", arange_array)

arr = np.arange(50,121,4)

print("Second Array", arr)

arr1 = np.arange(15)

print("Third Array", arr1)

arr2 = np.arange(20,0,-1)

print("Reverse Array", arr2)


(IV)linspace() function takes arguments: start index, end index and the number of
elements to be outputted. These number of elements would be linearly spaced in
the range mentioned.
arr = np.linspace(15, 75, 10)

print("First Array", arr)

arr1 = np.linspace(50,100,25)

print("Second Array", arr1)

(V)
# arr of shape (5,2) with datatype=float filled with random values

arr = np.empty((5,2), dtype=float)

print("Array with Float values", arr)

# observe what happens when executed

arr1 = np.empty((4,4), dtype=int)

print("Second Array", arr1)

2. When to use reshape method in numpy? Explain with example.


Ans:

The numpy.reshape() function is available in NumPy package. As the name suggests, reshape
means 'changes in shape'. The numpy.reshape() function helps us to get a new shape to an array
without changing its data. Reshaping means changing the shape of an array.

The shape of an array is the number of elements in each dimension.

By reshaping we can add or remove dimensions or change number of elements in each dimension.

From 1d to 2d:
import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

newarr = arr.reshape(4, 3)

print(newarr)

From 1d to 3d:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

newarr = arr.reshape(2, 3, 2)

print(newarr)

From multi dimensional to 1d :

Flattening array means converting a multidimensional array into a 1D array.

We can use reshape(-1) to do this.

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])

newarr = arr.reshape(-1)

print(newarr)

3. Apply arithmetic operators, relational operators and logical operators on vector using numpy.
Ans:

array1 = np.array([10,20,30,40,50])
array2 = np.arange(5)
array2
array3 = array1 + array2
array4= array1*2
array5= array1**2
array6= np.power(array1,3)

A = np.array([[3,2],[0,1]])
B = np.array([[3,1],[2,1]])
Print(A+B)

a = np.array([ [True, True], [False, False]])


b = np.array([ [True, False], [True, False]])

print(np.logical_or(a, b))
print(np.logical_and(a, b))

import numpy as np

A = np.array([ [11, 12, 13], [21, 22, 23], [31, 32, 33] ])
B = np.array([ [11, 102, 13], [201, 22, 203], [31, 32, 303] ])

A == B
A>=B

4. Explain compound condition in numpy.

5. How to create an alias of an array using numpy?


Ans:

 The homogeneous multidimensional array is the main object of NumPy. It is basically a


table of elements which are all of the same type and indexed by a tuple of positive integers.
The dimensions are called axis in NumPy.
 The NumPy's array class is known as ndarray or alias array. The numpy.array is not the
same as the standard Python library class array.array. The array.array handles only one-
dimensional arrays and provides less functionality.

->import numpy as np
arr=np.array([1,2,3])
print(arr)

 We have imported numpy with alias name np. We have declared the 'arr' variable and
assigned the value returned by np.array() function. In the array() function, we have passed
only the elements, not axis. Lastly, we have tried to print the value of arr.

->import numpy as np
arr=np.array([[1,2.,3.],[4.,5.,7]])
print(arr)
 We have imported numpy with alias name np. We have declared the 'arr' variable and
assigned the value returned by np.array() function. In the array() function, we have passed
the number of elements in different square brackets. Lastly, we have tried to print the value
of arr.

6. Briefly explain matrix module.


Ans:
A matrix is a rectangular 2-dimensional array which stores the data in rows and columns. The matrix can store any
data type such as number, strings, expressions, etc.
->matrix = [[ 'Arun', 25, 90, 74],
['Sachin', 410, 87.50, 130],
[56, 'Abhinay', 253, 471]]
print("The matrix is: ", matrix)

->matrix = [[ 'Arun', 25, 90, 74],


['Sachin', 410, 87.50, 130],
[56, 'Abhinay', 253, 471]]

matrix_length = len(matrix)

#To read the last element from each row.


for i in range(matrix_length):
print(matrix[i][-1])

->mat1 = [[10, 13, 44],


[11, 2, 3],
[5, 3, 1]]

mat2 = [[7, 16, -6],


[9, 20, -4],
[-1, 3 , 27]]

mat3 = [[0,0,0],
[0,0,0],
[0,0,0]]
matrix_length = len(mat1)

#To Add mat1 and mat2 matrices


for i in range(len(mat1)):
for k in range(len(mat2)):
mat3[i][k] = mat1[i][k] + mat2[i][k]

#To Print the matrix


print("The sum of Matrix mat1 and mat2 = ", mat3)

->import numpy as np
mat1 = np.array([[4, 6], [5, 10]])
mat2 = np.array([[3, -1], [11, 22]])
mat3 = mat1.dot(mat2)
print("The matrix is:")
print(mat3)

7. Explain generation of random number,all zero valued matrices,all ones valued matrices, identity
matrix.
8. Draw plot for given data using Pylab/ matplotlib and numpy.
Ans:

 The plot() function is used to draw points (markers) in a diagram.

 By default, the plot() function draws a line from point to point.

 The function takes parameters for specifying points in the diagram.

 Parameter 1 is an array containing the points on the x-axis.

 Parameter 2 is an array containing the points on the y-axis.

->import matplotlib.pyplot as plt


import numpy as np

xpoints = np.array([1, 8])


ypoints = np.array([3, 10])

plt.plot(xpoints, ypoints)
plt.show()

 To plot only the markers, you can use shortcut string notation parameter 'o', which means 'rings'

->import matplotlib.pyplot as plt


import numpy as np

xpoints = np.array([1, 8])


ypoints = np.array([3, 10])

plt.plot(xpoints, ypoints, 'o')


plt.show()

9. Implementation of client and server in context of chat application.


10. List and explain methods supported by tkinter to place/arrange various widgets in
window.
Ans:

Tkinter has three built-in layout managers that use geometric methods to position
widgets in an application frame:
 pack() organizes widgets in horizontal and vertical boxes that are limited to left,
right, top, bottom positions. Each box is offset and relative to each other.
 place() places widgets in a two dimensional grid using x and y absolute
coordinates.
 grid() locates widgets in a two dimensional grid using row and column absolute
coordinates.
pack is the easiest layout manager to use with Tkinter. Instead of declaring the precise
location of a widget, pack() declares the positioning of widgets in relation to each other.
However, pack() is limited in precision compared to place() and grid() which feature
absolute positioning. For simple positioning of widgets vertically or horizontally in
relation to each other, pack() is the layout manager of choice.
pack() has four padding options:
 Internal padding
 External padding
 Padx, which pads along the x axis
 Pady, which pads along the y axis
 import tkinter as tk

 root = tk.Tk()

 test = tk.Label(root, text="red", bg="red", fg="white")
 test.pack(padx=5, pady=15, side=tk.LEFT)
 test = tk.Label(root, text="green", bg="green", fg="white")
 test.pack(padx=5, pady=20, side=tk.LEFT)
 test = tk.Label(root, text="purple", bg="purple", fg="white")
 test.pack(padx=5, pady=20, side=tk.LEFT)

 root.mainloop()

place() lets you position a widget either with absolute x,y coordinates, or relative to
another widget.
Example
In this example, three labels are positioned diagonally using x,y coordinates.
from tkinter import *

root = Tk()

root.geometry('250x200+250+200')

Label(root, text="Position 1 : x=0, y=0", bg="#FFFF00", fg="white").place(x=5, y=0)

Label(root, text="Position 2 : x=50, y=40", bg="#3300CC", fg="white").place(x=50, y=40)


Label(root, text="Position 3 : x=75, y=80", bg="#FF0099", fg="white").place(x=75, y=80)

root.mainloop()

grid() positions widgets in a two dimensional grid of rows and columns similar to a
spreadsheet.
Example
In this example, four labels are positioned in a grid of rows and columns:
from tkinter import *

root = Tk()

Label(text="Position 1", width=10).grid(row=0, column=0)

Label(text="Position 2", width=10).grid(row=0, column=1)

Label(text="Position 3", width=10).grid(row=1, column=0)

Label(text="Position 4", width=10).grid(row=1, column=1)

root.mainloop()

11. Explain steps to create widgets. Write Python program to display a label on clicking a
button using tkinter.(any widgets)
12. Significance of Intvar class in tkinter.
Ans:

A variable defined using IntVar() function holds integer data where we can set integer
data and can retrieve it as well using getter and setter methods. These variables can be
passed to various widget parameters, for example, the variable parameter of Radio
Button and CheckBox Button, textvariable parameter of Label Widget, etc as we will
see in examples. Once these variables get connected to widgets, the connection works
both ways: if the IntVar() variable changes, the value of the widget also gets updated
automatically with the new value.

We need Tkinter IntVar() function which takes the following parameters to define
the variable:
 master: It is the window with which IntVar() variable is associated. If nothing is
specified, it defaults to root window.
 value: The initial value given to the integervariable. Defaults to 0.
 name: The name given to the defined variable. Default value is PY_VARnum(like
PY_VAR1, PY_VAR2, etc).
import tkinter as tk

master_window = tk.Tk()
master_window.geometry("250x150")
master_window.title("IntVar Example")
integer_variable = tk.IntVar(master_window, 255)

label = tk.Label(master_window, textvariable=integer_variable, height=250)


label.pack()

master_window.mainloop()

13. Write a code to draw rectangle with border color of blue and inner filling of color yellow using
turtle.
Ans:

import turtle
tr = turtle.Turtle()
tr.fillcolor('yellow')
tr.begin_fill()
for i in range(2):
tr.forward(250)
tr.right(90)
tr.forward(150)
tr.right(90)
tr.end_fill()
turtle.done()

OR
14. List and Explain Methods supported by turtle module.

You might also like