Control Flow: Control Structures Conditional Structure
Control Flow: Control Structures Conditional Structure
Control Structures
Conditional Structure
1.Sequential structure(if)
3.Repetition structure/looping/iterative
• while
• For
Unconditional Structure
• Break
• Continue
• Pass
• 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
• 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
• 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
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
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!
Examples
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
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
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'
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
Other Examples
UNIT IV
Lists
• A list is a sequential collection of values, it is a data structure
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>.pop(i) Deletes the ith element of the list and returns its value.
Disadvantage of List
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
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
Case 2:
Enter first number:30
Enter second number:12
GCD is: 6
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
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
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
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']
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
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
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]
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:
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
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
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
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
• dict.copy()
dict1 = {'Name': 'Zara', 'Age': 7};
dict2 = dict1.copy()
print("New Dictionary : %s" (dict2))
O/p
Dictionary : {'Name': 'Zara‘, 'Age': 7}
• fromkeys() Parameters
• 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 ?
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:
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:
output:
Enter the string:welcome
w :*
e : **
l :*
c :*
o :*
m :*