Results for
"Python Programing Lab(R16)"
Python Programing Lab EXERCISE NO : 16(a) EXERCISE - 16(b)
EXERCISE NO : 16(a)
Description:
Here, we will implement a classical data structure known as a stack. Stack is a linear data structure which follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out).
Build any one classical data structure.
Mainly the following three basic operations are performed in the stack:
Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow condition.
Pop: Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be an Underflow condition.
Peek or Top: Returns top element of stack.
Applications of stack:
Balancing of symbols.
Infix to Postfix /Prefix conversion.
Redo-undo features at many places like editors, photoshop.
Forward and backward feature in web browsers.
Used in many algorithms like Tower of Hanoi, tree
traversals, stock span
problem, histogram problem.
Other applications can be Backtracking, Knight tour problem, rat in a maze, N queen
problem and sudoku solver.
EXERCISE - 16(b)
Description:
The knapsack problem or rucksack problem is a problem in combinatorial optimization.
Given a set of items, each with a weight and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible. It derives its name from the problem faced by someone who is constrained by a fixed-size knapsack and must fill it with the most valuable items.
Applications of 0/1 Knapsack problem
Knapsack problems appear in real-world decision-making processes in a wide variety of fields, such as finding the least wasteful way to cut raw materials,selection ofinvestmentsandportfolios,selection of assets forasset-backed securitization,and generating keys for the Merkle–Hellman and other knapsack cryptosystems.
Python Programing Lab EXERCISE NO : 15(a) EXERCISE - 15(b)
EXERCISE NO : 15(a)
Description:
The Python unit testing framework, sometimes referred to as “PyUnit,” is a Python languageversion of JUnit, by Kent Beck and Erich Gamma.
unittest supports test automation, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework. The unittest module provides classes that make it easy to support these qualities for a set of tests.
The unittest module provides a rich set of tools for constructing and running tests.
test case:
A test case is the smallest unit of testing. It checks for a specific response to a particular set of inputs. unittest provides a base class, TestCase, which may be used to create new test cases.
assertTrue:
assertTrue is an assertion method that creates a bool value from the received value and then
evaluating it.
In this program, We will create a module called even.py which consists of a function even_number. We will import this module in another file along with another module unittest.
Here, we will define a function test_fun_even in a class Test_even_numbers. In this function, we are passing a list of all even numbers. If all the numbers are even, then all test cases are satisfied and the output will be OK.
EXERCISE - 15(b)
Description:
In this program, We will create a module called reverse.py which consists of a function reverse_string. We will import this module in another file along with another module unittest.
Here, we will define a function test_fun_string in a class Test_string_equal. In this function, we are passing a list of all strings. If all the strings are palindromes, then all test cases are satisfied then the output will be OK.
Python Programing Lab EXERCISE NO : 14(a) EXERCISE - 14(b)
EXERCISE NO : 14(a)
Description:
Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides a fast and easy way to create GUI applications. Tkinter provides a powerful object- oriented interface to the Tk GUI toolkit.
Creating a GUI application using Tkinter is an easy task. All we need to do is perform the following steps:
- Import the Tkinter module.
- Create the GUI application main window.
- Add one or more widgets to the GUI application.
- Enter the main event loop to take action against each event triggered by the user.
EXERCISE - 14(b)
Description:
Turtle graphics is a popular way for introducing programming to kids. It was part of the original Logo programming language developed by Wally Feurzig and Seymour Papert in 1966.
The turtle module provides turtle graphics primitives, in both object-oriented and procedure- oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
To make use of the turtle methods and functionalities, we need to import turtle.”turtle”comes packed with the standard Python package and need not be installed externally. The roadmap for executing a turtle program follows 4 steps:
- Import the turtle module
- Create a turtle to control.
- Draw around using the turtle methods.
- Run turtle.done().
Python Programing Lab EXERCISE NO : 13(a) EXERCISE - 13(b)
EXERCISE NO : 13(a) EXERCISE - 13(b)
Description:
Class variable: A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class's methods. Class variables are not used as frequently as instance variables are.
Instance variable: A variable that is defined inside a method and belongs only to the current instance of a class.
self variable: The first argument to every method inside a class is a special variable self. Every time a class refers to one of its variables or methods, it must precede them by itself. The purpose ofself is to distinguish class‟s variables and methods from other variables and functions in theprogram.
For implementing Class Robot, a class variable called count, instance variable called nameand self variable self is used.To distinguish their usage, class variables are accessed using classname with dot(.) operator. Where as, instance variables are accessed using self with dot(.) operator.
For implementing Class ATM Machine, an instance variable called balance and self variable self is used to call the instance variable within the method of a class.
Python Programing Lab EXERCISE NO : 11(a) EXERCISE - 11(b) EXERCISE - 11(C)
EXERCISE NO : 11(a)
Description:
A matrix is a two-dimensional data structure. In python, matrix is a nested list. A list is created by placing all the items (elements) inside a square bracket [ ], separated by commas.
Example: A = [[1, 2, 3], [3, 4, 5]]
In the above example A represents a 2 * 3 matrix.
Accessing the elements of a matrix:
Similar to list we can access elements of a matrix by using square brackets [ ] after the variable like a[row-number][col_number].
Example: A = [[1, 2, 3], [3, 4, 5]]
In the above Matrix,
A[0] contains [1, 2, 3]
A[0][0] contains 1
EXERCISE - 11(b)
Description:
In order to perform addition of two matrices, the two matrices must have same number of rows and same number of columns.
We should use nested for loops to iterate through each row and each column. At each point, We add the corresponding elements in the two matrices and store it in the result.
Example :
Consider, Two 2*2 Matrices, A = [[2, 2], [2, 2]]
B = [[1, 1], [1, 1]]
If we perform Addition, then we will get the resultant matrix:
[[3, 3], [3, 3]].
EXERCISE - 11(C)
Description:
In order to perform multiplication of two matrices, then the number of columns in first matrix should be equal to the number of rows in second matrix.
When we multiply two matrices by each other, the resulting matrix will have as many columns as the biggest matrix in the equation.
For example, If we are multiplying a 3*3 by a 3*4 matrix, the resulting matrix will be a 3*4.
Example:
Consider two matrices,
A = [[1, 2, 3], [1, 1 ,1]] Which is a 2 * 3 matrix. B = [[1, 1], [2, 1], [3, 1]] Which is a 3 * 2 matrix.
If we perform multiplication of above matrices, then we will get [[14, 6], [6, 3]], Which is a 2*2 matrix.
Python Programing Lab EXERCISE NO : 12(a) EXERCISE - 12(b) EXERCISE - 12(C)
EXERCISE NO : 12(a)
Description:
pip is a package management system used to install and manage software packages written in Python. Many packages can be found in the Python Package Index(PyPI). Python 2.7.9 and later (on the python2 series), and Python 3.4 and later include pip (pip3 for Python 3) by default.
Pip is a recursive acronym that can stand for either "Pip Installs Packages" or "Pip Installs Python". One major advantage of pip is the ease of its command-line interface, which makes installing Python software packages as easy as issuing one command:
Write a procedure to Install packages requests, flask and explore them using pip.
pip install package-name
EXERCISE - 12(b)
Description:
The different steps involved in making request to the server is summarized below:
- Make Request:
Request is made by importing the requests module.
Example:
import requests
- Get the webpage using get():
r = requests.get('url')(r stands for Response object) HTTP POST request can be made using post()
r = requests.post('url', data = {'key':'value'})
- Response Content:
Content of the server's response can be read using text property.
Example:
import requests
r = requests.get('http://www.google.com') r.text
- Response status code:
It can be retrieved using r.status_code. Where, r is response object.
- Response headers:
Servers response headers can be viewed using r.headers.
- Cookies:
These can be obtained using r.cookies['cookie name']
EXERCISE - 12(C)
Description:
It defines classes which implement the client side of the HTTP and HTTPS protocols. The different steps involving in establishing connection to the server is:
1 Get HTTP Connection instance using httplib.HTTPConnection().
2 Request a web page using request() belonging to Connection instance.
3 Once the request is sent to the server, response is retrieved from the server using
getresponse() returning a HTTPResponse instance.
4 Read the response using response instance read().
5 Read status of response.
6 Close the connection to the server.
Python Programing Lab EXERCISE NO : 10(a) EXERCISE - 10(b) EXERCISE - 10(C)
EXERCISE NO : 10(a)
Description:
We need to write a function cumulative_product to find cumulative product of numbers in the list.
A Cumulative product is a sequence of partial products of a given sequence. For example,The cumulative product of sequence [a,b,c,.....] are a,ab,abc,.....
EXERCISE - 10(b)
Description:
We need to write a function reverse to reverse the given elements in a list. Reversing of a list is done by using the feature called slicing.
Python‟s list objects have an interesting feature called slicing. We can view it as anextension of the square brackets indexing syntax. It includes a special case where slicing a list with“[::-1]” produces a reversed copy.
EXERCISE - 10(C)
Description:
We need to write a functions to compute gcd, lcm of numbers. But here the constraint is each function should not exceed one line. For this, We are using lambda function.
lambda function:
We can use lambda keyword to create small anonymous functions. lambda functions can have any number of arguments but contains only one expression. The expression is evaluated and returned. They cannot contains commands or multiple expressions.
The general form of lambda function is as followes:
lambda arguments : expression
Python Programing Lab EXERCISE NO : 9(a) EXERCISE - 9(b) EXERCISE - 9(C)
Description:
Two strings are said to be nearly equal iff a single mutation applied to one string will result in another string. That means, Given two strings s1 and s2, find if s1 can be converted to s2 with exactly one edit(mutation). If yes, then the function should return a True value as the result. Otherwise, it must return a False value as the result.
EXERCISE - 9(b)
Description:
We need to write a function dups to find all duplicate elements in the list. If an element is repeated more than once in the list, then add that repeated element to the resultant list.
EXERCISE - 9(C)
Description:
We need to write a function unique to find all unique elements in the list. If an element is found only once in the list, then add that element to the resultant list.
Python Programing Lab EXERCISE - 8(b)
Description:
We need to write a function to find out mean, median and mode for a given set of numbers in a list. Mean, Median and Mode are 3 kinds of averages.
Mean:
It is the average we are used to, where we add up all the numbers and then divide by the total number of numbers.
Median:
It is the middle value in the list of numbers. To find median, all numbers have to be listed in numerical order from smallest to largest.
If total numbers are odd, then median is the middle value. If total numbers are even, then median is the average of 2 middle values.
Mode:
It is the value that occurs most often. If no number is repeated among a list of numbers then there is no mode for the list.
EXERCISE - 8(a)
Write a function ball_collide that takes two balls as parameters and computes if they are colliding. Your function should return a Boolean representing whether or not the balls are colliding. Hint: Represent a ball on a plane as a tuple of (x, y, r), r being the radius If (distance between two balls centers) <= (sum of their radii) then (they are colliding).
Description:
We need to write a function to find out whether two balls are colliding or not by using the distance formaulae i.e,, If (distance between two balls centers) <= (sum of their radii) then we must return True. Otherwise, we must return False. Distance between two ball centers can be calculated by using the formulae:
Here, We are using the concept functions.
Functions:
A function is a group of related statements that performs a specific task. Funtions helps break our program into smaller and modular chunks. As our program grows longer, functions make it more organized and manageable.
Further more, It avoids repetition and code reusable. The general form of a function is as follows:
def function_name(parameter_list):
“””doc-string”””
statement(s)
Function Call:
Once we define a function, We can call it from another function, program or even from the Python prompt. To call a function, We can simply type the function name with appropriate paramenters.
return statement:
This statement is used to exit a function and go back to place from where it was called. The general form of return statement is:
return [expression]
Python Programing Lab R16 EXERCISE - 7(b)
Python Programing Lab R16 EXERCISE - 7(b)
Aim:
Write a program to compute the number of characters, words and lines in a file.
Description:
Traverse each character in the file so that we can find number of characters, words and lines in a text file. Here, We are using the some of the basic methods of files.
We already discussed about open() and close() in the previous programs.
read():
If we need to extract string that contains all characters in the file, We can use read(). TheSyntax for read() in Python is:
str = file_object.read()
Program:
l
ines=0
words=0
chars=0
f=open('netaji.txt','r')
for line in f:
wordslist=line.split()
lines+=1
words+=len(wordslist)
chars+=len(line)
print("no.of characters",chars)
print("no.of words",words)
print("no.of lines",lines)
Output:
Python Programing Lab R16 EXERCISE - 7(a)
Python Programing Lab R16 EXERCISE - 7(a)
Aim:
Write a program to print each line of a file in reverse order.
Description:
Traverse each line of the file and we have to display every line contents in reverse order. Here, We are using the some of the basic methods of files and a string method strip().
Python provides basic functions and methods necessary to manipulate files by default. We can do most of the file manipulations using a file object.
open():
Before we can read or write a file, we have to open it using Python‟s built-in open(). This function creates a file object, which would be utilized to call other support methods associated with it.
The Syntax for opening a file object in Python is:
file_object = open(“Name of the file”,”Mode of the file”)
close():
This method of a file object flushes any unwritten information and closes the file object. Python automatically closes a file when the reference object of a file is reassigned to another file.
The Syntax for closing a file object in Python is:
file_object.close()
readlines():
This method will returns every line of the file as a list. The Syntax for readlines() in Python is:
file_lines = file_object.readlines()
This method returns a copy of the string in which all chars have been stripped from the beginning and end of the string (default whitespace characters).
The Syntax for strip() is Python is:
str.strip([chars])
Program:
f=open('netaji.txt','r').read()
#print(f)
print(f[::-1])
f=open('netaji.txt','r').readlines()
print(f)
print(f[::-1])
Output:
Python Programing Lab R16 EXERCISE - 6(b)
Python Programing Lab R16 EXERCISE - 6(b)
Aim:
Write a program to count frequency of characters in a given file. Can you use character frequency to tell whether the given file is a Python program file, C program file or a text file?
Description:
Traverse each character in the file and its occurrence is stored in the dictionary. Here, We are using the concept of files and a Dictionary.
Files:
Python provides basic functions and methods necessary to manipulate files by default. Some of the useful functions in this program are:
open():
Before we can read or write a file, we have to open it using Python‟s built-in open(). This function creates a file object, which would be utilized to call other support methods associated with it.
The Syntax for opening a file object in Python is:
file_object = open(“Name of the file”,”Mode of the file”)
read():
If we need to extract string that contains all characters in the file, We can use read().
TheSyntax for read() in Python is:
str = file_object.read()
Dictionary:
The dictionary is Python‟s built-in mapping type. Dictionaries map keys to values and these <key,value> pairs provides a useful way to store data in python. The only way to access the value part of the dictionary is by using the key.
We can specify the dictionary <key,value> pairs between '{' and '}'. <key,value> pairs arespecified as a list(separated by commas).
Program:
from collections import Counter
with open('netaji.txt','r') as f:
c=Counter()
for x in f:
print(x)
c+=Counter(x.strip())
print(c)
Output:
Python Programing Lab (R16) EXERCISE - 6(a)
Python Programing Lab (R16) EXERCISE - 6(a)
Aim:
Write a program combine_lists that combines these lists into a dictionary.
Description:
Python offers a range of compound data types often referred to as Sequences. List is one of the most frequently used and very versatile data type used in Python.
In Python Programming, a List is created by placing all the elements inside a square bracket [ ], separated by commas. It can have any number of items and they may be of different types.
Examples:
list1 = [10,20,30,40]
list2 = [“Ram”,19,87.81]
Similar to string indices, list indices starts at 0 and lists can be sliced, concatenated and so on..
Here, The task is to combine 2 lists into a dictionary. That means, One list elements will become the keys and another list elements will become the values in the resultant dictionary.
Program:
lists=list()
n=int(input("Enter no.of lists u want to combine"))
for i in range(0,n):
a=input("Enter the value")
lists.append(a)
for b in lists:
print b
dic=dict([(digit,[]) for digit in lists[:]])
print(dic)
Output:
Python Programing Lab (R16) EXERCISE - 5(b)
Python Programing Lab (R16) EXERCISE - 5(b)
Aim:
Write a program to use split and join methods in the string and trace a birthday with a dictionary data structure.
Description:
Compare the entered birthdate with each and every person‟s date of birth in the dictionary and check whether the entered birthdate is present in the dictionary or not. Here, We are using two built-in methods of the string: split() and join().
split():
This method breaks up a string using the specified separator and returns a list of strings. The general form of split() is as follows:
str.split(separator)
join():
This method provides a flexible way to concatenate a string. This method returns a string inwhich the string elements of a sequence have been joined by „sep‟ separator. The general form of join() is as follows:
sep.join(sequence)
Here, sequence is the sequence of elements to be joined.
Program:
pen='+'
pin=['H','E','L','L','O']
print("Joining")
print(pen.join(pin))
c=pen.join(pin)
print("Splitting")
print(c.split('+'))
people={
'Netaji':{
'birthday':'Aug 15'
},
'Manaswi':{
'birthday':'Mar 21'
},
'Chandrika':{
'birthday':'July 7'
}
}
labels={
'birthday':'birth date'
}
name=input("Name:")
request=input('birthday(b)?')
if request=='b':
key='birthday'
if name in people:
print("%s's %s is %s." % (name, labels[key], people[name][key]))
Output:
Python Programing Lab(R16) EXERCISE - 5(a)
Python Programing Lab EXERCISE - 5(a)
Aim:
Write a program to count the numbers of characters in the string and store them in a dictionary data structure.
Description:
Traverse each character in the string and its occurrence is stored in the dictionary. Here, We are using a String and a Dictionary.
String:
A String is a sequence of characters. Strings can be created by enclosing characters inside a single quote or double quotes. Even triple quotes can be used in Python but generally used to represent multiline strings and docstrings.
For reading strings in Python2.7, we are using raw_input(). This function reads a line from input(i.e., the user) and returns a string by stripping a trailing new line.
Dictionary:
The dictionary is Python's built-in mapping type. Dictionaries map keys to values and these <key,value> pairs provides a useful way to store data in python. The only way to access the value part of the dictionary is by using the key.
We can specify the dictionary <key,value> pairs between '{' and '}'. <key,value> pairs arespecified as a list(separated by commas).
Program:
s=input("Enter ur name: ")
#print(len(s)) as length index starts with 1
p=len(s)
count=0
for i in range(0,p):
count=count+1
print(count)
dic=dict([(letter,[]) for letter in s[:]])
print(dic)
Output:
Python Programing Lab EXERCISE - 4(b)
Python Programing Lab EXERCISE - 4(b)

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even- valued terms.
Description:
The Fibonacci sequence is a series of numbers where a number is found by adding up the two numbers before it. Starting with 0 and 1, the series will be 0,1,1,2,3,5,8,13 and so forth.
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the Recurrence relation:
Fn = Fn-1 + Fn-2
With initial values F0 = 0 and F1 = 1
Program:
a=1
b=2
c=3
i=0
print(" The fibonacci series are :")
print(a,b)
while i <= 10:
c=a+b
print(c)
a=b
b=c
i=i+1
print("The sum of even valued term is :")
sum=0
i=0
while i <= 10:
if i%2 == 0:
print(i)
sum=sum+i
i=i+1
print("sum =",sum)
Output:
Python Programing Lab EXERCISE - 4(a)
Aim:
Write a program to find the sum of all primes below two million.
Description:
A Prime number is a natural number greater than 1 that has no positive divisors other than 1
and itself. A natural number greater than 1 and that is not a prime number is called a composite
number.
Here, We are using a for loop and a break statement.
break:
break statement terminates the loop and resumes execution at the next statement, just like
the traditional break statement in C. The break statement can be used in both while and for loops.
If we are using break statement inside a nested loop, it stops the execution of the innermost
loop and start executing the next line of code after the block.
Algorithm:
Step1: Start
Step2: Initialize sum = 0 and i = 2
Step3: Repeat Steps 4 to 13 while i < 2000000
Step4: Initialize c = 0
Step5: Check whether i is greater than 2 and i is divisible by 2 or not. If yes, goto Step6 else, goto Step7
Step6: Set c = 1 and goto Step12
Step7: Initialize j = 3
Step8: Repeat Steps 9 to 11 while j <= int(i**0.5)
Step9: Check whether i is divisible by j or not. If yes, goto Step10. Otherwise, goto Step11
Step10: Set c = 1 and goto Step12
Step11: Increment j by 2
Step12: Check whether c is 0 or not. If yes, goto Step13
Step13: Add i to the sum and store the result in sum
Step14: Display sum
Step15: Stop
Program:
print("To find sum of prime no's")
sum=0
for i in range(2,2000000):
flag=0
for j in range(2,i):
if i%j==0:
flag=1
if flag==0:
print(i)
sum=sum+i
print sum