[go: up one dir, main page]

0% found this document useful (0 votes)
109 views40 pages

Control Flow: Control Structures Conditional Structure

Control flow structures in Python include conditional and unconditional structures. Conditional structures include sequential, selection, and repetition structures using if, elif, else statements and while and for loops. Unconditional structures break, continue, and pass allow altering normal flow. If statements execute code based on a condition being true. Else blocks provide alternative execution. Nested if statements allow multiple conditions. While and for loops repeat code. Break and continue alter loop execution, and pass acts as a null operation.

Uploaded by

BARATH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
109 views40 pages

Control Flow: Control Structures Conditional Structure

Control flow structures in Python include conditional and unconditional structures. Conditional structures include sequential, selection, and repetition structures using if, elif, else statements and while and for loops. Unconditional structures break, continue, and pass allow altering normal flow. If statements execute code based on a condition being true. Else blocks provide alternative execution. Nested if statements allow multiple conditions. While and for loops repeat code. Break and continue alter loop execution, and pass acts as a null operation.

Uploaded by

BARATH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Control Flow

Control Structures

Conditional Structure
1.Sequential structure(if)

2.Selection structure/branching/decision making


 Simpe if statement
 if … else statement
 if … elif … else statement
 Nested if statement
 ternary if statement

3.Repetition structure/looping/iterative
• while
• For

Unconditional Structure
• Break
• Continue
• Pass

Simple if statement(Conditional execution):

• The simplest form of if statement: if the condition is true; it executes true block statements otherwise
execution resumes in the normal flow.
• Syntax:
ifcondition:
Statement1
Statement 2
• Example:
1) a=5
if(a>10):
print(“a is greater”)
output: doesn’t executed true block because condition failed
2) x=5
if x > 0:
print('x is positive')
output: it prints ‘x is positive’ because condition is true.
if…else statement(Alternativeexecution)

• It is alternative execution, in which there are two possibilitiesand the condition determines
which one gets executed either true block statements or false block statements
• The condition must be true or false, exactly one of the alternatives will be executed.

Syntax:
ifcondition:
Statement1
Statement 2
else:
Statement3
Statement 4

Program
1)
temp=20
if temp<10:
print(“it is bad:”)
else:
print(“it is good:”)
Output: The condition is failed so it executes – false block statements it is good

2) x=int(input(“Enter the x value:”))


if x%2 == 0:
print('x is even')
else:
print('x is odd')
Output: based on x value either it prints odd or even

if … elif …else(Chained conditionals)

• There are more than two possibilities and need more than twobranches.
Syntax
• If condition1:
Statement1
Statement 2
elifcondition2:
Statement3
Statement 4
elsecondition3:
Statement4
Program
1) if (x < y):
print('x is less than y')
elif x > y:
print('x is greater than y')
else:
print ('x and y are equal')

• Each condition is checked in order. If the first is false, the nextis checked, and so on.
• If one of them is true, the corresponding branch executes, andthe statement ends.
• Even if more than one condition is true, only the first truebranch executes

Nested if
• One condition nested within another

Program
if x == y:
print('x and y are equal')
else:
if x < y:
print('x is less than y')
else:
print('x is greater than y')

Explanation:
if the value of x is equal to the value of y then it will display the print statement like x
and y are equal; if not, it will check the value of x is less than y. if the condition is satisfied
then it will print the statement like x is less than y, otherwise it will print x is greater than y.
number = 23
guess = int(input('Enter an integer : '))
ifguess == number: # New block starts here
print('Congratulations, you guessed it.')
print('(but you do not win any prizes!)')
# New block ends here
elifguess < number: # Another block
print('No, it is a little higher than that') # You can do whatever youwant in a block ...
else:
print('No, it is a little lower than that') # you must have guessed >number to reach here
print('Done') # This last statement is always executed, # after the ifstatement is executed.
Ternary If statement: “Success” if condition “Failure”
Short hand if … else statement;
Ex: mark=int (input(“Enter the mark”))
print(“pass” if mark >=50 “fail”)
Output:
Enter the mark 78
pass
Enter the mark 17
fail

Indefinite Loops(while loop)

• While loops are called "indefinite loops"because they keep going until a logicalcondition becomes
False

Loops (repeated steps) have iterationvariables that change each time through aloop. Often these
iteration variables gothrough a sequence of numbers.

Definite Loops
• Run the loop once for each of the items in aset using the Python for construct
• These loops are called "definite loops" becausethey execute an exact number of times
• Definite loops iterate through the members ofa set

A Simple Definite Loop(for loop)


Breaking Out of a Loop
• The break statement ends the current loop andjumps to the statement immediately following
theloop
• It is like a loop test that can happen anywhere in thebody of the loop

while True: >hello there


line = input('> ') hello there
if line == 'done' : >finished
break Finished
print(line) >done
print('Done!') Done!

Example
for letter in 'Python': # First Example
if letter == 'h':
break
print('Current Letter :', letter)

OUTPUT:
Current Letter : P
Current Letter : y
Current Letter : t

# Second Example
var = 10
whilevar> 0:
print (Current variable value :', var)
var = var -1
ifvar == 5:
break
print "Good bye!“

OUTPUT:
Current variable value : 10
Current variable value :9
Current variable value :8
Current variable value :7
Current variable value :6
Good bye!
Finishing an Iteration with continue

 The continue statement ends the currentiteration and jumps to the topof the loop andstarts the
nextiteration
while True:
line = input('> ') >hello there
if line[0] == '#' : hello there
continue ># don't print this
if line == 'done': >print this!
break print this!
print(line) >done
print('Done!') Done!
Example :Continue

for letter in 'Python':


if letter == 'h':
continue
print 'Current Letter :', letter

OUTPUT:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Example
for x in range(7):
if (x == 3 or x==6):
continue
print(x)

Example

var = 10
whilevar> 0:
var = var -1
ifvar == 5:
continue
print('Current variable value :', var)
print("Good bye!")

OUTPUT
Current variable value : 10
Current variable value :9
Current variable value :8
Current variable value :7
Current variable value :6
Current variable value :4
Current variable value :3
Current variable value :2
Current variable value :1
Good bye!

Pass
 The pass statement is a null operation
 Nothing happens when it executes
 It is used when a statement is required syntactically butyou do not want any command or code
to execute.

Example
for letter in 'Python':
if letter == 'h':
pass
print('This is pass block')
print('Current Letter :', letter)
print("Good bye!")

OUTPUT:
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!

Difference between variousiterations

Statement simply when the python interpreterencounters the


Pass means 'do passstatement, it simplycontinues with its
nothing' execution
continue with the resume execution at the topof the loop or goes
Continue
loop to nextiteration
When a break statement isencountered, it
Break Breaks the loop terminatesthe block and gets thecontrol out of
the loop
the exit condition will beevaluated again, and
While Indefinite Loops
executionresumes from the top
the item being iterated over will
For Definite Loop
move to its next element

Program for check whether the number is Prime or not

n=int(input("Enter the number:"))


fori in range(2,n):
ifn%i==0:
print ("Not a Prime number")
break
else:
print ( "Prime Number")
Output:
Enter the number:45
Not Prime number
Enter the number:17
Prime Number
Fruitful function
 Function that returns value is called fruitfulfunctions
 The first example is area, which returns thearea of a circle with the given radius:
def area(radius):
temp = math.pi * radius**2
return temp
 Return statement includes an expression.
 This statement means: “Return immediatelyfrom this function and use the followingexpression
as a return value.”
 Function can written more concisely:
def area(radius):
returnmath.pi * radius**2

 multiple return statements, one in each branch ofa conditional:


defabsolute_value(x):
if x < 0:
return -x
else:
return x
 return statements are in an alternative conditional, onlyone will be executed

Examples

def distance(x1, y1, x2, y2):


dx = x2 - x1
dy = y2 - y1
dsquared = dx**2 + dy**2
result = math.sqrt(dsquared)
return result

Local and Global scope

 Variables in a program may not be accessible atall locations in that program.


 This depends on where you have declared avariable.
 The scope of a variable determines the portion ofthe program where you can access a
particularidentifier.
 There are two basic scopes of variables in Python
– Global variables
– Local variables
TYPES
When it is accessible from all partsof a program(ie. Anywhere!) Variables definedoutside a function
body
- GLOBAL Scope
• name = ‘MaryPoppins’
• print(name)
declaredOUTSIDE of any functions-----Global

When it is accessible ONLY withina function/procedure(: Variablesthat are defined inside a


functionbody ) - LOCAL Scope
def Greeting():
name = 'Mary Poppins'
age = 200
address = 'Far Faraway' # declared inside a function-----Local
Composition
 Call one function from within another. This ability is called composition.
 The center point is stored in the variables xc and yc, and the perimeter point is in xpand yp.
The first step is to find the radius of the circle, which is the distancebetween the two points.
We just wrote a function, distance, that does that:
radius = distance(xc, yc, xp, yp)
 The next step is to find the area of a circle with that radius; we just wrote that, too:
result = area(radius)
 Encapsulating these steps in a function:
defcircle_area(xc, yc, xp, yp):
radius = distance(xc, yc, xp, yp)
result = area(radius)
return result
 The temporary variables radius and result are useful for development anddebugging, but once
the program is working, we can make it more concise bycomposing the function calls:
defcircle_area(xc, yc, xp, yp):
return area(distance(xc, yc, xp, yp))

Lambda Functions or Anonymous Functions

Lambda or anonymous functions are so called because they are not declared as other functions
using the defkeyword. Rather, they are created using the lambda keyword. Lambda functions
are throw-away functions,i.e. they are just needed where they have been created and can be used
anywhere a function is required. Thelambda feature was added to Python due to the demand
from LISP programmers.
Lambda functions contain only a single line. Its syntax can be given as,
lambda arguments : expression

Example:
sum = lambda x,y : x + y
print (“Sum = ”, sum(3,5))

Output
Sum = 8

Documentation Strings
Docstrings (documentation strings) serve the same purpose as that of comments, as they are designed
toexplain code. However, they are more specific and have a proper syntax.
Recursive Functions

A recursive function is defined as a function that calls itself to solve a smaller version of its task until a
finalcall is made which does not require a call to itself. Every recursive solution has two major cases,
which are asfollows:
• base case, in which the problem is simple enough to be solved directly without making any further
calls to the same function.
• recursive case, in which first the problem at hand is divided into simpler sub parts. Recursion
utilized divide and conquer technique of problem solving.

Example:

String

 A string is a sequence of characters. You can access thecharacters one at a time with the
bracket operator
>>>fruit = 'banana'
>>>letter = fruit[1]
 The second statement selects character number 1 from fruitand assigns it to letter
 The expression in brackets is called an index. The indexindicates which character in the
sequence you want (hencethe name).
>>>letter = fruit[1.5]
 TypeError: string indices must be integers, not float

Len:
 len is a built-in function that returns the number of charactersin a string
>>>fruit = 'banana'
>>>len(fruit)
6
 To get the last character, you have to subtract 1 from length
>>>last = fruit[length-1]
>>> print (last)
a

String special operators


Ex: a=Hello b=Python

Traversal with a for loop

prefixes = 'JKLMNOPQ'
suffix = 'ack'
for letter in prefixes:
print(letter + suffix)
The output is:
Jack
Kack
Lack
Mack
Nack
Oack
Pack
Qack

String slices
 A segment of a string is called a slice. Selecting a slice issimilar to selecting a character
>>> s = 'Monty Python'
>>> print s[0:5]
Monty
>>> print s[6:12]
Python
 If you omit the first index (before the colon), the slice starts atthe beginning of the string.
 If you omit the second index, the slice goes to the end of thestring:
>>>fruit = 'banana'
>>>fruit[:3]
'ban'
>>>fruit[3:]
'ana‘
>>>fruit = 'banana'
>>>fruit[3:3]
‘’
 An empty string contains no characters and has length 0, butother than that, it is the same as
any other string.

Program Example
stringvariable[start:end: stride or step]
str = 'programiz
'print('str = ', str)#first character
print('str[0] = ', str[0])#last character
print('str[-1] = ', str[-1])#slicing 2nd to 5th character
print('str[1:5] = ', str[1:5])#slicing 6th to 2nd last character
print('str[5:-2] = ', str[5:-2])
print('String reverse= ', str[ : : -1])

OUTPUT
str = programiz
str[0] = p
str[-1] = z
str[1:5] = rogr
str[5:-2] = am
string reverse = zimargorp

Strings are immutable

 The [] operator on the left side of an assignment, with theintention of changing a character in a
string. For example:
>>> greeting = 'Hello, world!'
>>>greeting[0] = 'J'

 TypeError: 'str' object does not support item assignment

 The “object” in this case is the string and the “item” is thecharacter you tried to assign.

 An object is the same thing as a value, but we will refinethat definition later. An item is
one of the values in asequence.

 The reason for the error is that strings are immutable, whichmeans you can’t change an
existing string. The best you cando is create a new string that is a variation on the original:
>>> greeting = 'Hello, world!'
>>>new_greeting = 'J' + greeting[1:]
>>> print (new_greeting)
Jello, world!

 This example concatenates a new first letteronto a slice of greeting. It has no effect on
theoriginal string
String methods
 A method it takes arguments and returns a value
 For example, the method upper takes a string andreturns a new string with all uppercase letters
>>>word = 'banana'
>>>new_word = word.upper()
>>> print (new_word)
BANANA
 The empty parentheses indicate that this methodtakes no argument.
 A method call is called an invocation
 In this case upper on the word is invoked
Example 1
>>>word = 'banana'
>>>index = word.find('a')
>>> print (index)
1
Example 2
>>>word.find('na', 3)
4
 It can take as a second argument the index whereit should start:
 Third argument the index where it should stop
>>>name = 'bulb'
>>>name.find('b', 1, 2)
-1
>>>name = 'bob'
>>>name.find('b', 1, 2)
-1
This search fails because b does not appear inthe index range from 1 to 2

Built-in String Methods


capitalize() Converts first character to Capital Letter
center() Pads string with specified character
count() returns occurrences of substring in string
endswith() Checks if String Ends with the Specified Suffix
encode() returns encoded string of given string
find() Returns the Highest Index of Substring
format() formats string into nicer output
index() Returns Index of Substring
isalnum() Checks Alphanumeric Character
isalpha() Checks if All Characters are Alphabets
isdecimal() Checks Decimal Characters
isdigit() Checks Digit Characters
isidentifier() Checks for Valid Identifier
islower() Checks if all Alphabets in a String are Lowercase
isnumeric() Checks Numeric Characters
isprintable() Checks Printable Character
isspace() Checks Whitespace Characters
istitle() Checks for Titlecased String
isupper() returns if all characters are uppercase characters
String Modules

Other Examples
UNIT IV
Lists
• A list is a sequential collection of values, it is a data structure

• Each value has a location {an index)


• Indexes range from 0to n-1{where n is the length of the list) and from -1to -n
• Lists are heterogeneous = values can be of any type {strings are homogeneous because their
elements are characters)

List Syntax
• Values are enclosed in [], rnyList = [3, 'a', True]
• One list can contain another
• Empty list = []
• Any type of data can be in the list
• You usually refer to a list by elements, that is with the []. You can refer to a list by its name {as
one whole thing) when passing it as an argument to a function.

List semantics
• Lists are mutab le, that is, eleme nts can be change d
• Individ ua l eleme nts can be change d the same way any variab le can be changed,
with an assignme n t stateme nt
• myList= [19,,'a',4, 7]
• m = 3
• myl_ ist[ m] = 9
• myl_ ist[ m+ l] = 8

List Operations

Method Meaning

<list>.append(x) Add element x to end of list.

Sort (order) the list. A comparison function may be


<list>.sort()
passed as a parameter.

<list>.reverse() Reverse the list.

<list>.index(x) Returns index of first occurrence of x.

<list>.insert(i, x) Insert x into list at index i.

<list>.count(x) Returns the number of occurrences of x in list.

<list>.remove(x) Deletes the first occurrence of x in list.

<list>.pop(i) Deletes the ith element of the list and returns its value.
Disadvantage of List

 Python lists are nice, but...


 They are slow to process
 They use a lot of memory
 For tables, matrices, or volumetric data, youneed lists of lists of lists... which becomesmessy to
program.

Arrays
 multidimensional rectangular data containerall elements have the same type
 compact data layout, compatible withC/Fortran
 efficient operations
 arithmetic
 flexible indexing

Why arrays?
 Arrays are the most “natural” data structurefor many types of scientific data
 Matrices
 Time series
 Images
 Functions sampled on a grid
 Tables of data
List as Array

 Arrays and lists are both used in Python to storedata


 They both can be used to store any data type(real numbers, strings, etc), and they both can
beindexed and iterated
 The main difference between a list and an arrayis the functions that you can perform to
them.
 For example, you can divide an array by 3, andeachnumber in the array will be divided by 3
and the result willbe printed.
Example
importnumpy
x = numpy.array([3, 6, 9, 12])
x/3.0
print(x)
Output:
array([1, 2, 3, 4])
 To divide a list by 3, Python will tell you that it can't bedone, and an error will be thrown.
y = [3, 6, 9, 12]
y/3.0
print(y)
Output:
Syntax error

Similarities between arrays and lists:


 Both are mutable: both can have elementsreassigned in place
 Arrays and lists are indexed and slicedidentically
 The len command works just as well onarrays as anything else
 Arrays and lists both have sort andreverse attributes
 With arrays, the + and * signs do not refer toconcatenation or repetition
 Examples:
>>> ar1 = numpy.array([2,4,6])
>>> ar1+2 # Adding a constant to an array adds
the constant to each term
[4,6,8] # in the array
>>> ar1*2 # Multiplying an array by a constant
multiplies each term in
[4,8,12] # the array by that constant

 Adding two arrays is just like adding two vectors


>>> ar1 = numpy.array([2,4,6]); ar2 = numpy.array([1,2,3])
>>> ar1+ar2
[3,6,9]
 Multiplying two arrays multiplies them term byterm:
>>> ar1*ar2
[2,8,18]
 Same for division:
>>>ar1/ar2
[2,2,2]

 Mutable types (dictionaries, lists, arrays) can haveindividual items reassigned in place, while
immutabletypes (numbers, strings, tuples) cannot.
>>> L = [0,2,3]
>>>L[0] = 1
>>> L
[1,2,3]
>>> s = 'string'
>>>s[3] = 'o'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object does not support item assignment
List Operation:

a) Slice operations ( [ ] )
b) Concatenation ( + )
c) Repetition ( * )
d) Membership ( in , not in)
e) Iteration ( for )
f) Comparison( > , < , = = , ! = )

Matrix Multiplication:

a=[ ]
b=[ ]
mul=[ ]
r=int(input(“Enter the number of rows for a and b matrix”))
c=int(input(“Enter the number of columns for a and b matrix”))
fori in range(r):
a.append([ ])
b.append([ ])
mul.append([ ])
print(“Enter the elements for a matrix”)
fori in range(r):
for j in range(c):
a[i].append(int(input( ))
print(“Enter the elements for b matrix”)
fori in range(r):
for j in range(c):
b[i].append(int(input( ))
print(“Intialization for mul matrix”)
fori in range(r):
for j in range(c):
mul.append(0))
print(“Multiplication of two matrix”)
fori in range(r):
for j in range(c):
for k in range(c):
mul[i][j]+=a[i][k]*b[k][j]

fori in range(r):
for j in range(c):
print(mul[i][j],end=”\t”)
print(“\n”)
Output:
Enter the elements for a matrix
1 2
3 4
Enter the elements for b matrix
2 4
6 8
Resultant Matrix
14 20
30 44

Illustrative Programs

Newton method for Square root


Algorithm:
1. Define a function named newtonSqrt().
2. Initialize approx as 0.5*n and better as 0.5*(approx.+n/approx.)
3. Use a while loop with a condition better!=approx to perform the following,
i. Set approx.=better
ii. Better=0.5*(approx.+n/approx.)
4. Print the value of approx
Program:
defnewtonSqrt(n):
approx = 0.5 * n
better = 0.5 * (approx + n/approx)
while better != approx:
approx = better
better = 0.5 * (approx + n/approx)
returnapprox

print('The square root is:' ,newtonSqrt(81))


OUTPUT:
The square root is:9
Greatest Common Divisor (GCD) using recursion:
defgcd(a,b):
if(b==0):
return a
else:
returngcd(b,a%b)
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
print("GCD is: ", gcd(a,b))
output:
Case 1:
Enter first number:5
Enter second number:15
GCD is: 5

Case 2:
Enter first number:30
Enter second number:12
GCD is: 6

Exponential Using Recursion


def power(base,exp):
if(exp==0):
return1
else:
return(base*power(base,exp-1))
base=int(input("Enter base: "))
exp=int(input("Enter exponential value: "))
print("Result:",power(base,exp))

Output
Case 1:
Enter base: 2
Enter exponential value: 5
Result: 32
Case 2:
Enter base: 5
Enter exponential value: 3
Result: 125
Sum an array of n numbers

size=int(input("enter the number of elements:"))


A=[]
print("Enter the elements:")
for i in range (0, size):
A.append(int(input()))
print("the elements of the list are:",A)
sum=0
for i in range (0, size):
sum=sum+A[i]
print("Sumis",sum)

OUTPUT
Enter the number of elements:5
Enter the elements:2
4
6
8
12
The elements of the list are: (2,4,6,8,12)
Sum is: 32

Note: print("Sum is", sum(A)) #using list function to sum up all the elements in the list
Linear Search
 Search is a process of finding a value in a list of values

Linear Search Algorithm


 Linear search algorithm finds given element in a list ofelements with O(n) time complexity
where n is totalnumber of elements in the list

 Search process starts comparing of search element withthe first element in the list

 If both are matching then results with element foundotherwise search element is compared with
nextelement in the list

 Otherwise, repeat the same with the next element in the listuntil search element is compared
with last element in the list
Example1:

Example2:
Program
size=int(input("enter the number of elements:"))
A=[]
n=int(input("Enter the number of elements"))
A=[]
print("Enter the elements:")
fori in range (0, n):
A.append(int(input()))
print("the elements of the list are:", A)
key= int(input("enter the element to be searched:"))
fori in range (0, n):
if key == A[i]:
print("The element {0} was found at the position{1}" .format(key, i+1))
break
else:
print("The element {} is not found".format(key))

Output 1:
Enter the number of elements:5
Enter the elements:
2
4
65
1
6
('the elements of the list are:', [2, 4, 65, 1, 6])
enter the element to be searched:6
The element 6 was found at the position5

Binary Search

 Binary search is a fast search algorithm with run-timecomplexity of Ο(log n). This search
algorithm works on the principle of divide and conquers
 The data collection should be in the sorted form
 Binary search looks for a particular item by comparingthe middle most item of the collection.
 if a match occurs, then the index of item is returned.
 If the middle item is greater than the item, then the itemis searched in the sub-array to the left
of the middleitem.
 Otherwise, the item is searched for in the sub-array tothe right of the middle item.
 This process continues on the sub-array as well until thesize of the sub array reduces to zero.
 Search the number 31
 Searching is performed in sorted array
 Formula: mid=(low+high)/2

Here it is, (0 + 9)/ 2 = 4 (integer value of 4.5). So,location 4 is the midof the array.
 compare the value stored at location 4, with the value beingsearched, i.e. 31. the value at
location 4 is 27, which is not amatch. the value is greater than 27

 We have a sorted array, so we also know that the target valuemust be in the upper portion of
the array
 Find new mid value (low=mid+1)
 Mid=(5+9)/2=7 (i.e) 35

 The value stored at location 7 is not a match. So, the valuemust be in the lower part from this
location

 Calculate the mid again. This time it is 5.

 Compare the value stored at location 5 with our target value.


 Hence, the searched element is found

Example2
Algorithm:
Step 1: Start
Step 2: Read n elements in the list
Step 3: found=false
Step 4: Set first=0, last=len(item_list)-1
Step 5: Repeat steps while first<=last
Step 6: mid=(first+last)/2
Step 7: Check if the item is in the mid position, return found=True
Step 8: Else if item <item_list[mid], then last=mid-1 else first=mid+1, return found
Step 9: Stop

Program
n=int(input("enter numbers insert:"))
A=[]
print("Enter number:")
for i in range (0, n):
A.append(int(input()))
print("Entered list are: ",A)
print("sorted List: ",A.sort())
element=int(input("enter the element to be searched:"))
start=0
last=len(A)
while start <=last:
mid = (start+last)//2
if A[mid]==element:
print("element:", element, "found at location", mid)
break
elifA[mid] < element:
start = mid + 1
else:
last = mid – 1
else:
print("element is not found")

OUTPUT:
enter numbers insert:4
Enter number:
2
3
1
5
Entered list are: [2, 3, 1, 5]
sorted List: [1, 2, 3, 5]
enter the element to be searched2
element: 2 found at location 1
LIST
 A list is a sequence of values
 The values in a list are called elements orsometimes items. they can be any type
 list contains a string, a float, an integer.

Syntax
 elements in square brackets […]
 [10, 20, 30, 40]
 [a', ‘b', ‘c']

Accessing Values in Lists

To access values in lists, use the square brackets for slicing alongwith the index or indices to obtain
value available at that index
Example
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7 ]
print("list1[0]: ", list1[0])
print("list2[1:5]: ", list2[1:5])

• OUTPUT
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]

Updating Lists
 Update single or multiple elements of lists by left-hand side ofthe assignment operator or
append method
 Example
list = ['physics', 'chemistry', 1997, 2000]
print("Value available at index 2 : ")
print(list[2])
list[2] = 2001
print("New value available at index 2 :")
print(list[2])
OUTPUT
Value available at index 2 : 1997
New value available at index 2 : 2001

Delete List Elements

 To remove a list element, use del statement


Example
list1 = ['physics', 'chemistry', 1997, 2000]
print(list1)
del list1[2]
print("After deleting value at index 2 : ")
print list1)

OUTPUT
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 : ['physics', 'chemistry', 2000]
List operations
 Lists respond to the + and * operators much like strings; they meanconcatenation and
repetition.
 The + operator concatenates lists:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print (c)
[1, 2, 3, 4, 5, 6]
 Similarly, the * operator repeats a list a given number of times:
>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
 The first example repeats [0] four times. The second examplerepeats the list [1, 2, 3] three
times.
List slices
 The slice operator also works on lists:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>>t[1:3]
['b', 'c']
>>>t[:4]
['a', 'b', 'c', 'd']
>>>t[3:]
['d', 'e', 'f']
 If you omit the first index, the slice starts at the beginning. If you omit the second, the
slicegoes to the end. So if you omit both, the slice is a copy of the whole list.
>>>t[:]
['a', 'b', 'c', 'd', 'e', 'f']

 Since lists are mutable, it is often useful to make a copy before performing operations thatfold,
spindle or mutilate lists.

 A slice operator on the left side of an assignment can update multiple elements:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>>t[1:3] = ['x', 'y']
>>> print (t )
['a', 'x', 'y', 'd', 'e', 'f']
>>> l=[1,2,3,4]
>>>l[1:]+l[:1]
[2, 3, 4, 1]
>>> l=[1,2,3,4]
>>>l[2:]+l[:2]
[3, 4, 1, 2]
>>>l[-1:]+l[:-1]
[4, 1, 2, 3]
List methods

 Append():
adds a new element to the end of a list
>>> t = ['a', 'b', 'c']
>>>t.append('d')
>>> print (t)
['a', 'b', 'c', 'd']

 Extend():
extend takes a list as an argument and appends all of theelements
>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>>t1.extend(t2)
>>> print (t1)
['a', 'b', 'c', 'd', 'e']

 Sort():
arranges the elements of the list from low to high:
>>> t = ['d', 'c', 'e', 'b', 'a']
>>>t.sort()
>>> print (t)
['a', 'b', 'c', 'd', 'e']
 Count():
method returns count of how many times obj occurs in list.
aList = [123, 'xyz', 'zara', 'abc', 123]
print("Count for 123 : ", aList.count(123))
print("Count for zara : ", aList.count('zara'))

OUTPUT:
Count for 123 : 2
Count for zara : 1

 Index():
returns index
aList = [123, 'xyz', 'zara', 'abc']
print("Index for xyz : ", aList.index( 'xyz' ))
print("Index for zara : ", aList.index( 'zara' ))

OUTPUT
Index for xyz : 1
Index for zara : 2
 Insert(index,obj)
inserts the given element at the given index
aList = [123, 'xyz', 'zara', 'abc']
aList.insert( 3, 2009)
print("Final List : ", aList)
Final List : [123, 'xyz', 'zara', 2009, 'abc']
 Pop()
removes and returns last object
List = [123, 'xyz', 'zara', 'abc']
print("A List : ", aList.pop())
print("B List : ", aList.pop(2))

OUTPUT
A List :abc
B List :zara
 Remove()
removes the given object from the list.
aList = [123, 'xyz', 'zara', 'abc', 'xyz']
aList.remove('xyz')
print("List : ", aList)
aList.remove('abc')
print("List : ", aList)

OUTPUT
List : [123, 'zara', 'abc', 'xyz']
List : [123, 'zara', 'xyz']

 Reverse()
reverse the given object from the list.
aList = [123, 'xyz', 'zara', 'abc', 'xyz']
aList.reverse()
print("List : ", aList)

OUTPUT
List : ['xyz', 'abc', 'zara', 'xyz', 123]
Built-in functions in listList loop
>>>mylist = [[1,2,3],[4,5,6,7],[8,9,10]]
>>>for x in mylist:
iflen(x)==3:
print x

OUTPUT
[1, 2, 3] [8, 9, 10]

List Mutability
 lists are mutable.
 bracket operator appears on the left side of anassignment, it identifies the element of the listthat
 >>> numbers = [17, 123]
 >>> numbers[1] = 5
 >>> print numbers
 [17, 5]will be assigned

List indices work the same way as string indices:


 Any integer expression can be used as an index.
 If you try to read or write an element that does not exist, youget an IndexError.
 If an index has a negative value, it counts backward from theend of the list.

The in operator also works on lists

>>>cheeses = ['Cheddar', 'Edam', 'Gouda']


>>> 'Edam' in cheeses
True
>>> 'Brie' in cheeses
False
Aliasing
 If a refers to an object and you assign b = a, then bothvariables refer to the same object:
>>> a = [1, 2, 3]
>>> b = a
>>>b is a
True

 The association of a variable with an object is called areference. In this example, there are
two references to thesame object.
 An object with more than one reference has more than onename, so we say that the object is
aliased.
 If the aliased object is mutable, changes made with one aliasaffect the other:
>>>b[0] = 17
>>>print(a)
[17, 2, 3]
 This behavior can be useful, it is error-prone
 It is safer to avoid aliasing when working withmutable objects
 For immutable objects like strings, aliasing is notas much of a problem.
a = 'banana'
b = 'banana'
 It almost never makes a difference whether a andb refer to the same string or not

Cloning lists
original_list = [10, 22, 44, 23, 4]
new_list = list(original_list)
print(original_list)
print(new_list)

O/P:
[10, 22, 44, 23, 4]
[10, 22, 44, 23, 4]

a = [81, 82, 83]


b = a[:]
# make a clone using slice
print(a == b)
b[0] = 5
print(a)
print(b)
O/P:
True
[81, 82, 83]
[5, 82, 83]
List Parameters

 When you pass a list to a function, the function gets a reference tothe list. If the function
modifies a list parameter, the caller sees thechange. For example, delete_head removes the first
element from alist:
defdelete_head(t):
del t[0]
 Here’s how it is used:
>>>letters = ['a', 'b', 'c']
>>>delete_head(letters)
>>> print (letters)
['b', 'c']
List Parameters
 It is important to distinguish between operations that modify listsand operations that create new
lists. For example, the appendmethod modifies a list, but the + operator creates a new list:
>>> t1 = [1, 2]
>>> t2 = t1.append(3)
>>> print t1
[1, 2, 3]
>>> print t2
None
>>> t3 = t1 + [4]
>>> print t3
[1, 2, 3, 4]
• This difference is important when you write functions that aresupposed to modify lists.
List as comprehension:

 To create dynamic initialization of list with n numbers is known as list as comprehension.


Syntax:variablename=[ x for i in sequence [if expression] ]
Example1: A=[x for x in range(1,100) if x%2==0 ] #[2,4,6,…]
Example2: B= [x*3 for x in range(1,10)] #[3,8,27,…]

Tuples
Tuple Assignment
 A tuple is a sequence of values.
 The values can be any type, and they are indexed by integers
 Tuples are immutable
 Example Swap to variables
>>>temp = a
>>> a = b
>>> b = temp
 Tuple assignment
>>>a, b = b, a
 The left side is a tuple of variables; the right side is a tuple of expressions
 Each value is assigned to its respective variable
• >>> a, b = 1, 2, 3
• ValueError: too many values to unpack
 The number of variables on the left and the number of values on the right have to be the same

Tuples as return values


 a function can only return one value
 For example, if you want to divide two integers and compute the quotient andremainder
 it is inefficient to compute x/y and then x%y.
 It is better to compute them both at the same time

Example
 The built-in function divmodtakes two arguments and returns a tuple of two values, the
quotient and remainder
>>> t = divmod(7, 3)
>>> print (t)
(2, 1)
 To store the result as a tuple use
>>>quot, rem = divmod(7, 3)
>>>print(quot)
2
>>>print( rem)
1

 example for a function that returns a tuple


defmin_max(t):
return min(t), max(t)

A=[23,6,60]
a1,a2=min_max(A)
print("min is % and max is %", %(a1,a2))

 max and min are built-in functions that find the largest and smallest elements of a sequence]
 min_max computes both and returns a tuple of two values

all() Return True if all elements of the tuple are true (or if the tuple is empty).
any() Return True if any element of the tuple is true. If the tuple is empty, return False.
enumerate() Return an enumerate object. It contains the index and value of all the items of tuple as pairs.
len() Return the length (the number of items) in the tuple.
max() Return the largest item in the tuple.
min() Return the smallest item in the tuple
sorted() Take elements in the tuple and return a new sorted list (does not sort the tuple itself).
sum() Retrun the sum of all elements in the tuple.
tuple() Convert an iterable (list, string, set, dictionary) to a tuple.

Dictionaries
 A dictionary is like a list
 Dictionary is a mapping between a set of indices (whichare called keys) and a set of values.
 Each key maps to a value. The association of a key anda value is called a key-value pair or
sometimes anitem
 In a list, the indices have to be integers; in a dictionarythey can be (almost) any type
 The function dictcreates a new dictionary with noitems
 dict is the name of a built-in function, avoid using as avariable name
>>> eng2sp = dict()
>>> print (eng2sp)
{}----- empty dictionary

• Ex1:
>>>eng2sp['one'] = 'uno‘
>>> print (eng2sp)
{'one': 'uno'}
• The output format is also an input format

• Ex2:
>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
>>> print (eng2sp)
{'one': 'uno', 'three': 'tres', 'two': 'dos'}
Accessing Values in Dictionary
 To access dictionary elements, use squarebracket
dict = {'Name': ‘python', 'Age': 7, 'Class': 'First'}
print("dict['Name']: ", dict['Name'])
print("dict['Age']: ", dict['Age‘])

Output
dict['Name']: python
dict['Age']: 7

Updating Dictionary
 update a dictionary by adding a new entry or akey-value pair
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print("dict['Age']: ", dict['Age'])
print("dict['School']: ", dict['School'])

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

Delete Dictionary Elements


 removes individual dictionary elements or clearsthe entire contents of a dictionary
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
deldict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
deldict ; # delete entire dictionary
print("dict['Age']: ", dict['Age'])
print("dict['School']: ", dict['School'])

OUTPUT
dict['Age']: Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ",
dict['Age'];
TypeError: 'type' object is unsubscriptable

Built- in Dictionary Functions&Dictionary Methods


• dict.clear()
dict = {'Name': 'Zara', 'Age': 7};
print("Start Len : %d" , len(dict))
dict.clear()
print("End Len : %d" , len(dict))
o/p
Start Len : 2
End Len : 0

• dict.copy()
dict1 = {'Name': 'Zara', 'Age': 7};
dict2 = dict1.copy()
print("New Dictionary : %s" (dict2))
O/p
Dictionary : {'Name': 'Zara‘, 'Age': 7}

• fromkeys() Parameters

seq− list of values which would be used for dictionary keyspreparation.

value− optional, if provided then value would be set to thisvalue


dict.fromkeys(seq[, value])
seq = ('name', 'age', 'sex')
dict = dict.fromkeys(seq)
print("Dictionary : %s" % str(dict))
print("New Dictionary : %s" % str(dict))
• O/p
Dictionary : {'age': None, 'name': None, 'sex': None}
New Dictionary : {'age': 10, 'name': 10, 'sex': 10}

• get()
• returns a value for the given key.
• If key is not available then returns defaultvalue None
dict = {'Name': 'Zabra', 'Age': 7}
print("Value : %s" % dict.get('Age'))
print("Value : %s" % dict.get('Education', "Never"))
• O/p
Value : 7
Value : Never

• has_key()
returns true if a given key is available in thedictionary, otherwise it returns a false
dict = {'Name': 'Zara', 'Age': 7}
print("Value : %s" % dict.has_key('Age'))
print("Value : %s" % dict.has_key('Sex'))
• O/p
Value : True
Value : False
• items()
returns a list of tuple pairs
dict = {'Name': 'Zara', 'Age': 7}
print ( "Value : %s" % dict.items())
• O/p
Value : [('Age', 7), ('Name', 'Zara')]
• dict.keys()
returns a list of all the available keys in thedictionary
dict = {'Name': 'Zara', 'Age': 7}
print("keys : %s" % dict.keys())
• O/p
keys : ['Age', 'Name']

• setdefault()
dict = {'Name': 'Zara', 'Age': 7}
print("Value : %s" % dict.setdefault('Age', None))
print("Value : %s" % dict.setdefault('Sex', None))
• O/p
Value : 7
Value : None

• update()
• adds dictionary dict2's key-values pairs in todict
dict = {'Name': 'Zara', 'Age': 7}
dict2 = {'Sex': 'female' }
dict.update(dict2)
print("Value : %s" % dict)
• O/p
Value : {'Age': 7, 'Name': 'Zara', 'Sex': 'female'}

• values()
returns a list of all the values available in a givendictionary.
dict = {'Name': 'Zara', 'Age': 7}
print("Value : %s" % dict.values())
• O/p
Value : [7, 'Zara']
Program for storing n student details in dictionary and search with roll no ?

n=int(input("Enter the n number of students:"))


stud_info={}
fori in range(n):
roll=int(input("Enter the rollno:"))
name=input("Enter the name:")
stud_info.update({roll:name})
print(stud_info)

roll=int(input("Enter the rollno to be searched"))


if roll in stud_info.keys():
print("Name is:",stud_info[roll])
else:
print("Not found")
Output:
Enter the n number of students:2
Enter the rollno:101
Enter the name:Raja
Enter the rollno:102
Enter the name:kani
{101: 'Raja', 102: 'kani'}
Enter the rollno to be searched102
Name is: kani
Iterative Program:

Insertion Sort:

An element which is to be 'insert'ed in this sorted sub-list, has to find its appropriate place and then it
has to be inserted there. Hence the name, insertion sort.
The array is searched sequentially and unsorted items are moved and inserted into the sorted sub-list
(in the same array). This algorithm is not suitable for large data sets.

Algorithm:
Step 1 − If it is the first element, it is already sorted. ;
Step 2 − Pick next element
Step 3 − Compare with all elements in the sorted sub-list
Step 4 − Shift all the elements in the sorted sub-list that is greater than the
value to be sorted
Step 5 − Insert the value
Step 6 − Repeat until list is sorted

program

A=[24,5,1,67,3]

fori in range(1,len(A)):
current=A[i]
position=i
while position > 0 and A[position-1] > current:
A[position]=A[position-1]
position-=1
A[position]=current

print(A)

Output:
[sort] [Unsorted]
Input: 24 | 5, 1, 67, 3
1st Iteration: 5, 24 | 1, 67, 3 Move/Swap required: 1
2nd Iteration: 1, 5, 24 | 67, 3 Move/Swap required: 2
3rd Iteration: 1, 5, 24, 67 | 3 Move/Swap required: 0
4th Iteration: 1, 3, 5, 24, 67 Move/Swap required:3
Selection Sort
Selection sort makes n-1 number of passes through the array. In the first pass it finds the
smallest element and puts it in first position. The second pass will skip the first element and find the
next smallest item and put it in second position. This repeats until n-1 smallest elements are found and
swapped to their places. The nth element is the last and it is already in place. Before we look at the
implementation of the algorithm, let's do one example.

A=[35,2,6,66,1]

fori in range(len(A)):
min=i
for j in range(i+1,len(A)):
if (A[j]<A[min]):
min=j
A[i],A[min]=A[min],A[i]

print(A)

output:

Input: 24, 5, 1, 67, 3


1st Iteration: 1, 5, 24, 67, 3 initial min position=0, target min=2 swap A[0] and A[2]
2nd Iteration: 1, 3, 24, 67, 5 initial min position=1, target min=4  swap A[1] and A[4]
3rd Iteration: 1, 3, 5, 67, 24 initial min position=2, target min=4  swap A[2] and A[4]
4th iteration: 1, 3, 5, 24, 67 initial min position=3, target min=4  swap A[3] and A[4]

Merge sort:

The first algorithm we will study is the merge sort. Merge sort is a recursive algorithm that
continually splits a list in half. If the list is empty or has one item, it is sorted by definition (the base
case). If the list has more than one item, we split the list and recursively invoke a merge sort on both
halves. Once the two halves are sorted, the fundamental operation, called a merge, is performed.
Merging is the process of taking two smaller sorted lists and combining them together into a single,
sorted, new list.

Program

def merge(left,right):
result=[]
i,j=0,0
whilelen(result)<len(left)+len(right):
if left[i]<right[j]:
result.append(left[i])
i+=1
else:
result.append(right[j])
j+=1
ifi==len(left) or j==len(right):
result.extend(left[i:] or right[j:])
break
return result
defmergesort(list):
iflen(list)<2:
return list
mid=len(list)//2
left=mergesort(list[:mid])
right=mergesort(list[mid:])
return merge(left,right)

l=[35,36,78,88,2,6,1,15,8,3,89]

r=mergesort(l)

print(r)

Output:
Histogram:

Based on the character repetition in the given string; it prints the histogram – number occurrences of
character is displayed with (* symbol).

Program:

indata=input("Enter the string:")


d={}
fori in indata:
ifi not in d.keys():
d[i]=1
else:
d[i]=d[i]+1

for key, val in d.items():


print(key,"\t:","*"*val)

output:
Enter the string:welcome
w :*
e : **
l :*
c :*
o :*
m :*

You might also like