PSC QBank Answerkey
PSC QBank Answerkey
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.
5. break branching statement is used to break the loop and transfer control
count = 0
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).
print("List Iteration")
for i in l:
print(i)
print("\nTuple Iteration")
for i in t:
print(i)
# Iterating over a String
print("\nString Iteration")
s = "Geeks"
for i in s :
print(i)
print("\nDictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d :
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.
Example:
avg_number(3, 4)
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
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.
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.
John
Mary
Nina
('John', 'LA')
('Mary', 'NY')
('Nina', 'DC')
print(b)
func()
Global Scope:We also declare a variable ‘b’ outside any other python Variable scope,
this makes it global scope.
Q7. Recursion
Python also accepts function recursion, which means a defined function can call itself.
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.
10
15
21
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)
print(add(10, 2))
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.
"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
Syntax
To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")
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.
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
sort()
Sets
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
symmetric_difference_update() inserts the symmetric differences from this set and another
update() Update the set with the union of this set and others
Dict
items() Returns a list containing a tuple for each key value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified v
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!.
True
>>>
True
False
True
False
True
True
>>>
def Cloning(li1):
li_copy = li1[:]
return li_copy
# Driver Code
li2 = Cloning(li1)
Output:
Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]
def Cloning(li1):
li_copy = []
li_copy.extend(li1)
return li_copy
# Driver Code
li2 = Cloning(li1)
Output:
Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]
def Cloning(li1):
li_copy = list(li1)
return li_copy
# Driver Code
li2 = Cloning(li1)
Output:
Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]
def Cloning(li1):
return li_copy
# Driver Code
def Cloning(li1):
return li_copy
# Driver Code
li2 = Cloning(li1)
Output:
Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]
# Using append()
def Cloning(li1):
li_copy =[]
# Driver Code
li2 = Cloning(li1)
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:
def Cloning(li1):
li_copy =[]
li_copy = li1.copy()
return li_copy
# Driver Code
li2 = Cloning(li1)
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.
#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
(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.
#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"
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.
#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
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
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
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.
#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
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"
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_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:
OR
https://www.geeksforgeeks.org/types-of-inheritance-python/
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:
self.x = x
self.y = y
p1 = Point(1, 2)
p2 = Point(2, 3)print(p1+p2)
Output
print(p1+p2)
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.
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.
class Point:
self.x = x
self.y = y
def __str__(self):
return "({0},{1})".format(self.x,self.y)
class Point:
self.x = x
self.y = y
def __str__(self):
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.
class Point:
self.y = y
def __str__(self):
x = self.x + other.x
y = self.y + other.y
return Point(x, y)
class Point:
self.x = x
self.y = y
def __str__(self):
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.
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)
Bitwise OR p1 | p2 p1.__or__(p2)
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.
self.x = x
self.y = y
def __str__(self):
p2 = Point(-2,-3)
p3 = Point(1,-1)
Output
True
False
False
Similarly, the special functions that we need to implement, to overload other comparison operators are tabulated below.
Equal to p1 == p2 p1.__eq__(p2)
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.
Syntax:
isinstance(object, classinfo)
Parameters:
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
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()
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
issubclass(class, classinfo)
issubclass() Parameters
issubclass() takes two parameters:
False otherwise
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.
class
stack:
def __init__(self,initialVal=[]):
self.stack = initialVal
def push(self,ele):
self.stack.append(ele)
return self.stack
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.
def __init__(self,initialVal=[]):
self.queue = initialVal
def enqueue(self,ele):
self.queue.append(ele)
return self.queue
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])
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])
myset = {1,2,3,3,3}
# iteration of set
myset.add(ele)
myset.remove(ele)
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.
mydict = {'a':1,'b':2}
mydict['c'] = 3
mydict['a'] = 5
print(len(mydict))
print(key)
print(value)
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
headNode = ListNode(1)
secondNode = ListNode(2)
thirdNode = ListNode(3)
headNode.next = secondNode
secondNode.next = thirdNode
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
curNode = headNode
while curNode.next.val != 5:
curNode = curNode.next
curNode.next = curNode.next.next
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.
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")
Iterative:
Python3
# 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
. 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:]
mergeSort(r)
b=c=d=0
arr[d] = l[b]
b += 1
else:
arr[d] = r[c]
c += 1
d += 1
arr[d] = l[b]
b += 1
d += 1
arr[d] = r[c]
c += 1
d += 1
def printList(arr):
for i in range(len(arr)):
print()
# Driver program
if __name__ == '__main__':
arr = [0,1,3,5,7,9,2,4,6,8]
mergeSort(arr)
printList(arr)
Output
0,1,2,3,4,5,6,7,8,9
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.
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.
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.
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
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
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
Unit III
import numpy as np
numpy_array = np.array(li)
print(numpy_array)
numpy_array = np.array([5,7,4,1,5,6])
II
print(numpy_array)
str = ['the','air','after','summer','rain']
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
arr = np.arange(50,121,4)
arr1 = np.arange(15)
arr2 = np.arange(20,0,-1)
arr1 = np.linspace(50,100,25)
(V)
# arr of shape (5,2) with datatype=float filled with random values
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.
By reshaping we can add or remove dimensions or change number of elements in each dimension.
From 1d to 2d:
import numpy as np
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)
import numpy as np
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)
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
->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.
matrix_length = len(matrix)
mat3 = [[0,0,0],
[0,0,0],
[0,0,0]]
matrix_length = len(mat1)
->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:
plt.plot(xpoints, ypoints)
plt.show()
To plot only the markers, you can use shortcut string notation parameter 'o', which means 'rings'
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')
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()
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)
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.