GE3151 Problem Solving and Python Programming - 01 - by LearnEngineering - In-1
GE3151 Problem Solving and Python Programming - 01 - by LearnEngineering - In-1
Algorithm
Definition: An algorithm is procedure consisting of a finite set of unambiguous rules (instructions) which
specify a finite sequence of operations that provides the solution to a problem. In other word, an algorithm is a
step-by-step procedure to solve a given problem
Definition: An algorithm is a finite number of clearly described, unambiguous “double” steps that can be
n
systematically followed to produce a desired result for given input in a finite amount of time.
g.i
Building blocks of algorithm
It has been proven that any algorithm can be constructed from just three basic building blocks. These three
rin
building blocks are Sequence, Selection, and Iteration.
Building Block Common name
ee
Sequence Action
Selection Decision
gin
Iteration Repetition or Loop
A sequence is one of the basic logic structures in computer programming. In a sequence structure, an
En
action, or event, leads to the next ordered action in a predetermined order. The sequence can contain any
number of actions, but no actions can be skipped in the sequence. Once running, the program must perform
each action in order without skipping any.
arn
A selection (also called a decision) is also one of the basic logic structures in computer programming. In
a selection structure, a question is asked, and depending on the answer, the program takes one of two courses of
action, after which the program moves on to the next event
Le
An iteration is a single pass through a group/set of instructions. Most programs often contain loops of
instructions that are executed over and over again. The computer repeatedly executes the loop, iterating through
w.
the loop
ww
.in
ng
eri
Write an algorithm to add two numbers entered by user.
Step 1: Start
e
gin
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
En
Write an algorithm to find the largest among three different numbers entered by user.
Step 1: Start
Le
If a>c
Display a is the largest number.
Else
ww
Step 1: Start
Step 2: Declare variables a, b, c, D, x1, x2, rp and ip;
Visit For More : www.LearnEngineering.in
Visit For More : www.LearnEngineering.in
.in
Step 5: Stop
ng
Step 1: Start
Step 2: Declare variables n,factorial and i.
eri
Step 3: Initialize variables
factorial←1
i←1
Step 4: Read value of n
e
gin
Step 5: Repeat the steps till i=n
5.1: factorial←factorial*i
5.2: i←i+1
Step 6: Display factorial
En
Step 7: Stop
arn
Step 1: Start
Step 2: Declare variables n,i,flag.
Le
flag←0
Go to step 6
5.2 i←i+1
Step 6: If flag=0
Display n is not prime
else
Display n is prime
Step 7: Stop
Step 1: Start
Visit For More : www.LearnEngineering.in
Visit For More : www.LearnEngineering.in
Pseudo code:
Pseudo code is a detailed yet readable description of what a computer program or algorithm must do, expressed
.in
in a formally-styled natural language rather than in a programming language. Pseudo code is sometimes used as
a detailed step in the process of developing a program
ng
Compute the area of a rectangle:
GET THE length, l, and width, w
eri
COMPUTE area = l*w
DISPLAY area
Compute the perimeter of a rectangle:
e
gin
READ length, l
READ width, w
COMPUTE Perimeter = 2*l + 2*w
DISPLAY Perimeter of a rectangle
En
Iteration:
arn
Iteration is the act of repeating a process, either to generate an unbounded sequence of outcomes, or with the
aim of approaching a desired goal, target or result. Each repetition of the process is also called an "iteration",
and the results of one iteration are used as the starting point for the next iteration.
Le
a = 0
w.
}
print a // the number 6 is printed (0 + 1; 1 + 2; 3 + 3)
Recursion
The process in which a function calls itself directly or indirectly is called recursion and the corresponding
function is called as recursive function. Using recursive algorithm, certain problems can be solved quite easily.
Examples of such problems are Towers of Hanoi (TOH), In order/Preorder/Post order Tree Traversals, DFS of
Graph, etc.
int fact(int n)
{
Visit For More : www.LearnEngineering.in
Visit For More : www.LearnEngineering.in
In the above example, base case for n < = 1 is defined and larger value of number can be solved by converting
to smaller one till base case is reached.
Disadvantages of Recursion over iteration
.in
Note that both recursive and iterative programs have same problem solving powers, i.e., every recursive
ng
program can be written iteratively and vice versa is also true. Recursive program has greater space requirements
than iterative program as all functions will remain in stack until base case is reached. It also has greater time
requirements because of function calls and return overhead.
eri
Advantages of Recursion over iteration
Recursion provides a clean and simple way to write code. Some problems are inherently recursive like tree
e
traversals, Tower of Hanoi, etc. For such problems it is preferred to write recursive code. We can write such
codes also iteratively with the help of stack data structure. For example refer Inorder Tree Traversal without
gin
Recursion, Iterative Tower of Hanoi.
Flow Charts
En
A Flowchart is a diagram that graphically represents the structure of the system, the flow of steps in a
process, algorithm, or the sequence of steps and decisions for execution a process or solution a problem.
arn
Flow charts are easy-to-understand diagrams that show how the steps of a process fit together. American
engineer Frank Gilbert is widely believed to be the first person to document a process flow, having introduced
the concept of a “Process Chart” to the American Society of Mechanical Engineers in 1921.
Le
Flow charts tend to consist of four main symbols, linked with arrows that show the direction of flow:
w.
4. Parallelograms, which show input and output. This can include materials, services or people.
.in
ng
eri
e
gin
En
arn
Le
w.
ww
.in
ng
eri
Flowchart to find the number is odd or Even
e
gin
En
arn
Le
w.
ww
.in
ng
eri
e
gin
Factorial of the given Number
En
arn
Le
w.
ww
.in
ng
eri
e
gin
En
arn
Le
w.
ww
.in
ng
eri
Flow chart for finding Prime number
e
gin
En
arn
Le
w.
ww
.in
ng
eri
e
gin
En
arn
Le
w.
ww
.in
ng
e eri
gin
En
arn
Le
Illustrative problems: find minimum in a list, insert a card in a list of sorted cards, guess an integer number in a
w.
.in
ng
e eri
gin
En
arn
Le
w.
ww
To find the minimum from the list the same flowchart but change the sign
.in
ng
e eri
gin
En
arn
Le
Sorting is ordering a list of objects. We can distinguish two types of sorting. If the number of objects is small
w.
enough to fits into the main memory, sorting is calledinternal sorting. If the number of objects is so large that
some of them reside on external storage during the sort, it is called external sorting. In this chapter we consider
the following internal sorting algorithms
ww
Bucket sort
Bubble sort
Insertion sort
Selection sort
Heapsort
Mergesort
print(x)
if guess == x:
print("Hit!")
.in
else:
ng
print ("Your guess is too high")
OUTPUT
eri
>>> runfile('C:/Users/admin/.anaconda/navigator/gu.py', wdir='C:/Users/admin/.anaconda/navigator')
158
e
gin
Please enter your guess: 200
59
arn
Flow Chart
w.
ww
.in
ng
eri
e
gin
En
arn
Le
w.
ww
range(stop)
stop: Number of integers (whole numbers) to generate, starting from zero. eg. range(3) ==
[0, 1, 2].
.in
step: Difference between each number in the sequence.
Note that:
ng
All parameters must be integers.
eri
All parameters can be positive or negative.
range() (and Python in general) is 0-index based, meaning list indexes start at 0, not 1. eg.
The syntax to access the first element of a list is mylist[0]. Therefore the last integer
generated by range() is up to, but not including, stop. For example range(0, 5) generates
integers from 0 up to, but not including, 5. e
gin
Python's range() Function Examples
... print(i)
...
0
arn
1
2
3
4
Le
...
4
6
ww
8
>>> # Going backwards
>>> for i in range(0, -10, -2):
... print(i)
...
0
-2
-4
-6
-8
Tower of the Hanoi
.in
ng
eri
e
gin
En
arn
Le
w.
ww
.in
ng
eri
e
gin
En
arn
Le
w.
ww
.in
Notice that, as the rules specify, the disks on each peg are stacked so that smaller disks are always on top of the
larger disks. If you have not tried to solve this puzzle before, you should try it now. You do not need fancy
disks and poles–a pile of books or pieces of paper will work.
ng
e eri
gin
En
How do we go about solving this problem recursively? How would you go about solving this problem at all?
What is our base case? Let’s think about this problem from the bottom up. Suppose you have a tower of five
arn
disks, originally on peg one. If you already knew how to move a tower of four disks to peg two, you could then
easily move the bottom disk to peg three, and then move the tower of four from peg two to peg three. But what
if you do not know how to move a tower of height four? Suppose that you knew how to move a tower of height
Le
three to peg three; then it would be easy to move the fourth disk to peg two and move the three from peg three
on top of it. But what if you do not know how to move a tower of three? How about moving a tower of two
disks to peg two and then moving the third disk to peg three, and then moving the tower of height two on top of
w.
it? But what if you still do not know how to do this? Surely you would agree that moving a single disk to peg
three is easy enough, trivial you might even say. This sounds like a base case in the making.
Here is a high-level outline of how to move a tower from the starting pole, to the goal pole, using an
ww
intermediate pole:
As long as we always obey the rule that the larger disks remain on the bottom of the stack, we can use the three
steps above recursively, treating any larger disks as though they were not even there. The only thing missing
from the outline above is the identification of a base case. The simplest Tower of Hanoi problem is a tower of
one disk. In this case, we need move only a single disk to its final destination. A tower of one disk will be our
base case. In addition, the steps outlined above move us toward the base case by reducing the height of the
tower in steps 1 and 3. Listing 1 shows the Python code to solve the Tower of Hanoi puzzle.
moveTower(height-1,fromPole,withPole,toPole)
moveDisk(fromPole,toPole)
moveTower(height-1,withPole,toPole,fromPole)
.in
def moveDisk(fp,tp):
print("moving disk from",fp,"to",tp)
ng
moveTower(3,"A","B","C")
e eri
OUTPUT
gin
runfile('C:/Users/admin/.anaconda/navigator/toh.py',wdir='C:/Users/admin/.anaconda/navigator')
moving disk from A to B
En
Two Marks
n
A value is one of the basic things ina programs like a letter or a number. The values are
g.i
belonging to different types. For example
>>> type(‘Hello’)
rin
<type ‘str’>
>>> type(17) ee
<type ‘float’>
gin
2. Define variables.
A variable is a name that refers to a value. They can contain both letters and numbers but
they do not begin with a letter. The underscore ‘_’ can appear in a name.
En
Example:
arn
>>> n=176
A Boolean expression is an expression that is either true (or) false. The Operator == which
w.
compares two operands and produces True if they are equal otherwise it is false.
>>> 5==5
ww
True
>>> 5==6
False
4. Define String
>>> fruit=’banana’
Output:
5.Define List.
n
A List is a sequence of values. The values are characters in a list they can be of any type. The
g.i
values in a list are called elements.
Examples
rin
[10,20,30,40] number List
>>> n=[17,35]
arn
>>> n[0]=5
7. Define Expression
considered an expression.
8. Define Tuples
ww
A Tuple is a sequence of values. The values can be of any type, They are indexed by integers.
>>> t=(‘a’,’b’,’c’)
>>> t[1:3]
>>(‘a’,’b’)
a=5
b=6
a,b=b,a
print (a,b)
n
11. What are different Membership Operators in python?
g.i
In – Evaluates to true, if it finds a variable in the specified sequence and false otherwise.
Not in- Evaluates to true, if it does not finds a variable in the specified sequence and false
rin
otherwise.
12.Define Functions
ee
A function is a named sequence of statements that performs a computation. A function takes
an argument and returns a result. The result is called the return value.
gin
Example
def print_1():
En
print (“welcome”)
arn
13.Define Module
1.Function arguments
2.keyword arguments
3.Default arguments
1. Define Operators. What are the different types of Operators in python? Explain in
detail.
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.
Types of Operator
n
Arithmetic Operators
Comparison (Relational) Operators
g.i
Assignment Operators
Logical Operators
Bitwise Operators
rin
Membership Operators
Identity Operators
+ Addition a + b = 30
operator.
Subtracts right hand operand from left
- Subtraction a – b = -10
hand operand.
arn
hand operand
Divides left hand operand by right
% Modulus b%a=0
hand operand and returns remainder
w.
These operators compare the values on either sides of them and decide the relation among
them. They are also called Relational operators.
n
If the value of left operand is less than
< the value of right operand, then (a < b) is true.
g.i
condition becomes true.
If the value of left operand is greater
>= than or equal to the value of right (a >= b) is not true.
rin
operand, then condition becomes true.
If the value of left operand is less than
<= or equal to the value of right operand, (a <= b) is true.
ee
then condition becomes true.
gin
Python Assignment Operators
/= Divide c /= a is equivalent to c = c / ac /= a is
operand and assign the result to left
AND equivalent to c = c / a
operand
%=
It takes modulus using two operands
Modulus c %= a is equivalent to c = c % a
and assign the result to left operand
AND
**= Performs exponential (power)
Exponent calculation on operators and assign c **= a is equivalent to c = c ** a
AND value to the left operand
//= Floor It performs floor division on operators
c //= a is equivalent to c = c // a
Division and assign value to the left operand
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b =
13; Now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
n
a&b = 0000 1100
g.i
a|b = 0011 1101
rin
~a = 1100 0011
ee
There are following Bitwise operators supported by Python language
There are following logical operators supported by Python language. Assume variable a holds
10 and variable b holds 20 then
Python’s membership operators test for membership in a sequence, such as strings, lists, or
tuples. There are two membership operators as explained below
n
g.i
Python Identity Operators
rin
Identity operators compare the memory locations of two objects. There are two Identity
operators explained below:
Operator Description
Evaluates to true if the variables
ee on
Example
x is y, here is results in 1 if id(x) equals
is either side of the operator point to the
gin
id(y).
same object and false otherwise.
Evaluates to false if the variables on
x is not y, here is not results in 1 if id(x)
is not either side of the operator point to the
is not equal to id(y).
En
The following table lists all operators from highest precedence to lowest.
Operator Description
Le
A function is a block of organized, reusable code that is used to perform a single, related
action. Functions provide better modularity for application and a high degree of code reusing.
Defining a Function
Function blocks begin with the keyword def followed by the function name and
n
parentheses ( ( ) ).
Any input parameters or arguments should be placed within these parentheses. You
g.i
can also define parameters inside these parentheses.
The first statement of a function can be an optional statement - the documentation
string of the function or docstring.
rin
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return
ee
None.
gin
Syntax
function_suite
return [expression]
By default, parameters have a positional behavior and you need to inform them in the same
arn
Example
Le
The following function takes a string as input parameter and prints it on standard screen.
w.
return
Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be included in
the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from
another function or directly from the Python prompt. Following is the example to call
printme() function −
#!/usr/bin/python
n
Pass by reference vs value
g.i
All parameters (arguments) in the Python language are passed by reference. It means if you
change what a parameter refers to within a function, the change also reflects back in the
rin
calling function. For example −
mylist = [10,20,30];
En
changeme( mylist );
print "Values outside the function: ", mylist
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
arn
Function Arguments
Le
You can call a function by using the following types of formal arguments:
Required arguments
w.
Keyword arguments
Default arguments
Variable-length arguments
ww
Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here,
the number of arguments in the function call should match exactly with the function
definition.
print str
return;
printme()
n
Keyword arguments
g.i
Keyword arguments are related to the function calls. When you use keyword arguments in a
function call, the caller identifies the arguments by the parameter name.
rin
This allows you to skip arguments or place them out of order because the Python interpreter
is able to use the keywords provided to match the values with parameters. You can also make
keyword calls to the printme() function in the following ways −
#!/usr/bin/python
ee
gin
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
En
return;
Default arguments
Le
A default argument is an argument that assumes a default value if a value is not provided in
the function call for that argument.
w.
Variable-length arguments
You may need to process a function for more arguments than you specified while defining
the function. These arguments are called variable-length arguments and are not named in the
function definition, unlike required and default arguments.
n
return [expression]
g.i
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword
variable arguments. This tuple remains empty if no additional arguments are specified during
the function call. Following is a simple example −
rin
# Function definition is here
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
ee
print "Output is: "
gin
print arg1
for var in vartuple:
print var
return;
En
70
60
50
w.
def sum(a,b):
ww
return a+b
def sub(a,b):
return a-b
def mul(a,b):
return a*b
def div(a,b):
return(a//b)
print ("Subtraction",sub(8,4))
print ("Multiplication",mul(8,4))
print ("Division",div(8,2))
Output:
n
Addition 11
g.i
Subtraction 4
Multiplication 32
rin
Division 4
return 1
En
y=y%len(l)
return l[y:]+l[:y]
arn
print(rotate([1,2,3,4]))
print(rotate([2,3,4,1]))
Le
print(rotate([3,4,1,2]))
w.
print(rotate([3,2,1,4]))
Output:
ww
[2, 3, 4, 1]
[3, 4, 1, 2]
[4, 1, 2, 3]
[2, 1, 4, 3]
def swap(a,b):
a,b=b,a
swap(4,5)
Output:
n
Values after swapping 5 4
g.i
4. Distance between two points
import math
rin
p1 = [4, 0]
p2 = [6, 6] ee
distance = math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) )
gin
print(distance)
Output:
En
6.324555320336759
arn
5.Sum of n numbers
def sum(n):
Le
s=0
w.
for i in range(1,n):
s=s+i
ww
return s
n=int(n)
Output:
Sum of n numbers 45
def sumofevenodd(n):
se=0
so=0
for i in range(1,n):
n
if i%2==0:
g.i
se=se+i
else:
rin
so=so+i
return se,so ee
n=input("Enter the input value of n")
gin
n=int(n)
Output:
def sum(farg,*args):
w.
s=0
for i in args:
ww
s=s+i
sum(1,4,5,6)
Output:
def someFunction(**kwargs):
if 'text' in kwargs:
print (kwargs['text'])
someFunction(text='welcome')
Output:
Welcome
9. Keyword arguments
n
def print_info(name,age=25):
g.i
print ("Name:",name)
print("Age",age)
rin
print_info(name='Uma',age=35)
print_info(name='Reka') ee
Output:
gin
Name: Uma
Age 35
En
Name: Reka
Age 25
arn
Le
w.
ww
Conditionals:
.in
Boolean values:
ng
Boolean values are the two constant objects False and True. They are used to represent truth
values (although other values can also be considered false or true). In numeric contexts (for
example when used as the argument to an arithmetic operator), they behave like the
eri
integers 0 and 1, respectively.
To see what the return value (True or False) will be, simply print it out.
En
str="Hello World"
print str.isalpha() #False #check if all char in the string are alphabetic
The if statement
Conditional statements give us this ability to check the conditions. The simplest form is
the if statement, which has the general form:
if BOOLEAN EXPRESSION:
STATEMENTS
The colon (:) is significant and required. It separates the header of the compound statement from
the body.
The line after the colon must be indented. It is standard in Python to use four spaces for
.in
indenting.
All lines indented the same amount after the colon will be executed whenever the
ng
BOOLEAN_EXPRESSION is true.
Here is an example:
eri
If a>0:
The header line of the if statement begins with the keyword if followed by a boolean
expression and ends with a colon (:).
The indented statements that follow are called a block. The first unintended statement marks the
end of the block. Each statement inside the block must have the same indentation.
if else statement
when a condition is true the statement under if part is executed and when it is false the statement
under else part is executed
if a>0:
print(“ a is positive”)
.in
else:
ng
print(“ a is negative”)
eri
Flow Chart
e
gin
En
arn
Le
w.
ww
if BOOLEAN EXPRESSION:
else:
Each statement inside the if block of an if else statement is executed in order if the boolean
expression evaluates to True. The entire block of statements is skipped if the boolean expression
evaluates to False, and instead all the statements under the else clause are executed.
else:
.in
pass
Chained Conditionals
ng
Sometimes there are more than two possibilities and we need more than two branches. One way
to express a computation like that is a chained conditional:
eri
if x < y:
STATEMENTS_A
e
gin
elif x > y:
STATEMENTS_B
En
else:
STATEMENTS_C
arn
.in
ng
e eri
gin
elif is an abbreviation of else if. Again, exactly one branch will be executed. There is no limit of
the number of elif statements but only a single (and optional) final else statement is allowed and
En
if choice == '1':
arn
print("Monday.")
print(“Tuesday")
print("Wednesday")
ww
else:
print("Invalid choice.")
Another Example
def letterGrade(score):
letter = 'A'
letter = 'B'
.in
if score >= 70:
letter = 'C'
ng
else: # grade must D or F
eri
letter = 'D'
else:
e
gin
letter = 'F'
return letter
En
Program1:
if x1>x2:
print("x1 is big")
w.
else:
ww
print("x2 is big")
Program2:
largest = num1
largest = num2
.in
else:
largest = num3
ng
print("The largest number between",num1,",",num2,"and",num3,"is",largest)
eri
import math
a=int(input("Enter a"))
e
gin
b=int(input("enter b"))
c=int(input("enter c"))
En
d = b**2-4*a*c
d=int(d)
arn
if d < 0:
elif d == 0:
w.
x = (-b+math.sqrt(b**2-4*a*c))//2*a
else:
x1 = (-b+math.sqrt(b**2-4*a*c))//2*a
x2 = (-b-math.sqrt(b**2-4*a*c))//2*a
print ("This equation has two solutions: ", x1, " and", x2)
x=int(input("enter a number"))
if x%2==0:
else:
print("it is Odd")
.in
Program 4: Positive or negative
x=int(input("enter a number"))
ng
if x>0:
print("it is positive")
eri
else:
print("it is negative")
e
gin
Each condition is checked in order. If the first is false, the next is checked, and so on. If one of
En
them is true, the corresponding branch executes, and the statement ends. Even if more than one
condition is true, only the first true branch executes.
arn
Nested Conditionals
Flowchart
Le
w.
ww
.in
ng
eri
e
gin
if x < y:
STATEMENTS_A
En
else:
if x > y:
arn
STATEMENTS_B
else:
Le
STATEMENTS_C
w.
The outer conditional contains two branches. The second branch contains another if statement,
which has two, branches of its own. Those two branches could contain conditional statements as
well.
ww
Logical operators often provide a way to simplify nested conditional statements. For example,
we can rewrite the following code using a single conditional:
if x < 10:
Iteration
Computers are often used to automate repetitive tasks. Repeating identical or similar tasks
without making errors is something that computers do well and people do poorly.
While loop
While statement
The general syntax for the while statement looks like this:
.in
While BOOLEAN_EXPRESSION:
ng
STATEMENTS
Like the branching statements and the for loop, the while statement is a compound statement
eri
consisting of a header and a body. A while loop executes an unknown number of times, as long
at the BOOLEAN EXPRESSION is true.
e
The flow of execution for a while statement works like this:
gin
Evaluate the condition (BOOLEAN EXPRESSION), yielding False or True.
If the condition is false, exit the while statement and continue execution at the next statement.
En
If the condition is true, execute each of the STATEMENTS in the body and then go back to step
1.
arn
n=int(input("enter n"))
Le
s=0
while(n>0):
w.
r=n%10
ww
s=s+r
n=n/10
print("sum of digits",int(s))
OUTPUT
enter n 122
sum of digits 5
n=int(input("enter n"))
a=n
a=int(a)
s=0
.in
while(n>0):
r=n%10
ng
s=s+r*r*r
n=n//10
eri
print(s)
if(s==a):
e
gin
print("It is an Armstrong number")
else:
En
n=int(input("enter n"))
a=n
Le
a=int(a)
w.
s=0
while(n>0):
ww
r=n%10
s=s*10+r
n=n//10
print(s)
if(s==a):
print("It is a Palindrome")
else:
for loop
.in
The for loop processes each item in a sequence, so it is used with Python’s sequence data types -
strings, lists, and tuples.
ng
Each item in turn is (re-)assigned to the loop variable, and the body of the loop is executed.
eri
for LOOP_VARIABLE in SEQUENCE:
STATEMENTS
e
gin
>>> for i in range(5):
i is now 0
i is now 1
arn
i is now 2
i is now 3
Le
i is now 4
>>>
w.
Example 2:
ww
Using the tab character ('\t') makes the output align nicely.
0 1
1 2
2 4
3 8
4 16
5 32
6 64
.in
7 128
8 256
ng
9 512
10 1024
eri
11 2048
12 4096
e
gin
Meaning Math Symbol Python Symbols
Equals = ==
Le
Not equal ≠ !=
def convert(n):
ww
if n > 1:
convert(n//2)
dec=int(input("enter n"))
convert(dec)
OUPUT
enter n 25
11001
.in
dec = int(input("enter n"))
ng
print(bin(dec),"in binary.")
print(oct(dec),"in octal.")
eri
print(hex(dec),"in hexadecimal.")
OUTPUT
e
gin
enter n 25
0b11001 in binary.
0o31 in octal.
arn
0x19 in hexadecimal.
n= int(input("enter a number"))
w.
f=1
for i in range(1,n+1):
ww
f = f*i
OUTPUT
enter a number 7
.in
# prime numbers are greater than 1
if num > 1:
ng
for i in range(2,num):
if (num % i) == 0:
eri
break
else:
e
gin
print(num)
OUTPUT
En
2
Le
3
w.
7
ww
11
13
17
19
23
a = int(input("enter a"))
b=int(input("enter b"))
temp = a
.in
a=b
b = temp
ng
print("\nafter swapping\na=", a, " b=", b)
eri
a = int(input("enter a"))
b=int(input("enter b"))
e
gin
print("before swapping\na=", a, " b=", b)
a,b=b,a
En
if ch == '+':
ww
res = n1+n2
elif ch == '-':
res = n1-n2
elif ch == '*':
res = n1 * n2
elif ch == '/':
res = n1 / n2
.in
print(n1, "/", n2, "=", res)
else:
ng
print("enter a valid operator")
Fruitful function
eri
Fruitful function is a special function in which function is defined in the return statement,
It is a function with return type as expression.The first example is area, which returns the area of
a circle with the given radius: e
gin
def cal(r1):
return 3.14*r1*r1
En
r=int(input("enter r"))
arn
print("ans=",cal(r))
We have seen the return statement before, but in a fruitful function the return statement includes
a return value. This statement means: "Return immediately from this function and use the
Le
following expression as a return value." The expression provided can be arbitrarily complicated,
so we could have written this function more concisely:
w.
Sometimes it is useful to have multiple return statements, one in each branch of a conditional:
def absoluteValue(x):
ww
if x<0:
return -x
else:
return x
Since these return statements are in an alternative conditional, only one will be executed. As
soon as one is executed, the function terminates without executing any subsequent statements.
Code that appears after a return statement, or any other place the flow of execution can never
reach, is called dead code.
To deal with increasingly complex programs, you might want to try a process called
incremental development. The goal of incremental development is to avoid long
debugging sessions by adding and testing only a small amount of code at a time.
As an example, suppose you want to find the distance between two points, given by
the coordinates (x1, y1) and (x2, y2). By the Pythagorean theorem, the distance is:
distance =
√ (x2 − x1)2 + (y2 − y1)2
.in
Program for Distance Calculation
import math
ng
def distance(x1, y1, x2, y2):
dx=x2-x1
eri
dy=y2-y1
return (math.sqrt(dx**2)+(dy**2))
x1=int(input("enter x1"))
e
gin
y1=int(input("enter y1"))
x2=int(input("enter x2"))
y2=int(input("enetr y2"))
print(distance(x1,y1,x2,y2))
En
def recur_fibo(n):
if n <= 1:
Le
return n
else:
w.
return(recur_fibo(n-1) + recur_fibo(n-2))
ww
if nterms <= 0:
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
Function composition is a way of combining functions such that the result of each function is
.in
passed as the argument of the next function. For example, the composition of two
functions fand g is denoted f(g(x)). x is the argument of g, the result of g is passed as the
argument of fand the result of the composition is the result of f.
ng
Let’s define compose2, a function that takes two functions as arguments (f and g) and returns a
function representing their composition:
eri
def compose2(f, g):
... return x * 2
...
arn
... return x + 1
Le
...
>>> inc_and_double(10)
ww
Syntax
pass
Example
#!/usr/bin/python3
if letter == 'h':
pass
.in
print ("Good bye!")
ng
Output
When the above code is executed, it produces the following result −
eri
Current Letter : P
Current Letter : y
e
gin
Current Letter : t
This is pass block
Current Letter : h
En
Current Letter : o
Current Letter : n
arn
Good bye!
Le
Local Variables
w.
Define the variables inside the function definition, they are local to this function by default. This
ww
means that anything will do to such a variable in the body of the function will have no effect on
other variables outside of the function, even if they have the same name. This means that the
function body is the scope of such a variable, i.e. the enclosing context where this name with its
values is associated.
def f():
print(s)
f()
Output:
.in
I Love Paris in the summer.
ng
The variable s is defined as the string "I love Paris in the summer!", before calling the function
f(). The body of f() consists solely of the "print(s)" statement. As there is no local variable s, i.e.
eri
no assignment to s, the value from the global variable s will be used. So the output will be the
string "I love Paris in the summer!". what will happen, if we change the value of s inside of the
e
gin
function f()?
def f():
En
print(s)
f()
print(s)
w.
Output:
ww
I love London!
I love Paris!
Even though the name of both global and local variables are same. The value of the local
variables does not affect the global variables. If we are directly calling the global variable,
without assigning any values to the variable, if both local and global variables are same. It
produces an Unbound Local Error.
For Example,
def f():
.in
print(s)
ng
print(s)
eri
s = "I love Paris!"
f()
e
gin
Unbound Local Error: local variable's' referenced before assignment. Because Local variable s
referenced before assignment.
En
We want use global variable in python. We should give keyword global in python
def f():
Le
global s
print(s)
w.
Output:
Recursive Functions:
.in
A recursive function is a function that calls itself. To prevent a function from repeating itself
indefinitely, it must contain at least one selection statement. This statement examines a condition
ng
called a base case to determine whether to stop or to continue with another recursive step.
1. Program for finding the factorial of a given no
eri
def fact(n):
if n==0:
return 1
e
gin
else:
return n*fact(n-1)
En
def fib(n):
w.
if n<3:
return 1
ww
else:
return fib(n-1)+fib(n-2)
print("The nth fibbonacci no is",fib(10))
Output:
The nth Fibonacci series is 55.
Strings
.in
Len
Len is a inbuilt function. It returns number of characters in a string.
ng
len(fruit)
Out[4]: 6
eri
String Slices:
A segment of a string is called string slices.
Fruit=’banana’ e
gin
Fruit[1:4]
It returns the output as ‘ana’. It includes the first character and excludes the last character in a
En
string.
Fruit[:3]
arn
Fruit[3:3]
If first index is greater than or equal to the second index. Then it returns empty string as output’
w.
‘.
Fruit[:]
ww
String Immutable
We cant change the value of the strings.
fruit[0]='w'
Traceback (most recent call last):
File "<ipython-input-10-839a456c8838>", line 1, in <module>
fruit[0]='w'
TypeError: 'str' object does not support item assignment
Strings are immutable.
String Methods
.in
ng
Built-in String Methods
A method is similar to a function. It takes an argument and returns the values. A method call is called invocation.
eri
Python includes the following built-in methods to manipulate strings −
2 center(width, fillchar)
Returns a space-padded string with the original string centered to a total of width columns.
arn
4 decode(encoding='UTF-8',errors='strict')
Decodes the string using the codec registered for encoding. encoding defaults to the default
ww
string encoding.
5 encode(encoding='UTF-8',errors='strict')
Returns encoded string version of string; on error, default is to raise a ValueError unless
errors is given with 'ignore' or 'replace'.
7 expandtabs(tabsize=8)
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not
provided.
.in
8 find(str, beg=0 end=len(string))
ng
Determine if str occurs in string or in a substring of string if starting index beg and ending
index end are given returns index if found and -1 otherwise.
eri
9 index(str, beg=0, end=len(string))
e
Same as find(), but raises an exception if str not found.
gin
10 isalnum()
En
Returns true if string has at least 1 character and all characters are alphanumeric and false
otherwise.
arn
11 isalpha()
Returns true if string has at least 1 character and all characters are alphabetic and false
otherwise.
Le
12 isdigit()
w.
13 islower()
Returns true if string has at least 1 cased character and all cased characters are in lowercase
and false otherwise.
14 isnumeric()
Returns true if a unicode string contains only numeric characters and false otherwise.
15 isspace()
Returns true if string contains only whitespace characters and false otherwise.
16 istitle()
.in
Returns true if string is properly "titlecased" and false otherwise.
ng
17 isupper()
Returns true if string has at least one cased character and all cased characters are in
uppercase and false otherwise.
eri
18 join(seq)
e
Merges (concatenates) the string representations of elements in sequence seq into a string,
gin
with separator string.
19 len(string)
En
20 ljust(width[, fillchar])
arn
Returns a space-padded string with the original string left-justified to a total of width
columns.
Le
21 lower()
w.
22 lstrip()
23 maketrans()
24 max(str)
25 min(str)
.in
26 replace(old, new [, max])
Replaces all occurrences of old in string with new or at most max occurrences if max given.
ng
27 rfind(str, beg=0,end=len(string))
eri
Same as find(), but search backwards in string.
29 rjust(width,[, fillchar])
Returns a space-padded string with the original string right-justified to a total of width
columns.
arn
30 rstrip()
Le
31 split(str="", num=string.count(str))
Splits string according to delimiter str (space if not provided) and returns list of substrings;
ww
32 splitlines( num=string.count('\n'))
Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs
removed.
33 startswith(str, beg=0,end=len(string))
Determines if string or a substring of string (if starting index beg and ending index end are
given) starts with substring str; returns true if so and false otherwise.
34 strip([chars])
.in
35 swapcase()
ng
Inverts case for all letters in string.
eri
36 title()
Returns "titlecased" version of string, that is, all words begin with uppercase and the rest
are lowercase.
e
gin
37 translate(table, deletechars="")
Translates string according to translation table str(256 chars), removing those in the del
En
string.
arn
38 upper()
39 zfill (width)
Returns original string leftpadded with zeros to a total of width characters; intended for
w.
40 isdecimal()
Returns true if a unicode string contains only decimal characters and false otherwise.
This module contains a number of functions to process standard Python strings. In recent
versions, most functions are available as string methods as well (more on this below).
# File: string-example-1.py
import string
text = "Monty Python's Flying Circus"
.in
print "upper", "=>", string.upper(text)
print "lower", "=>", string.lower(text)
ng
print "split", "=>", string.split(text)
print "join", "=>", string.join(string.split(text), "+")
eri
print "replace", "=>", string.replace(text, "Python", "Java")
print "find", "=>", string.find(text, "Python"), string.find(text, "Java")
e
gin
print "count", "=>", string.count(text, "n")
count => 3
Example: Using string methods instead of string module functions
w.
# File: string-example-2.py
ww
.in
find => 6 -1
count => 3
ng
In addition to the string manipulation stuff, the string module also contains a number of
functions which convert strings to other types:
eri
Example: Using the string module to convert strings to numbers
e
gin
# File: string-example-3.py
import string
En
print int("4711"),
print string.atoi("4711"),
arn
print float("4711"),
print string.atof("1"),
print string.atof("1.23e5")
.in
print(c)
revword('string')
ng
Output:
g
eri
n
i
r e
gin
t
s
En
def find(word,letter):
index=0
Le
while index<len(word):
if word[index]==letter:
w.
return index
index=index+1
ww
return -1
print("the letter present", find('malayalm','l'))
Output:
The letter present 2
def find(word,ch):
count=0
for letter in word:
if letter==ch:
count=count+1
return count
.in
print("The total count for the given letter", find('malayalm','l'))
Output:
ng
The total count for the given letter 2
3. String Palindrome
eri
def palin(word):
y=word[::-1]
if word==y: e
gin
print("Palindrome")
else:
En
print("Not Palindrome")
palin('good')
arn
Output:
Not Palindrome.
5. Write a Program for GCD of two numbers
Le
def ComputeGCD(x,y):
while y:
w.
x,y=y,x%y
return x
ww
print(exp)
expo(5,2)
Output
25
.in
ng
eri
e
gin
En
arn
Le
w.
ww
A list is a sequence of values. In a string, the values are characters but in a list, list values
can be any type.
Elements or Items:
.in
The values in a list are called elements or items. list must be enclosed in square brackets
([and]).
Examples:
ng
>>>[10,20,30]
>>>[‘hi’,’hello’,’welcome’]
Nested List:
eri
A list within another list is called nested list.
Example:
[‘good’,10,[100,99]]
Empty List:
e
A list that contains no elements is called empty list. It can be created with empty
gin
brackets, [].
Assigning List Values to Variables:
Example:
>>>numbers=[40,121]
En
>>>characters=[‘x’,’y’]
>>>print(numbers,characters)
Output:
arn
[40,12][‘x’,’y’]
4.1.1 LIST OPERATIONS:
Example 1: The + operator concatenates lists:
>>>a=[1,2,3]
Le
>>>b=[4,5,6]
>>>c=a+b
>>>c
w.
Output: [1,2,3,4,5,6]
Example 2:
The * operator repeats a list given number of times:
ww
>>>[0]*4
Output:
[0,0,0,0]
>>>[1,2,3]*3
Output:
[1,2,3,1,2,3,1,2,3]
The first example repeats [0] four times.The second example repeats [1,2,3] three
times.
.in
Example:
>>>t[1:3]=[‘x’,’y’]
>>>t
ng
Output:
[‘a’,’x’,’y’,’d’,’e’,’f’]
eri
4.1.3 LIST METHODS:
Python provides methods that operate on lists.
Example:
e
1. append adds a new element to the end of a list.
>>>t=[‘a’,’b’,’c’,’d’]
gin
>>>t.append(‘e’)
>>>t
Output:
[‘a’,’b’,’c’,’d’,’e’]
En
>>>t1.extend(t2)
>>>t1
Output:
[‘a’,’b’,’c’,’d’]
Le
t2 will be unmodified.
4.1.4 LIST LOOP:
List loop is traversing the elements of a list with a for loop.
w.
Example 1:
>>>mylist=[[1,2],[4,5]]
>>>for x in mylist:
ww
if len(x)==2:
print x
Output:
[1,2]
[4,5]
Example 2:
>>>for i in range(len(numbers)):
Numbers[i]=numbers[i]*2
.in
Output:
red
green
ng
blue
purple
4.1.5 MUTABILITY:
eri
Lists are mutable. Mutable means, we can change the content without changing the
identity. Mutability is the ability for certain types of data to be changed without entirely
recreating it.Using mutable data types can allow programs to operate quickly and efficiently.
Example 1:
>>>numbers=[42,123]
En
>>>numbers[1]=5
>>>numbers
[42,5]
arn
Figure 4.1 shows the state diagram for cheeses, numbers and empty:
Lists are represented by boxes with the word “list” outside and the elements of the list
inside. cheeses refers to a list with three elements indexed 0, 1 and 2.
If a refers to an object and we assign b = a, then both variables refer to the same object:
>>> a = [1, 2, 3]
>>> b = a
.in
>>> b is a
True
ng
The state diagram looks like Figure 4.2.
e eri
Figure 4.2 State Diagram
The association of a variable with an object is called a reference. In this example, there
gin
are two references to the same object.An object with more than one reference has more than one
name, so we say that the object is aliased.If the aliased object is mutable, changes made with one
alias affect the other:
En
daniel=veggies
# Copying a complete slice CLONES a list
david=veggies[:]
Le
daniel[6]="emu"
# Daniel is a SECOND NAME for veggies so that changing Daniel also changes veggies.
# David is a COPY OF THE CONTENTS of veggies so that changing Daniel (or
veggies) does NOT change David.
w.
# Changing carrots into beetroot was done before any of the copies were made, so will
affect all of veggies, daniel and david
ww
.in
Example 1:
>>> t1 = [1, 2]
>>> t2 = t1.append(3)
ng
>>> t1
Output:
[1, 2, 3]
eri
Example 2:
>>> t2
Output:
None e
gin
En
4.2. TUPLES
A tuple is a sequence of values.
Le
The values can be any type and are indexed by integers, unlike lists.
Tuples are immutable.
Syntactically, a tuple is a comma-separated list of values:
w.
.in
name. Most list operators also work on tuples. The bracket operator indexes an element:
Example:
>>> t = ('a', 'b', 'c', 'd', 'e')
ng
>>> t[0]
Output: 'a' And the slice operator selects a range of elements.
Example:
eri
>>> t[1:3] Output:('b', 'c')But if we try to modify one of the elements of the
tuple, we get an error:
>>> t[0] = 'A'
e
TypeError: object doesn't support item assignmentBecause tuples are immutable, we
can’t modify the elements. But we can replace one
gin
tuple with another: Example:
>>> t = ('A',) + t[1:]
>>> t
Output:
En
('A', 'b', 'c', 'd', 'e')This statement makes a new tuple and then makes t refer to it.
The relational operators work with tuples and other sequences; Python starts by
comparing the first element from each sequence. If they are equal, it goes on to the next
arn
elements, and so on, until it finds elements that differ. Subsequent elements are not considered
(even if they are really big).
Example 1:
>>> (0, 1, 2) < (0, 3, 4)
Le
Output:
True
Example 2:
w.
.in
'monty'
>>> domain
'python.org'
ng
4.2.2 TUPLE AS RETURN VALUES
A function can only return one value, but if the value is a tuple, the effect is the same as
returning multiple values. For example, if we want to divide two integers and compute the
eri
quotient and remainder, it is inefficient to compute x/y and then x%y. It is better to compute
them both at the same time. The built-in function divmod takes two arguments and returns a
tuple of two values, the quotient and remainder. We can store the result as a tuple:
Example:
>>> t = divmod(7, 3) e
gin
>>> t
Ouput:
(2, 1)
Or use tuple assignment to store the elements separately:
En
Example:
>>> quot, rem = divmod(7, 3)
>>> quot
arn
Output:
2
Example:
>>> rem
Le
Output:
1
Here is an example of a function that returns a tuple:
w.
def min_max(t):
return min(t), max(t)
max and min are built-in functions that find the largest and smallest elements of a
ww
.in
Example:
>>> t = [('a', 0), ('c', 2), ('b', 1)]
>>> d = dict(t)
ng
>>> d
Output:
{'a': 0, 'c': 2, 'b': 1}
eri
Combining dict with zip yields a concise way to create a dictionary:
Example:
>>> d = dict(zip('abc', range(3)))
Output:
>>> d
e
gin
{'a': 0, 'c': 2, 'b': 1}
The dictionary method update also takes a list of tuples and adds them, as key-value
pairs, to an existing dictionary. It is common to use tuples as keys in dictionaries (primarily
because we can’t use lists). For example, a telephone directory might map from last-name, first-
En
name pairs to telephone numbers. Assuming that we have defined last, first and number, we
could write: directory [last, first] = number
The expression in brackets is a tuple. We could use tuple assignment to traverse this
arn
There are two ways to represent tuples in a state diagram. The more detailed version
shows the indices and elements just as they appear in a list. For example, the tuple('Cleese',
w.
'John') would appear as in Figure 4.4. But in a larger diagram we might want to leave out the
details. For example, a diagram of the telephone directory might appear as in Figure 4.5.
Here the tuples are shown using Python syntax as a graphical shorthand. The telephone
ww
number in the diagram is the complaints line for the BBC, so please don’t call it.
.in
4.4.1 LIST COMPREHENSION
The function shown below takes a list of strings, maps the string method capitalize to the
elements, and returns a new list of strings:
ng
def capitalize_all(t):
res = []
for s in t:
eri
res.append(s.capitalize())
return res
We can write this more concisely using a list comprehension:
def capitalize_all(t):
e
gin
return [s.capitalize() for s in t]
The bracket operators indicate that we are constructing a new list. The expression inside
the brackets specifies the elements of the list, and the ‘for’ clause indicates what sequence we are
traversing.The syntax of a list comprehension is a little awkward because the loop variable, s in
En
def only_upper(t):
res = []
for s in t:
if s.isupper():
Le
res.append(s)
return res
We can rewrite it using a list comprehension
w.
def only_upper(t):
return [s for s in t if s.isupper()]
List comprehensions are concise and easy to read, at least for simple expressions. And
ww
they are usually faster than the equivalent for loops, sometimes much faster.
But, list comprehensions are harder to debug because we can’t put a print statement
inside the loop. We can use them only if the computation is simple enough that we are likely to
get it right the first time.
4.5 ILLUSTRATIVE PROGRAMS SELECTION SORT
Selection sort is one of the simplest sorting algorithms. It is similar to the hand picking
where we take the smallest element and put it in the first position and the second smallest at the
second position and so on. It is also similar. We first check for smallest element in the list and
swap it with the first element of the list. Again, we check for the smallest number in a sub list,
excluding the first element of the list as it is where it should be (at the first position) and put it in
.in
smallest = min(a[i:])
#index of smallest element
index_of_smallest = a.index(smallest)
ng
#swapping
a[i],a[index_of_smallest] = a[index_of_smallest],a[i]
i=i+1
eri
print (a)
Output
>>>
[10, 11, 12, 14, 15, 16, 19]
4.5.2 INSERTION SORT e
gin
Insertion sort is similar to arranging the documents of a bunch of students in order of
their ascending roll number. Starting from the second element, we compare it with the first
element and swap it if it is not in order. Similarly, we take the third element in the next iteration
and place it at the right place in the sub list of the first and second elements (as the sub list
En
containing the first and second elements is already sorted). We repeat this step with the fourth
element of the list in the next iteration and place it at the right position in the sub list containing
the first, second and the third elements. We repeat this process until our list gets sorted.
arn
ALGORITHM:
1. Compare the current element in the iteration (say A) with the previous adjacent element
to it. If it is in order then continue the iteration else, go to step 2.
Le
2. Swap the two elements (the current element in the iteration (A) and the previous adjacent
element to it).
3. Compare A with its new previous adjacent element. If they are not in order, then proceed
w.
to step 4.
4. Swap if they are not in order and repeat steps 3 and 4.
5. Continue the iteration.
ww
PROGRAM:
a = [16, 19, 11, 15, 10, 12, 14]
#iterating over a
for i in a:
j = a.index(i)
#i is not the first element
while j>0:
#not in order
if a[j-1] > a[j]:
.in
merging two halves. The merge(arr, l, m, r) is key process that assumes that arr[l..m] and
arr[m+1..r] are sorted and merges the two sorted sub-arrays into one. See following C
implementation for details.
ng
The following diagram shows the complete merge sort process for an example array {38,
27, 43, 3, 9, 82, 10}. If we take a closer look at the diagram, we can see that the array is
recursively divided in two halves till the size becomes 1. Once the size becomes 1, the merge
eri
processes comes into action and starts merging arrays back till the complete array is merged.
e
gin
En
arn
Le
w.
ww
ALGORITHM:
MergeSort(arr[], l, r)
If r > l
1. Find the middle point to divide the array into two halves:
middle m = (l+r)/2
2. Call mergeSort for first half:
Call mergeSort(arr, l, m)
3. Call mergeSort for second half:
.in
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
ng
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
eri
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf): e
gin
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
En
alist[k]=righthalf[j]
j=j+1
k=k+1
arn
print("Merging ",alist)
n = input("Enter the size of the list: ")
n=int(n);
alist = []
Le
for i in range(n):
alist.append(input("Enter %dth element: "%i))
mergeSort(alist)
w.
print(alist)
Input:
a = [16, 19, 11, 15, 10, 12, 14]
ww
Output:
>>>
[10, 11, 12, 14, 15, 16, 19]
4.5.5 HISTOGRAM
A histogram is a visual representation of the Distribution of a Quantitative variable.
Appearance is similar to a vertical bar graph, but used mainly for continuous
distribution
It approximates the distribution of variable being studied
A visual representation that gives a discretized display of value counts.
.in
ng
def histogram(s):
d = dict()
for c in s:
eri
if c not in d:
d[c] = 1
else:
return d
d[c] += 1
e
gin
The name of the function is histogram, which is a statistical term for a collection of
counters (or frequencies).
The first line of the function creates an empty dictionary. The for loop traverses the
En
string.Each time through the loop, if the character c is not in the dictionary, we create a new item
with key c and the initial value 1 (since we have seen this letter once). If c is already in the
dictionary we increment d[c]. Here’s how it works:
arn
Example:
>>> h = histogram('brontosaurus')
>>> h
Output:
Le
in the dictionary, get returns the corresponding value; otherwise it returns the default value. For
example:
>>> h = histogram('a')
ww
>>> h
{'a': 1}
>>> h.get('a', 0)
1
>>> h.get('b', 0)
0
As an exercise, use get to write histogram more concisely. We should be able to eliminate
the if statement.
.in
Again, the keys are in no particular order. To traverse the keys in sorted order, we can use
the built-in function sorted:
>>> for key in sorted(h):
ng
... print(key, h[key])
a1
o1
eri
p1
r2
t1
e
Write a function named choose_from_hist that takes a histogram as defined in Histogram
given above and returns a random value from the histogram, chosen with probability in
gin
proportion to frequency. For example, for this histogram:
>>> t = ['a', 'a', 'b']
>>> hist = histogram(t)
>>> hist
En
{'a': 2, 'b': 1}
The function should return 'a' with probability 2/3 and 'b' with probability 1/3.
TWO MARKS
arn
Examples:
>>>[10,20,30]
>>>[‘hi’,’hello’,’welcome’]
2. What is a nested list? Give example.
w.
.in
the object is aliased.
If the aliased object is mutable, changes made with one alias affect the other.
Example:
ng
If a refers to an object and we assign b = a, then both variables refer to the same object:
>>> a = [1, 2, 3]
>>> b = a
eri
>>> b is a True
8. What is the difference between copying and cloning lists?
Copying a list gives it another name but copying a complete slice clones a list.
e
9. Give example for copying and cloning lists.
Example:
gin
veggies=["potatoes","carrots","pepper","parsnips","swedes","onion","min
ehead"]
veggies[1]="beetroot"
Copying a list
En
daniel=veggies
CLONES a list
david=veggies[:]
arn
daniel[6]="emu"
10. Define Dictionaries. Give example.
A dictionary is an associative array (also known as hashes). Any key of the
dictionary is associated (or mapped) to a value. The values of a dictionary can be
Le
>>> t = d.items()
>>> t
Output:
ww
.in
and restart, they pick up where they left off.
Examples of persistent programs are operating systems, which run pretty much
ng
whenever a computer is on, and web servers, which run all the time, waiting for requests to come
in on the network.
eri
One of the simplest ways for programs to maintain their data is by reading and writing
text files. We have already seen programs that read text files; in this chapter we will see
e
programs that write them. An alternative is to store the state of the program in a database.
gin
5.1 FILES:TEXTFILE
A textfile is a sequence of characters stored on a permanent medium like a hard drive,
flash memory, or CD-ROM.
En
addition to printable characters, text files also contain the nonprinting newline character, \n, to
denote the end of each text line. the newline character causes the screen cursor to move to the
beginning of the next screen line. Thus, text files can be directly viewed and created using a text
Le
editor.
In contrast, binary files can contain various types of data, such as numerical values,
w.
and are therefore not structured as lines of text. Such files can only be read and written via a
computer program.
ww
All files must first be opened before they can be used. In Python, when a file is opened, a file
object is created that provides methods for accessing the file.
.in
file_object = open(“filename”, “mode”) where file_object is the variable to add the file object.
To open a file for reading, the built-in open function is used as shown,
ng
input_file=open('myfile.txt','r')
eri
The modes are:
‘r’ – Read mode which is used when the file is only being read
e
gin
‘w’ – Write mode which is used to edit and write new information to the file (any existing
files with the same name will be erased when this mode is activated)
‘a’ – Appending mode, which is used to add new data to the end of the file; that is new
En
with a file
The first argument is the file name to be opened, 'myfile.txt'. The second argument, 'r',
Le
indicates that the file is to be opened for reading. (The second argument is optional when
opening a file for reading.) If the file is successfully opened, a file object is created and assigned
w.
First, if the file name does not exist, then the program will terminate with a “no such file or
directory” error.
... open('testfile.txt','r')
Traceback (most recent call last):
File " , pyshell#1 . ", line 1, in , module .
open('testfile.txt','r')
IOError: [Errno 2] No such file or directory:
'testfile.txt'
Visit For More : www.LearnEngineering.in
Visit For More : www.LearnEngineering.in
This error can also occur if the file name is not found in the location looked for
(uppercase and lowercase letters are treated the same for file names). When a file is opened,
it is first searched for in the same folder/directory that the program resides in.
However, an alternate location can be specified in the call to open by providing a path to
the file.
input_file=open('data/myfile.txt','r')
.in
the file is searched for in a subdirectory called data of the directory in which the program
is contained. Thus, its location is relative to the program location. (Although some operating
ng
systems use forward slashes, and other backward slashes in path names, directory paths in
Python are always written with forward slashes and are automatically converted to backward
eri
slashes when required by the operating system executing on.) Absolute paths can also be
provided giving the location of a file anywhere in the file system.
e
gin
input_file= open('C:/mypythonfiles/data/myfile.txt','r')
When the program has finished reading the file, it should be closed by calling the close method
En
input_file=open('C:/mypythonfiles/data/myfile.txt','r')
arn
output_file=open('mynewfile.txt','w')
output_file.close()
.in
write () #Used to write a fixed sequence of characters to a file
ng
writelines() #writelines can write a list of strings.
eri
f = open("test.txt","w") #opens file with name of "test.txt"
f.close()
e
gin
En
arn
Le
print fh.read()
To read one line at a time:
fh = open("hello".txt", "r")
print fh.readline()
To read a list of lines:
fh = open("hello.txt.", "r")
print fh.readlines()
To write to a file:
fh = open("hello.txt","w")
write("Hello World")
Visit For More : www.LearnEngineering.in
fh.close()
Visit For More : www.LearnEngineering.in
.in
ng
eri
5.1.4 FORMAT OPERATOR
The argument of write has to be a string, so if we want to put other values in a file, we
e
have to convert them to strings. The easiest way to do that is with str:
gin
>>> x = 52
En
>>> fout.write(str(x))
arn
which specify how the second operand is formatted. The result is a string.
For example, the format sequence '%d' means that the second operand should be formatted
w.
as a decimal integer:
ww
>>> camels = 42
>>> '%d' % camels
'42'
The result is the string '42', which is not to be confused with the integer value 42.
A format sequence can appear anywhere in the string, so you can embed a value
in a
If there is more than one format sequence in the string, the second argument has to be a
tuple. Each format sequence is matched with an element of the tuple, in order.
The following example uses '%d' to format an integer, '%g' to format a floating-point
number, and '%s' to format a string:
.in
'In 3 years I have spotted 0.1 camels.'
ng
The number of elements in the tuple has to match the number of format sequences in the
string. Also, the types of the elements have to match the format sequences:
eri
>>> '%d %d %d' % (1, 2)
TypeError: not enough arguments for format string
>>> '%d' % 'dollars'
e
TypeError: %d format: a number is required, not str
gin
5.2 COMMAND LINE ARGUMENTS
En
sys.argv is a list in Python, which contains the command-line arguments passed to the
w.
script.
With the len(sys.argv) function you can count the number of arguments.
ww
If you are gonna work with command line arguments, you probably want to
use sys.argv.
To use sys.argv, you will first have to import the sys module.
Example
import sys
print "This is the name of the script: ", sys.argv[0]
print "Number of arguments: ", len(sys.argv)
print "The arguments are: " , str(sys.argv)
Output
This is the name of the script: sysargv.py Visit For More : www.LearnEngineering.in
Number of arguments in: 1
Visit For More : www.LearnEngineering.in
.in
5.3 ERRORS AND EXCEPTIONS, HANDLING EXCEPTIONS
ng
Various error messages can occur when executing Python programs. Such errors are
eri
called exceptions. So far we have let Python handle these errors by reporting them on the screen.
Exceptions can
be “caught” and “handled” by a program, however, to either correct the error and continue
e
gin
execution,
or terminate the program gracefully.
5.3.1 WHAT IS AN EXCEPTION?
En
as standard exceptions .
Base class for all errors that occur for
ArithmeticError
numeric calculation.
Le
fails.
Raised when division or modulo by zero
ZeroDivisionError
takes place for all numeric types.
ww
.in
ValueError type has the valid type of arguments, but the
arguments have invalid values specified.
Raised when a generated error does not fall
ng
RuntimeError
into any category.
eri
5.3.2 PYTHON EXCEPTION HANDLING - TRY, EXCEPT AND FINALLY
try:
such cases, an exception (object) is raised that can be caught
statements
by its client code (the code that called it), or the client’s client
except ExceptionType:
arn
code, etc., until handled (i.e. the exception is caught and the
statements error appropriately dealt with). If an exception is thrown back
except ExceptionType: to the top-level code and never caught, then the program
Le
statements
terminates displaying the exception type that occurred.
w.
ww
import math
.in
num=int(input('Enter the number'))
print('the factorial is',math.factorial(num))
Output
ng
Enter the number-5
ValueError:Recovery
factorial() via
not defined for negative values
eri
Example:Program Exception Handling
import math
num=int(input('Enter the number'))
valid_input=False; e
gin
while not valid_input:
try:
result=math.factorial(num);
En
except ValueError:
print('Cannot recompute reenter again')
num=int(input('Please reenter'))
Le
Output
Enter the number-5 Cannot recompute reenter again
Please reenter5
w.
A Python module is a file containing Python definitions and statements. The module that
is directly executed to start a Python program is called the main module. Python provides
standard (built-in) modules in the Python Standard Library.
Each module in Python has its own namespace: a named context for its set of identifiers.
The fully
Python has a math module that provides most of the familiar mathematical functions. A
module is a file that contains a collection of related functions.
Before we can use the module, we have to import it:
This statement creates a module object named math. If you print the module object, you
.in
get some information about it:
ng
>>> print math
<module 'math' (built-in)>
eri
The module object contains the functions and variables defined in the module. To access
one of the functions, you have to specify the name of the module and the name of the
e
function, separated by a dot (also known as a period). This format is called dot notation.
gin
>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)
En
The first example uses log10 to compute a signal-to-noise ratio in decibels (assuming that
Le
signal_power and noise_power are defined). The math module also provides log, which
computes logarithms base e.
w.
The second example finds the sine of radians. The name of the variable is a hint that sin
and the other trigonometric functions (cos, tan, etc.) take arguments in radians. To convert
ww
The expression math.pi gets the variable pi from the math module. The value of this
One of the most useful features of programming languages is their ability to take small
building blocks and compose them. For example, the argument of a function can be any
kind of expression, including arithmetic operators:
.in
x = math.sin(degrees / 360.0 * 2 * math.pi)
ng
x = math.exp(math.log(x+1))
eri
Almost anywhere you can put a value, you can put an arbitrary expression, with one
exception: the left side of an assignment statement has to be a variable name.
e
gin
>>> minutes = hours * 60 # right
>>> hours * 60 = minutes # wrong!
En
.in
# Python code to demonstrate the working of
ng
# fabs() and factorial()
# importing "math" for mathematical operations
eri
import math
a = -10
b= 5
# returning the absolute value. e
gin
print ("The absolute value of -10 is : ", end="")
print (math.fabs(a))
En
Output:
The absolute value of -10 is : 10.0
The factorial of 5 is : 120
Le
5. copysign(a, b) :- This function returns the number with the value of ‘a’ but with the sign of
w.
.in
d=5
# returning the copysigned value.
ng
print ("The copysigned value of -10 and 5.5 is : ", end="")
print (math.copysign(5.5, -10))
eri
# returning the gcd of 15 and 5
print ("The gcd of 5 and 15 is : ", end="")
print (math.gcd(5,15))
e
gin
Output:
The copysigned value of -10 and 5.5 is : -5.5
The gcd of 5 and 15 is : 5
En
arn
Le
w.
ww
MATH MODULE
This module contains a set of commonly-used mathematical functions, including number-theoretic
functions (such as factorial); logarithmic and power functions; trigonometric (and hyperbolic)
functions; angular conversion functions (degree/radians); and some special functions and constants
(including pi and e). A selected set of function from the math module are presented here.
math.ceil returns the ceiling of x (smallest integer greater than or equal to x).
math.fabs(x) returns the absolute value of x
.in
math.factorial(x) returns the factorial of x
math.floor() returns the floor of x (largest integer less than x).
ng
math.fsum(s) returns an accurate floating-point sum of values in s (or other iterable).
math.modf() returns the fractional and integer parts of x.
eri
math.trunc(X) returns the truncated value of s.
math.exp(x) returns e**x, for natural log base e.
math.log(x,base) returns log x for base. If base omitted, returns log x base e.
e
gin
math.sqrt(x) returns the square root of x.
math.cos(x) returns cosine of x radians.
math.sin(x) returns sine of x radians.
En
IMPORTING MODULES
.in
members of the imported module. The Python Standard Library contains a set of predefined
Standard (built-in) modules.
ng
eri
1. import modulename
Makes the namespace of modulename available, but not part of, the importing
e
module. All imported identifiers used in the importing module must be fully
gin
qualified:
import math
print('factorial of 16 = ', math.factorial(16))
En
Each package in Python is a directory which MUST contain a special file called
__init__.py. This file can be empty, and it indicates that the directory it contains is a Python
package, so it can be imported the same way a module can be imported
.in
2. Put your classes in it.
3. Create a __init__.py file in the directory
ng
The __init__.py file is necessary because with this file, Python will know that this
directory is a Python package directory other than an ordinary directory (or folder – whatever
eri
you want to call it).
Now, we create the two classes for our package. First, create a file
Le
named Mammals.py inside the Animals directory and put the following code in it:
w.
ww
3
class Mammals:
4 def __init__(self):
''' Constructor for this class. '''
# Create some member animals
self.members = ['Tiger', 'Elephant', 'Wild Cat']
def printMembers(self): Visit For More : www.LearnEngineering.in
Visit For More : www.LearnEngineering.in
5
.in
The class has a property named members – which is a list of some mammals we might be
ng
interested in. It also has a method named printMembers which simply prints the list of mammals
of this class!.When you create a Python package, all classes must be capable of being imported,
eri
and won't be executed directly.
e
Next we create another class named Birds. Create a file named Birds.py inside
gin
the Animals directory and put the following code in it:
class Birds:
En
def __init__(self):
''' Constructor for this class. '''
# Create some member animals
arn
This code is similar to the code we presented for the Mammals class.
That's it! That's all there is to it when you create a Python package. For testing, we create
a simple file named test.py in the same directory where the Animals directory is located.
We place the following code in the test.py file:
.in
# Import classes from your brand new package
ng
from Animals import Mammals
eri
from Animals import Birds
e
gin
myMammal = Mammals()
myMammal.printMembers()
En
myBird = Birds()
arn
myBird.printMembers()
Le
w.
ww
.in
OUTPUT:
Enter file name: data1.txt
ng
Number of words:
2
eri
Case 2:
Contents of file:
This programming language is e
gin
Python
Output:
En
5
COPY FILE IN PYTHON
with open("test.txt") as f:
Le
f1.write(line)
OUTPUT:
ww
Case 1:
Contents of file(test.txt):
Hello world
Output(out.text):
Hello world