Algorithmic Problem Solving 1
Algorithmic Problem Solving 1
1
2.2 Problem Solving and Python Programming
UNIT -2
DATA, EXPRESSIONS,
STATEMENTS
Interpreter
Python is an interpreted language because they are executed by an interpreter. Interpreter
take high level program as input and executes what the program says. It processes the program a
minimum at a time. It read lines and performs computations alternatively. The figure 2.1 explains
the structure of an interpreter.
Compiler
A compiler reads the program and translates it completely to machine readable form called
object code or executable code before the program starts running. Once a program is compiled, the
programcanbeexecutedrepeatedlywithoutfurthertranslations.Thefigure2.2showsthestructure of a
compiler.
Interactive mode:
It is command line shell which gives immediate feedback for each statement, while running
previously fed statements in active memory.
In interactive mode, the program statements can be typed in prompt, so the interpreter
displays the result.
>>>1+1
2
Theprompt>>>(chevron)indicatesthattheinterpreterisready.Interactivemodeexecution is
convenient for smaller programs.
Script mode:
The programcanbestoredinafileandi t u s e s theinterpretertoexecute the file. The python
scripts filename ends with .pyextension.
Example:
# first simple program
It prints Hello, World. In python printing statement uses the keyword print as in the above
mentioned format.
In Python 3, the syntax for printing is slightly different like this, print
(‘Hello, World!’)
The parenthesis indicates that the print is a function. The single quotation represents the
beginning and end of the text to be displayed.
About Python:
Python was developed buy Guido van Rossum in 1991, a computer programmer at
CWI(Centrum Wiskunde and Informatica))
It is an object oriented interpreted and high level scripting language.
It has been used by the companies in real revenue generating products such as Googlesearch
engine, you tube, Bit torrent, for developing commercial robot.
It is open source and supports cross platform development.
Features of Python:
Python keywords:
Keywords are reserved words that cannot be used as identifiers. We cannot use a
keyword as variable name, function name or any other identifier. Keywords are case
sensitive. All the keywords except True, False and None are in lowercase. There are 33
and del from not while
As elif global or with
assert else if pass yield
break except import print True
class exec in raise False
continue finally is return None
def for lambda try
keywords.
Python Identifier:
Identifier are names for entities in program such as class, variable and function etc.
Valid identifier:
_sum,test12
Invalid identifier :
$include,if,10python
The values belong to different data types. In Python, the standard data types available are:
Data, Expressions, Statements 2.5
(1) Numbers : Integer, Boolean, Floating point, complex
(2) Sequences: String, List, Tuple
(3) Sets
(4) Mappings: Dictionary
(5) None
Example:
list1=[‘abcd’, 345, 3.2,’python’, 3.14]
list2=[234, ‘xyz’]
Example:
tuple1= (‘abcd’, 345 , 3.2,’python’, 3.14)
print tuple1[2:] #prints tuple1 starting at index 2 till the (3.2, ‘python’, 3.14)
end
print tuple 2 * 2 # asterisk (*) -is the repetition operator. (234, 'xyz', 234, 'xyz')
Prints the tuple2 two times.
print tuple1 + # prints concatenated tuples (‘abcd’, 345, 3.2,’python’,
tuple2 3.14, 234, ‘xyz’)
2.1.1.6 None
2.1.1.7 Sets
A set is an ordered collection of items. Every element is unique and cannot be changed.
A set is created by placing all the items inside curly braces{}, separated by comma. Add() and
update() are used to add new entries or updating existing elements.
Example :
Myset ={2,5}
print(myset)
myset.add(6)
print(myset)
output:
2.8 Problem Solving and Python Programming
{2,5}
{2,5,6}
2.2 Variable
Variable is an identifier that refers to a value. Values mays be numbers and text.No
Declaration is necessary. Declaration happened automatically when the value is assigned.
While creating a variable, memory space is reserved in memory. Based on the data type of
a variable, the interpreter allocates memory. The assignment statements are used to create new
variables and assign values to them.
>>>msg= ‘ Hello, World!’ #string assignemnet
>>> n=12 # integer assignment
>>> pi=3.14
The first statement creates a variable, msg and assigns ‘Hello, World!’ to it. The second
statement creates the variable, n assigns 12 to it. The third statement creates the variable, pi and
assigns the value 3.14.
Variable names can contain both letters and numbers. But do not start with a number. The
underscore character (_ ) can be used in variable names . In addition to variables, python has 31
keywords.
Multiple objects can be assigned to multiple variables as
a,b,c=1,2,3
Input comes from keyboard. Python has two key functions to deal with end user input. They are
1.input()
2.raw_input()
Example:
17 #expression
X #expression
X+17 #expression
Example:
Total= mark1+ \
mark2+ \
mark3
Butthestatementscontainedwithin[],{}or()bracketsdonotneedtouselinecontinuation characters.
Forexample,
2.4 COMMENTS
Comments are the non-executable statements explain what the program does. For large
programs it often difficult to understand what is does. The comment can be added in the program
code with the symbol #.
Single line comment - #
Multiline comment – ‘’’ ( triple single quotes at the start and end )
Example:
print ‘Hello, World!’ # print the message Hello, World!; comment
v=5 # creates the variable v and assign the value 5; comment
Date : 4.5.2020’’’
2.10 Problem Solving and Python Programming
2.5 OPERATORS
An operator is a special symbol that asks the compiler to perform particular mathematical
orlogicalcomputationslikeaddition,multiplication,comparisonandsoon.Thevaluestheoperator is
applied to are called operands.
If operators take one operand are called unary operators. Operators that takes two operand
are called binary operator.
For eg, in the expression 4 + 5, 4 and 5 are operands and + is an operator.
SampleCode:
a = 21
b = 10
c=0
Data, Expressions, Statements 2.1
c=a+b
print “Result of addition “, c
c=a-b
print “Result of subtraction “, c
c=a*b
print “Result of multiplication “, c
c=a/b
print “Result of division “, c
c=a%b
print “Result of modulus “, c
a=2
b=3
c = a**b
print “Result of exponentiation “, c
a = 10
b=5
c = a//b
print “Result of floor division “, c
Sample Output:
Result of addition 31
Result of subtraction 11
Result of multiplication 210
Result of division 2
Result of modulus 1
Result of exponentiation 8
Result of floor division 2
2.5.1.2 Comparison (Relational) Operators
These operators compare the values of their two operands and determine the relationship
among them.
Operator Description
== If the values of two operands are equal, then this operator returns true.
!= If values of two operands are not equal, then this operator returns true.
2.12 Problem Solving and Python Programming
Operator Description
> If the value of first operand is strictly greater than the value of second operand, then
this operator returns true.
< If the value of first operand is strictly smaller than the value of second operand, then
this operator returns true.
>= If the value of first operand is greater than or equal to the value of second operand,
then this operator returns true.
<= If the value of first operand is smaller than or equal to the value of second operand,
then this operator returns true.
SampleCode:
a = 10
b=5
c=a
print “c is “,c
c = a + b
print “c is “, c
c += a #c=c+a
print “c is “, c
c -=a #c=c-a
print “c is “, c
c *= a #c=c*a
print “c is “, c
c /= a #c=c/a
print “c is “, c
c=2
c %= a #c=c%a
print “c is “, c
c **= a # c = c ** a
print “c is “, c
c //= a # c = c // a
print “c is “, c
Sample Output:
c is 10
c is 15
c is 25
c is 15
c is 150
c is 15
c is 2
c is 1024
c is 102
Data, Expressions, Statements 2.11
The behaviour of each logical operator is specified in a truth table for that operator.
Sample Code:
a=True
b=False
print a and b
print a or b
print not a
2.12 Problem Solving and Python Programming
Sample Output:
False
True
False
Sample Code:
a = 60 # 60 = 00111100
b = 26 # 13 = 0001 1010
c = a & b; # 24 = 00011000
print “Result of Bitwise AND is “,
c c = a |b; # 62 = 00111110
print “Result of Bitwise OR is “, c
c = a ^b; # 38 = 00100110
print “Result of Bitwise XOR is “, c
c = ~a; # -61 = 11000011
print “Result of Bitwise Ones Complement is “, c
Data, Expressions, Statements 2.13
Sample Output:
Result of Bitwise AND is 24
Result of Bitwise OR is 62
Result of Bitwise XOR is38
Result of Bitwise Ones Complement is -61
Result of Bitwise Left Shift is240
Result of Bitwise Right Shift is15
2.5.1.6 Membership Operators
Membership operators test whether a value or variable is found in a sequence, such as
strings, lists, or tuples and explained below:
Operator Description
in Evaluatestotrueifitfindsavariableinthespecifiedsequenceandfalseotherwise.
not in Evaluatestotrueifitdoesnotfindsavariableinthespecifiedsequenceandfalse
otherwise.
SampleCode:
a=6
b=2
list = [1, 2, 3, 4, 5 ];
print a in list
print a not in list
print b in list
print b not in list
Sample Output:
False
True
True
False
2.14 Problem Solving and Python Programming
SampleCode:
a = 20
b = 20
print a is b
print id(a) == id(b)
print a is not b
b=30
print a is b
print a is not b
print id(a) == id(b)
Sample Output:
True
True
False
False
True
False
2.5.1.8 Unary arithmetic operators
Operator Description
+ Returns its numeric argument without any change.
- Returns its numeric argument with its sign changed.
SampleCode:
a = 10
b = +a
print b
c = -a
print c
Data, Expressions, Statements 2.15
Sample Output:
10
–10
The following table summarizes the operator precedence in Python, from the highest
precedence to the lowest precedence. Operators in the same box have the same precedence and
groupfromlefttoright(exceptforcomparisons,includingtests,whichallhavethesameprecedence and
chain from left to right and exponentiation, which groups from right toleft).
Examples:
4 * (6-3) is 12, and (1+2)**(6-3) is 27.
3**1+1 is 4, not 9.
2*1**4 is 2, not 16.
4*6-2 is 22, not 16.
4+2/2 is 5, not 3.
4/2*2 is 4, not 1.
2.6 FUNCTIONS
A function is a group of statements that perform a specific task. If a program is large, it
is difficult to understand the steps involved in it. Hence, it is subdivided into a number of smaller
programs called subprograms or modules. Each subprogram specifies one or more actions to be
performedforthelargerprogram.Suchsubprogramsarecalledasfunctions.Functionsmayormay not
take arguments and may or may not produceresults.
Advantages of Functions
• Decomposinglargerprogramsintosmallerfunctionsmakesprogrameasytounderstand,
maintain and debug.
• Functionsdevelopedforoneprogramcanbereusedwithorwithoutmodificationwhen
needed.
• Reduces program development time and cost.
• It is easy to locate and isolate faulty function.
Example:
print() Print objects to the stream.
Reads a line from input, converts it to a string (stripping a trailing newline), and
input()
returns that.
Data, Expressions, Statements 2.17
Sample Input/Output:
p
ord() function convert a character to an integer (ASCII value). It returns the Unicode
code point of that character.
ManyPythonfunctionsaresensitivetothetypeofdata.Forexample,youcannotconcatenate a
string with an integer. If you try, it will result in following error.
For the example above, use the str() conversion function to convert integer to string data
type.
>>> age = 21
>>> sign = “You must be “ + str(age) + “Years old”
>>>sign
Sample Output:
You must be 21 Years old
>>>import math
It will create a module object named math which contains functions and variables defined
in the module. Some of the familiar math functions are listed in Table.
1.0
factorial(n) Return n factorial math.factorial(5) 120
gcd(n,m) Return greatest math.gcd(10,125) 5
common divisior of
(n,m)
trunc(x) Return the real math.trunc(1.999) 1
value x truncated to
an integral
sin(x), cos(x), Return the arc sine, math.sin(math.pi/4) 0.7071067811865476
tan(x) cosine, tangent of x, math.cos(math.pi) –1.0
in radians.
math.tan(math.pi/6) 0.5773502691896257
Mathematical Constants
• math.pi
The mathematical constant π = 3.141592..., to available precision.
• math.e
The mathematical constant e = 2.718281..., to available precision.
Example:
import random
print random.randint(1,5)
print random.random()
data=(“cse”,”eee”,”ece”,”civil’,”mech”)
print random.choice(data)
Example
4
20.9
cse
Another program
import file
file.sum(10,20)
output:
30
Syntax:
def function_name( parameters ):
“function_docstring”
function_suite
return [expression]
The code block within every function starts with a colon (:) and is indented. The first
statement of a function can be an optional statement - the documentation string of the function or
docstring. The statement return [expression] exits a function, and optionally it returns the result of
the function. The rules for function names are the same as for variable names: letters, numbers and
somepunctuationmarksarelegal,butthefirstcharactercan’tbeanumber.Keywordsshouldnotbe used as
function name. To avoid confusion, use different names for functions andvariables.
Calling a Function
A function can be executed by calling it from another function or directly from the Python
prompt by its name.
Syntax:
function_name(parameters)
Function to display Welcome message.
def display():
print “Welcome!!!”
>>>display()
Sample output:
Welcome!!!
The first line of the function definition is called the header; the rest is called the body. The
header has to end with a colon and the body has to be indented. By convention, the indentation is
alwaysfourspaces.Inthisexample,thefunctionnameisdisplay().Theemptyparenthesesafterthe name
indicate that this function doesn’t take anyarguments.
Sample Input/Output:
Enter first number 10
Enter second number 5
Enter third number 25
25 is bigger
Inthisexample,thefunctionnameisgreat().Ittakesthreeparametersandreturnthegreatest
ofthree.input()readsinputvaluefromtheuser.Thefunctionisinvokedbycallinggreat(n1,n2,n3). print()
displays the output. The strings in the print statements are enclosed in doublequotes.
Flow of execution
Flow of execution specifies the order in which statements are executed. Program
execution starts from first statement of the program. One statement is executed at a time from top
to bottom.
Functiondefinitionsdonotaltertheflowofexecutionoftheprogram,andthestatementsinsidethe function
are not executed until the function is called. When a function is called, the control flow
jumpstothebodyofthefunction,executesthefunction,andreturnbacktotheplaceintheprogram where
the function call was made. Python is good at keeping track of where it is, so each time a
functioncompletes,theprogrampicksupwhereitleftoffinthefunctionthatcalledit.Whenitgets to the
end of the program, it terminates.
In this example, the arguments used in function call raise() are a, b and their values are
assigned to parameters no,power.
Sample output:
3.141592653589793
Functions witharguments
Functions may also receive arguments (variables passed from the caller to the function).
Arguments in function call are assigned to function parameters.
Sample output:
Enter Radius:6
Area of Circle:113.04
Sample input/output:
Enter a number:5
120
Output
good morning
welcome
Keyword arguments:
The function caller identifies the arguments by the parameter name.
These values get a assigned to the arguments according to their position.
The order of the arguments can be changed.
Mix positioned arguments with key word arguments during function call.
Keyword arguments must follow positional arguments but reverse not
possible.
Example :
def display (rollno,name=”surya”,sch=”GHSS”,groups=”cs”):
print rollno
print name
print sch
print group
display(cs20)
display(rollno=cs21,name=”sachin”)
output:
cs20e
surya
GHSS
cs
cs21
sachin
GHSS
cs
Default arguments:
It can provide default value to an argument by using theassignment operator.
Arguments assume default value if a value is not provided in the function call.
Example:
def display(*names):
print names
display(“sachin”,”dravid”,”kapil”)
output:
sachin
dravid
kapil
output:
15
7
2.8 ILLUSTRATIVEPROGRAMS
2.8.1 Function to exchange the values of twovariables
defswap(a,b): # function definition forswapping
tmp=a
a=b
b=tmp
print ‘After Swap: n1=”,a, “n2=”,b
return
Sample input/output:
Enter first number1
Enter second number11
Before Swap: n1= 1 n2= 11
After Swap: n1= 11 n2= 1
2.8.2 Python program to test for leapyear
Note: A leap year is divisible by four, but not by one hundred, unless it is divisible by four
hundred.
def leapyr(yr): # functiondefinition
if yr%4==0 and yr%100!=0 or yr%400==0: # condition check for leap year
print ‘LeapYear’
else:
print ‘Not a Leap Year’
return
year=input(“Enter a year”)
leapyr(year) # function call
Sample input/output:
Enter a year1900
Not a Leap Year
Sampleoutput:
15
2.8.5 Python program to reverse astring
def string_reverse(str1):
rstr1= “”
index=len(str1)
while index>0:
rstr1+=str1[index-1]
index=index-1
return rstr1
print “Reverse String:”, string_reverse(“Python”)
Sample output:
Reverse String:nohtyP
Sample output:
2
4
6
8
2.8.8 Functionthatcirculates/rotatesthelistvaluesforgivennumberoftimes(order)
def rotate(l,order):
for i in range(0,order):
j=len(l)-1
while j>0:
tmp=l[j]
l[j]=l[j-1]
l[j-1]=tmp
j=j-1
print i, ‘rotation ’,l
return
l=[1,2,3,4,5]
rotate(l,3)
Sample output:
0 rotation: [5, 1, 2, 3, 4]
1 rotation: [4, 5, 1, 2, 3]
2 rotation: [3, 4, 5, 1, 2]
Sample input/output:
Enter a number5
Not a Perfect number
Enter a number6
Perfect number
Sample input/output:
Enter a string:madam
madam is a Palindrome
2.8.12 Function that checks whether a number is palindrome ornot
def Palindrome_Number():
no = input(“Enter a Number:”)
q=no
rev = 0
while(q!=0): # loop for reverse
rev = q % 10 + rev * 10
q = q / 10
if( rev == no):
print(‘%d is a palindrome number’ %no)
else:
print(‘%d is not a palindrome number’ %no)
Sample input/output:
Enter a Number121
121 is a palindrome number
2.8.13 Find the distance between two points (xc,yc) and(xp,yp).
import math
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
dsquared = dx**2 + dy**2
result = math.sqrt(dsquared)
return result
xc=int(input("Enter xc"))
yc=int(input("Enter yc"))
xp=int(input("Enter xp"))
yp=int(input("Enter yp"))
print (distance(xc,yc,xp,yp))
Sample input/output:
Enter xc 2
Enter yc 2
Enter xp 4
Enter yp 4
2.82
Data, Expressions, Statements 2.31
Disadvantages:
• Python isslow.
• Has limitations with databaseaccess.
• Python is not good for multi-processor/multi-corework.
5. Defineoperator.
An operator is a special symbol that asks the compiler to perform particular mathematical
or logical computations like addition, multiplication, comparison and so on. The values the
operator is applied to are called operands.
20. Definefunction.
A function is a self-contained program, or a sub-program of one or more statements which is
used to do some particular task.
Types of functions: i)User defined, ii)pre-defined
PYTHONDOWNLOAD
AND INSTALLATIONINSTRUCTIONS
Visit python.org/download/ and download the appropriate Python 3 Windows installer for
your architecture (32-bit and 64-bit). The following are the steps involved in downloading and
installing Python 3.4.3 version on Windows 7. The current version available is Python 3.6.2. The
Pythondownload requires about24Mbofdiskspace;keepitonyourmachine,incaseyouneedto re-
install Python. When installed, Python requires about an additional 50 Mb of diskspace.
DOWNLOADING
(1) Visit https://www.python.org/downloads/. The following page will appear in your
browser.
Ensure that the Install for all users radio button is pressed.
(3) Click Next >button.
A new Python 3.4.3 Setup pop-up window will appear (Select Destination Directory).
Note that if you have installed an earlier version of Python 3.4, the following pop-up
window will appear.
Python Download And Installation Instructions 3
Click the Yes button to use the newest installation. The default directory will appear in
thebottomasC:\Python34\andunlessyouhaveagoodreasontouseanotherdirectory, use
this one.
Use the default customization, which selects the Python Interpreter and all its libraries
(about 42 Mb).
During installation, it will show the various operations it is performing and a progress
bar for each one. It might temporarily pop-up a small window in which to execute
commands.
Eventually a new Python 3.4.3 Setup pop-up window will appear (Complete the
Python 3.4.3 Installer).
C:\Python34(ortowhateverdirectoryonwhichyouinstalledPython)double-clickthe
icon/file python.exe. The following pop-up window willappear.
A pop-up window with the title C:\Python34\python.exe appears, and inside the
window on the first line is the text Python 3.4.3 ... (notice that it should say 32 bit).
Inside the window, at the bottom left, is the prompt >>>: type exit() to this prompt and
pressentertoterminatePython.Youshouldkeepthefilepython-3.4.3.msisomewhere on
your computer in case you need to reinstall Python (not likely necessary).
WhenyoufirstlaunchtheAdd/Removeapplication,itwillshowyoualistofpreselected
applications in different categories. Some are already installed; most are not. Because
the repository contains over 10,000 applications, there are different filters you can
apply to see small parts of the repository. The default filter is “Canonical-maintained
applications,”whichisasmallsubsetofthetotalnumberofapplicationsthatareofficially
supported by Canonical, the company that creates and maintains Ubuntu Linux.
Python3isnotmaintainedbyCanonical,sothefirststepistodropdownthisfiltermenu and
select “All Open Source applications.”
6 Problem Solving and Python Programming
Once you’ve widened the filter to include all open source applications, use the Search
box immediately after the filter menu to search for Python 3.
Now the list of applications narrows to just those matching Python 3. You’re going to
check two packages. The first is Python (v3.0). This contains the Python interpreter
itself.
The second package you want is immediately above: IDLE (using Python-3.0).
Afteryou’vecheckedthosetwopackages,clicktheApplyChangesbuttontocontinue.
Python Download And Installation Instructions 7
The package manager will ask you to confirm that you want to add both IDLE (using
Python-3.0)and Python (v3.0). Click the Applybutton to continue.
Thepackagemanagerwillshowyouaprogressmeterwhileitdownloadsthenecessary
packages from Canonical’s Internetrepository.
Once the packages are downloaded, the package manager will automatically begin
installing them.
Ifallwentwell,thepackagemanagerwillconfirmthatbothpackagesweresuccessfully
installed.Fromhere,youcandouble-clickIDLEtolaunchthePythonShell,orclickthe Close
button to exit the package manager. You can always relaunch the Python Shell
bygoingtoyourApplicationsmenu,thentheProgrammingsubmenu,andselecting
IDLE.
GE8161 PROBLEM SOLVING AND PYTHON L T PC
PROGRAMMING LABORATORY 0042
OBJECTIVES
• To write, test, and debug simple Pythonprograms.
• To implement Python programs with conditionals andloops.
• Use functions for structuring Pythonprograms.
• Represent compound data using Python lists, tuples,dictionaries.
• Read and write data from/to files inPython.
LIST OF PROGRAMS
(1) Compute the GCD of twonumbers.
(2) Find the square root of a number (Newton’smethod)
(3) Exponentiation (power of a number)
(4) Find the maximum of a list ofnumbers
(5) Linear search and Binarysearch
(6) Selection sort, Insertionsort
(7) Mergesort
(8) First n primenumbers
(9) Multiplymatrices
(10) Programs that take command line arguments (wordcount)
(11) Find the most frequent words in a text read from afile
(12) Simulate elliptical orbits inPygame
(13) Simulate bouncing ball usingPygame
PLATFORM NEEDED
Python 3 interpreter for Windows/Linux
OUTCOMES
Upon completion of the course, students will be able to:
• Write, test, and debug simple Pythonprograms.
• Implement Python programs with conditionals andloops.
• Develop Python programs step-wise by defining functions and callingthem.
• Use Python lists, tuples, dictionaries for representing compounddata.
• Read and write data from/to files inPython.
TOTAL: 60 PERIODS
APPENDIX -A
LABPROGRAMS
Using Recursion.
def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
print (gcd(8,12))
Sample Output:
4
Using built-in functions.
from fractions import gcd
print (gcd(20,8))
Sample Output:
4
Using Non-recursion.
def gcd(x,y):
while y!=0:
(x,y)=(y,x%y)
return x
n1=int(input(‘Enter first number:’))
n2=int(input(‘Enter second number:’))
App-A.2 Problem Solving and Python Programming
print gcd(n1,n2)
Sample Output:
Enter first number:15
Enter second number:11
1
For example, if one wishes to find the square root of 612, this is equivalent to finding the
solution to
x2=612
The function to use in Newton’s method is then f(x) = x 2-612 with derivate f’(x)=2x.
import math
n=int(input(“Enter n”))
m=int(input(“Enter m”))
i=1
res=1
whilei<=m:
res*=n
i+=1
print (str(n)+ ‘^’+str(m)+ ‘=’+str(res))
print (str(math.pow(n,m))) #using built-in function
Sample Output:
Enter n 3
Enter m 4
3 ^ 4 =81
81.0
4. Find the maximum of a list ofnumbers
def myMax(L): # function with list as arguments
answer =None
for i in L:
if i > answer:
answer = i
return answer
l=input(‘Enter list of numbers’) # reads list as input
print ‘Maximum is’,myMax(l)
Sample input/output:
Enter list of numbers[1,12,34,11,56]
Maximum is 56
Python 3 code:
score = list(map(int, input(“Enter list of numbers”).split()))
print (“Maximum is”+ str(max(score)))
Sampleinput/output:
Enter list of numbers 1 2 4 5 3
Maximumis5
Sample input/output:
Enter no. of elements in the list 3
Enter no. 1
Enter no. 2
Enter no. 3
[‘1’, ‘2’, ‘3’]
Enter key to be searched 2
(True, 2)
Sample input/output:
Enter no5
enter no.12
enter no. 2
enter no.23
enter no. 4
enter no.5
Sorted List:
[2, 4, 5, 12, 23]
Sample input/output:
Enter number of elements5
Enter number12
Enter number23
Enter number4
Enter number16
Enter number34
[4, 12, 16, 23, 34]
Sample output:
Splitting [54, 26, 93, 17, 77, 31, 44, 55, 20]
Splitting [54, 26, 93, 17]
Splitting [54, 26]
Splitting [54]
Merging [54]
Splitting [26]
Merging [26]
Merging [26, 54]
Splitting [93, 17]
Splitting [93]
Merging [93]
Splitting [17]
Merging [17]
Merging [17, 93]
Merging [17, 26, 54, 93]
Splitting [77, 31, 44, 55, 20]
Splitting [77, 31]
Splitting [77]
Merging [77]
Splitting [31]
Merging [31]
Merging [31, 77]
Splitting [44, 55, 20]
Splitting [44]
Merging [44]
Splitting [55, 20]
Splitting [55]
Merging [55]
Splitting [20]
Merging [20]
Merging [20, 55]
Merging [20, 44, 55]
Merging [20, 31, 44, 55, 77]
Merging [17, 20, 26, 31, 44, 54, 55, 77, 93]
[17, 20, 26, 31, 44, 54, 55, 77, 93]
Sample Output:
[17, 20, 26, 31, 44, 54, 55, 77, 93]
Appendix -A Lab Programs App-A.11
8. First n primenumbers
def primes(n): # functiondefinition
out = list() # declare a list for prime number
for num in range(1, n+1): # loop iterates from 1 upto n+1
prime = True
for i in range(2, num):
if (num % i == 0):
prime = False
if prime:
out.append(num) # if number is prime, add it to list
return out
n=int(input(“Enter a number”)) # read a number
print primes(n) # functioncall
Sample input/output:
Enter a number20
[1, 2, 3, 5, 7, 11, 13, 17, 19]
9. Multiply matrices #
3x3 matrix a
= [[2,3,5],
[13,7,9],
[5,9,4]]
# 3x4 matrix
b =[[4,7,1,8],
[6,2,7,9],
[8,3,2,6]]
# result is 3x4
c = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
# iterate through rows of a
for i in range(len(a)):
# iterate through columns of b
App-A.12 Problem Solving and Python Programming
for j in range(len(b[0])):
# iterate through rows of c
for k in range(len(b)):
c[i][j] += a[i][k] * b[k][j]
for r in c:
print(r)
Sample Input/Output:
[66, 35, 33, 73]
[166, 132, 80, 221]
[106, 65, 76, 145]
Sample Input/Output:
This 1
program 2
example 1
Python 2
Appendix -A Lab Programs App-A.13
11. Find the most frequent words in a text read from afile
file=open(“sample.py”,”r+”)
wordcount={}
num_chars=0
for word infile.read().split():
num_chars+=len(word)
if word not in wordcount:
wordcount[word] =1
else:
wordcount[word] += 1
print(‘Number of characters:”+str(num_chars))
for k,v in wordcount.items():
print (str(k)+ ‘-’+ str(v))
file.close()
Sample Output:
Number of characters:109
This-6
is-6
an-6
example-6
Python-2
Testing-1
#mercury
mercuryColor = (222,184,135)
#venus
venusColor = (215, 212, 207)
#earth
earthColor = (165, 190, 231)
#mars
marsColor = (232, 193, 135)
#jupiter
jupiterColor = (180, 164, 156)
#saturn
saturnColor = (193, 184, 83)
#uranus
uranusColor = (166, 193, 213)
#neptune
neptuneColor = (144, 174, 224)
Planet.py
class planet:
name = ''
hasRing =False
color = (255, 255, 255) #default to white
#inital position
x=0
y=0
radius = 200 #radius of orbit
speed = 2 #default rate of change of angle
angle = 0 #initial angle to 0
width = 10 #size of planet in width
definit(self, nameOfPlanet):
self.hasRing = False
self.name = nameOfPlanet
self.width = 10
self.color = (255, 255, 255) #default to white
Appendix -A Lab Programs App-A.15
#inital position
self.x =0
self.y =0
self.radius = 200 #radius of orbit
self.speed = 2 #default rate of change of angle
self.angle = 0 #initial angle to 0
#accessor methods
def getColor(self):
return self.color
def setColor(self,inputColor):
self.color = inputColor
return True
def setX(self,xIn):
self.x = xIn
return True
def setY(self,yIn):
self.y = yIn
return True
defgetX(self):
return self.x
defgetY(self):
return self.y
def setRadius(self,radIn):
self.radius = radIn
return True
def getRadius(self):
return self.radius
def getNextAngle(self):
self.angle = self.angle + self.speed
if self.angle > 360:
self.angle -= 360
angleRad = self.angle * 0.0174532925
return angleRad
App-A.16 Problem Solving and Python Programming
def setSpeed(self,sIn):
self.speed = sIn
return True
def getSpeed(self):
return self.speed
defgetAngle(self):
return self.angle
def setAngle(self,aIn):
self.angle = aIn
return True
def getName(self):
return self.name
def setWidth(self, wIn):
self.width = wIn
return True
defgetWidth(self):
return self.width
defhasRings(self):
return self.hasRing
def toggleRings(self):
self.hasRing = not self.hasRing
Solar.py
import pygame
import math
import solarColorPalette
from planet import planet
pygame.init()
# Set the width and height of the screen [width, height]
screenWidth = 1024
screenHeight = 768
screenWidthHalf = screenWidth // 2
screenHeightHalf = screenHeight // 2
size = (screenWidth, screenHeight)
Appendix -A Lab Programs App-A.17
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Solar System") #set title
#logo = pygame.image.load("solar.gif") #set logo of program
#pygame.display.set_icon(logo)
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
#initialize planets
#mercury
mercury = planet('Mercury')
mercury.setColor(solarColorPalette.mercuryColor)
mercury.setWidth(3)
mercury.setRadius(50)
mercury.setSpeed(4.5)
mercury.setX(50)
mercury.setY(250)
#venus
venus = planet('Venus')
venus.setColor(solarColorPalette.venusColor)
venus.setWidth(7)
venus.setRadius(100)
venus.setSpeed(4)
venus.setX(100)
venus.setY(250)
#earth
earth = planet('Earth')
earth.setColor(solarColorPalette.earthColor)
earth.setWidth(6)
earth.setRadius(150)
earth.setSpeed(3)
earth.setX(150)
earth.setY(250)
App-A.18 Problem Solving and Python Programming
#mars
mars = planet('Mars')
mars.setColor(solarColorPalette.marsColor)
mars.setWidth(5)
mars.setRadius(180)
mars.setSpeed(2.5)
mars.setX(180)
mars.setY(250)
#jupiter
jupiter = planet('Jupiter')
jupiter.setColor(solarColorPalette.jupiterColor)
jupiter.setWidth(15)
jupiter.setRadius(250)
jupiter.setSpeed(2)
jupiter.setX(250)
jupiter.setY(250)
#saturn
saturn = planet('Saturn')
saturn.setColor(solarColorPalette.saturnColor)
saturn.setWidth(10)
saturn.setRadius(280)
saturn.setSpeed(2.3)
saturn.setX(280)
saturn.setY(250)
saturn.toggleRings()
#uranus
uranus = planet('Uranus')
uranus.setColor(solarColorPalette.uranusColor)
uranus.setWidth(9)
uranus.setRadius(320)
uranus.setSpeed(1.8)
uranus.setX(320)
uranus.setY(250)
Appendix -A Lab Programs App-A.19
#neptune
neptune = planet('Neptune')
neptune.setColor(solarColorPalette.neptuneColor)
neptune.setWidth(8)
neptune.setRadius(350)
neptune.setSpeed(1.2)
neptune.setX(350)
neptune.setY(250)
def drawPlanets(planetIn):
pygame.draw.circle(screen, solarColorPalette.white, [screenWidthHalf,screenHeig
htHalf], planetIn.getRadius(), 1)
pygame.draw.circle(screen, planetIn.getColor(), [planetIn.getX(), planetIn.getY()],
planetIn.getWidth(), planetIn.getWidth())
if planetIn.hasRings() == True:
pygame.draw.circle(screen, solarColorPalette.white, [planetIn.getX(),planetIn.
getY()], planetIn.getWidth()+5, 1)
def movePlanets(planetIn):
angl = planetIn.getNextAngle()
planetIn.setX(int(screenWidthHalf + math.sin(angl) * planetIn.getRadius()))
planetIn.setY(int(screenHeightHalf + math.cos(angl) * planetIn.getRadius()))
#venus
drawPlanets(venus)
#earth
drawPlanets(earth)
#mars
drawPlanets(mars)
#jupiter
drawPlanets(jupiter)
#saturn
drawPlanets(saturn)
#uranus
drawPlanets(uranus)
#neptune
drawPlanets(neptune)
#Moving the planets along orbit
#mercury
movePlanets(mercury)
#venus
movePlanets(venus)
#earth
movePlanets(earth)
#mars
movePlanets(mars)
#jupiter
movePlanets(jupiter)
#saturn
movePlanets(saturn)
#uranus
movePlanets(uranus)
#neptune
movePlanets(neptune)
pygame.display.flip()
# --- Limit to 120 frames per second
Appendix -A Lab Programs App-A.21
clock.tick(120)
pygame.quit()
direction = 1
pygame.display.update()
for event in pygame.event.get():
if event.type == QUIT: #window persists until the user close the window
pygame.quit()
sys.exit()
Sample output:
Sample Output:
[1, 2, 3, 4]
Method 2:
mylist=input(“Enter list of values”)
cleanlist=[]
[cleanlist.append(x) for x in mylist if x not in cleanlist]
print (cleanlist)
Sample Input/Output:
Enter list of values 1 1 2 2 3 3 4 5 5
[1, 2, 3, 4, 5]
APPENDIX-B
Sample Input/Output:
Enter temperature in Farenheit 106
Temperature in Celsius is 41.11
Sample Input/Output:
Enter raidus of circle 5
Circumference of circle: 31.428
Area of circle: 78.571
print (“Average:”,avg)
Sample Input/Output:
Enter first number 12
Enter second number 11
Enter third number 14
Average: 12.33
Sample Input/Output:
Enter Principal 1000
Enter rate of interest 7
Enter time period 2
Interest: 140
Amount: 1140
Sample Input/Output:
Enter side 1 of triangle 12
Enter side 1 of triangle 5
Enter side 1 of triangle 14
Area: 29.23
Sample Input/Output:
Enter a number 12
Even
Sample Input/Output:
Enter a number 123
Sum of digits: 6
App-B.4 Problem Solving and Python Programming
Sample Input/Output:
Enter a number 123
Reverse: 321
Sample Input/Output:
Enter a number 123
Not a Palindrome
for i in range(1,no):
if no%i==0:
sum=sum+i
if no==sum:
print(“Perfect number”)
else:
print(“Not a Perfect number”)
Sample Input/Output:
Enter a number 28
Perfect number
no=int(input(‘Enter a number’))
tmp=no
sum=0
while no>0:
rem=no%10
sum=sum+rem*rem*rem
no=no//10
if sum==tmp:
print (“Armstrong Number”)
else:
print(“Not a Armstrong Number”)
Sample Input/Output:
Enter a number 153
Armstrong number
12. Fibonacciseries
no=int(input(‘Enter a number’))
a=0
b=1
App-B.6 Problem Solving and Python Programming
cnt=2
print(a)
print(b)
while cnt<no:
c=a+b
print(c)
a=b
b=c
cnt=cnt+1
Sample Input/Output:
Enter a number 5
0
1
1
2
3
Sample Input/Output:
Enter a number 5
9
i=i+1
print(“Sum:”,sum)
Sample Input/Output:
Enter a number 5
55
Sample Input/Output:
Enter a number 4
*
**
***
****
Sample Input/Output:
Enter a number 4
1
12
123
1234
19. Write a program that prints the integers between 1 and n which are divisible
by 3, but not divisible by4
n=int(input(‘Enter a number’))
i=1
while i<=n:
if (i%3==0 and i%4!=0):
print(i)
i=i+1
Sample Input/Output:
Enter a number 10
3
6
9
ARRAYS
20. Find the maximum and minimum element in a set ofelements
from array import *
myArray = array(‘i’, [10,2,13,44,5])
maxi=myArray[0]
mini=myArray[0]
for i in myArray:
App-B.10 Problem Solving and Python Programming
if(i>maxi):
maxi=i
elif(i<mini):
mini=i
print(“Minimum:”,mini)
print(“Maximum:”,maxi)
Sample Input/Output:
Minimum:2
Maximum:44
-2 45 0 11 -9 -2 0 11 -9 45 -9 -2 0 11 45
-2 0 -9 11 45
-2 0 45 11 -9 -2 0 11 -9 45 -2 -9 0 11 45
-2 0 11 45 -9 -2 0 -9 11 45
-2 0 11 -9 45
def bubblesort( A ):
for i in range( len( A ) ):
for k in range( len( A ) - 1, i, -1 ):
if ( A[k] < A[k - 1]):
swap( A, k, k - 1)
def swap( A, x, y ):
tmp = A[x]
A[x] = A[y]
A[y] = tmp
a=[10,2,13,44,5]
bubblesort(a)
Appendix-B Solved Programs in Python App-B .11
Sample Input/Output:
[12,4,3]
[7,5,8]
24. Write a program that returns the position of the largest element in anarray
from array import *
myArray = array(‘i’, [10,2,13,44,5])
maxi=myArray[0]
pos=0
for i in range(len(myArray)):
if(myArray[i]>maxi):
maxi=myArray[i]
pos=i
print(“Maximum”,maxi,”at position”,pos+1)
Sample Input/Output:
Maximum 44 at position 4
Sample Input/Output:
Number of positive integers: 2
STRINGS
26. Read a string and find the number of vowels present in thestring
s=input(‘Enter a string:’)
cnt = 0
for i in range(len(s)):
if s[i]==’a’ or s[i]==’e’ or s[i]==’i’ or s[i]==’o’ or s[i]==’u’:
cnt=cnt+1
print (“Number of vowels:”,cnt)
Sample Input/Output:
Enter a string: apple
Number of vowels:2
Sample Input/Output:
Enter a string: apple
Enter a character: p
Number of occurrences: 2
App-B.14 Problem Solving and Python Programming
Sample Input/Output:
Enter a string: This is an example
Number of words: 4
Sample Input/Output:
Enter a string: example
Reverse: elpmaxe
30. Define a function that can accept two strings as input and print the string
withmaximumlengthinconsole.Iftwostringshavethesamelength,thenthe
function should print al l strings line byline.
def printValue(s1,s2):
len1 = len(s1)
len2 = len(s2)
if len1>len2:
print s1
elif len2>len1:
print s2
Appendix-B Solved Programs in Python App-B .15
else:
print s1
print s2
s1=raw_input()
s2=raw_input()
printValue(s1,s2)
Sample Input/Output:
Python
Example
Example
FUNCTIONS
31. Write a function to check whether a given number is even orodd
def check(no):
if (no%2)==0:
print (“Even”)
else:
print (“Odd”)
no=int(input(‘Enter a number’))
check(no)
Sample Input/Output:
Enter number: 4
Even
if no==isPerfect(no):
print(“Perfect number”)
else:
print(“Not a Perfect number”)
Sample Input/Output:
Enter a number 28
Perfect number
Sample Input/Output:
Enter a number 123
Reverse: 321
print (“Palindrome”)
else:
print(“Not a Palindrome”)
Sample Input/Output:
Enter a number 121
Palindrome
Sample Input/Output:
Enter a number 153
Armstrong number
36. Writeafunctiontofindthesumofindividualdigitsinagivenpositiveinteger
number
def sumofdigits(no):
sum=0
while no>0:
rem=no%10
sum=sum+rem
no=no//10
App-B.18 Problem Solving and Python Programming
return sum
no=int(input(‘Enter a number’))
print (“Sum of digits:”,sumofdigits(no))
Sample Input/Output:
Enter a number 123
Sum of digits: 6
Sample Input/Output:
Sum: 5
Multiplies: -176
38. Write a program to get the smallest and largest number from alist
def smallest_large_list( list ):
min = list[ 0 ]
max=list[0]
for a in list:
if a <min:
min = a
elif a>max:
max=a
print(“Max:”,max,”Min:”,min)
Appendix-B Solved Programs in Python App-B .19
Sample Input/Output:
Max:2 Min:-8
Sample Input/Output:
{40, 10, 80,50,20,60,30}
40. Writeaprogramtocountnumberofelementsinthelistwithinaspecified
range
def count_range_in_list(li, min, max):
ctr = 0
for x in li:
if min <= x <= max:
ctr += 1
return ctr
list1 = [10,20,30,40,40,40,70,80,99]
print(count_range_in_list(list1, 40, 100))
list2 = [‘a’,’b’,’c’,’d’,’e’,’f’]
print(count_range_in_list(list2, ‘a’, ‘e’))
Sample Input/Output:
6
5
App-B.20 Problem Solving and Python Programming
Sample Input/Output:
[11, 22, 44, 23, 54]
[11, 22, 44, 23, 54]
Sample Input/Output:
(‘e’,’l’,’p’,’m’,’a’,’x’,’e’)
(20, 15, 10, 5)
Sample Input/Output:
4
{1:1, 2:4, 3:9, 4:16}
Appendix-B Solved Programs in Python App-B .21
44. Write a program that accepts sequence of lines as input and capitalize each
character.
lines = []
while True:
s = raw_input()
if s:
lines.append(s.upper())
else:
break;
for sentence in lines:
print sentence
Sample Input/Output:
Example
EXAMPLE
45. Write a program that accepts a sentence and calculate the number of letters
anddigits.
s = raw_input()
d={“digits”:0, “letters”:0}
for c in s:
if c.isdigit():
d[“digits”]+=1
elif c.isalpha():
d[“letters”]+=1
else:
pass
print “LETTERS”, d[“letters”]
print “DIGITS”, d[“digits”]
Sample Input/Output:
Hello world 123
LETTERS 10
DIGITS 3
App-B.22 Problem Solving and Python Programming
46. Write a program that accepts a sentence and calculate the number of upper
case letters and lower caseletters.
s = raw_input()
d={“upper case”:0, “lower case”:0}
for c in s:
if c.isupper():
d[“upper case”]+=1
elif c.islower():
d[“lower case”]+=1
else:
pass
print “upper case”, d[“upper case”]
print “lower case”, d[“lower case”]
Sample Input/Output:
Hello
upper case 1
lower case 4
47. Defineafunctionwhichcanprintadictionarywherethekeysarenumbers
between 1 and 3 (both included) and the values are square of keys
def printDict():
d=dict()
d[1]=1
d[2]=2**2
d[3]=3**2
print d
printDict()
Sample Input/Output:
{1:1, 2:4, 3:9}
48. Withagiventuple(1,2,3,4,5,6,7,8,9,10),writeaprogramtoprintthefirsthalf
values in one line and the last half values in other line
tp=(1,2,3,4,5,6,7,8,9,10)
tp1=tp[:5]
tp2=tp[5:]
Appendix-B Solved Programs in Python App-B .23
print tp1
print tp2
File, Errors
Sample Input/Output:
{1,2,3,4,5}
{6,7,8,9,10}
49. Write a function to compute 5/0 and use try/except to catch theexceptions.
def throws():
return 5/0
try:
throws()
except ZeroDivisionError:
print “Divide by zero!”
except Exception, err:
print ‘Caught an exception’
finally:
print ‘In finally block for cleanup’
Sample Input/Output:
Divide by zero !
In finally block for cleanup
Sample Input/Output:
The list has no element at index 4.
App-B.24 Problem Solving and Python Programming
Sample Input/Output:
File random access
52. Rewrite the previous program so that the exception which is caught in the
except clause is re-raised after the error message isprinted.
def print_list_element(thelist, index):
try:
print(thelist[index])
except IndexError as ie:
print(“The list has no element at index %d.” % index)
raise ie
l=[1,2,3,4]
print_list_element(l,4)
Sample Input/Output:
The list has no element at index 4
Traceback (most recent call last):
File “main.py”, line 8, in <module>
print_list_element(l,4)
File “main.py”, line 6, in print_list_element
raise ie
IndexError: list index out of range
UNVERSITY QUESTION PAPERS
1. What is analgorithm?
2. Write an algorithm to accept two numbers, compute the sum and print theresult.
3. Name the four types of scalar objects Pythonhas.
4. What is a tuple? How literals of types tuples are written? Givenexamples?
5. Write a Python program to accept two numbers, multiply them and print theresult.
6. Write a Python program to accept two numbers, find the greatest and print theresult.
7. What is a list? How lists differ fromtuples?
8. How to slice a list inPython?
9. Write a Python script to display the current date andtime?
10. Write a note on modulardesign.