XI Computer Science Gist-04
XI Computer Science Gist-04
Computer Science
Gist-4 of Lessons covered between 4/11/2023 to 16/02/2024
Working with In-Built String Manipulation Methods
▪ string.capitalize(): Returns a copy of the string with its first character capitalized and all other characters
changed to lowercase
▪ string.title(): Returns a copy of the string with the first alphabet of each word in uppercase
▪ string.isspace(): Returns True if all characters in the string are white space characters (like newline \n, tab
\t or space). Else returns False. Returns False for a null string.
▪ string.isalnum(): Returns True if all characters in the string are alphanumeric i.e. either alphabets or digits
or both. Else returns False.
▪ string.isalpha(): Returns True if all characters in the string are alphabets only. Else returns False
▪ string.isdigit(): Returns True if all characters in the string are digits only. Else returns False
▪ string.islower(): Returns True if all characters in the string are in lowercase. Else returns False. At least one
character should be an alphabet for it to return True.
▪ string.isupper(): Returns True if all characters in the string are in
uppercase. Else returns False. At least one character should be an
alphabet for it to return True.
▪ string.find( sub, start, end ): Returns the lowest index in the string, where the sub-string sub is found
within the slice range between start and end. If start and end are not given, then uses the entire string.
Returns -1 if sub is not found.
▪ string.partition(): Partitions a string with respect to a given sub-string, into 3 parts always, to form a tuple.
In case the sub-string occurs more than once, ONLY the first occurrence is used. The three parts are the
part on the left of the partition, the partition string and the part on the right of the partition string.
▪ string.replace(): Replaces all occurrences of a given string (first string) with another string (second string).
Replaces By ‘i’
‘ro’
▪ index( ): Returns the index of the first occurrence index of a substring in a string. If substring is not
present, it raises an error. It can be used with a string, list, tuple.
▪ startswith( sub, start, end ): Returns True if a string starts with a given character or sub-string within a
range. Else returns False.
▪ endswith( ): Returns True if a string ends with a given character or sub-string within a range. Else returns
False.
Problems:
1. Program to input a sentence and find how many number of words are present in the sentence,
2. Write a program to input a sentence and find how many times the letter ‘a’ or ‘A’ occurs in the string.
7. Input a sentence and print all the words that start with ‘T’ or ‘t’ and also print a total count of all those words.
8. Write a program to input a sentence and capitalize the last letter of every word in a sentence.
9. Write a program to input a sentence and find how many words end with ‘e’ or ‘E’. Also print those words.
10. Write a program to input a sentence and print all the locations of the sub-string ‘th’ in the sentence.
p p p p
LISTS
What is a List?
• A List is a comma separated mutable sequence of ordered values of any data type
• The term mutable means the values in a list can be modified or changed in place without the requirement to
create a new list
• The term ordered values means the order in which you enter the values in a list is the same as the order in
which it is stored in memory or displayed
• The values in a list are separated by commas and put within a pair of square brackets [ ]
• Example of simple lists: L1 = [ 8.5, 2.5, 6.2 ], L2 = [ 1, 0, 1, 1 ], L3 = [ ‘cat’, ‘mat’, ‘bat’ ], L4 = [ 7, 9.3, ‘pi’ ]
• When an element of a list is itself a list, then it is called a nested list
• Example of nested list: L5 = [ 2, 4, [ 7.1, 3.5, 9.2 ], 8 ]
A list can be created in any one of the following ways:
• L=[] print(L) → [ ] #Creates empty or null list
• L=[4] print(L) → [ 4 ] #Creates a single value list
• L = [ 3, 6, 8 ] print(L) → [3, 6, 8] #Creates a list with 3 elements
• L = list ( ) print(L) → [ ] #Creates empty list using list function
• L = list ( [ 3, 5, 8 ] ) print(L) → [3, 5, 8] #Creates a new list from another list
• L = list ( 'python' ) print(L) → ['p', 'y', 't', 'h', 'o', 'n’] #List from string sequence
• L = list ( ( 3, 7, 4 ) ) print(L) → [3, 7, 4] #Creates list from tuple sequence
• L = list ( 12345 ) print(L) → ERROR #Can’t create list from a non-sequence
• L = list ( [ 12345 ] ) print(L) → [12345] #Creates a single value list
• L = list ( { 2:3, 5:6, 3:8 } ) print(L) → [2, 5, 3] #Creates list from dictionary keys
A list can be created in any one of the following ways:
• The value input will be first input as a string by the input() function.
• This string will then be converted to a list using eval() function
• The eval() function will read the string and convert it to a proper list keeping the data types same and as
input by the user
• Hence any type of data can be input using the eval() function, which then converts it to a proper data-
type
Different ways of inputting a list from the user:
• Using eval() function
Remember: If the [ ] brackets are not given during input, a tuple will be formed:
• Using a loop
• First an empty list is to be created { L=list() can also be used for this }
• Next, a for loop can be used to input the values to be stored, from the user
• The value val is then added to the list as a single element
• Note that for a list, the new value is added to the list as a single element LIST as [val]
List index System
• Being a sequence like a string, lists also follow an index system to access an element from the list
• The first element is given an index of 0 and the last element, an index of length-1
• Like a string these also use a negative index system with the last element having negative index -1 and first
element -(length)
• Example: L = [ 6.2, 9.1, 5, 8.2, ‘ab’, 7 ]
Length = total elements = 6
First element +ve index = 0
First element -ve index = -(len) = -6
Last element +ve index = (6-1) = 5
Last element -ve index = -1
Accessing an Element from a List
Once you create a list, the individual elements of a list can
be accessed using a pair of square brackets. The following
examples will make this clear:
You can repeat a list/tuple multiple times using the * operator. Multiplying by 0 gives a null list
2. append( ): Used to add an element at the end of an existing list. No new list is created
3. extend( ): Used to add the content of a list at the end of another list L. The values are added as the elements of
the list L and NOT as a sub-list. No new list created.
This is unlike the append() method, which will add the second list as a sub-list as shown below:
4. index( ): Returns the index of the first matched item (given by user) from the list
In case index given is out of range, Python
shows an error
5. reverse( ): Used to reverse the content of a list
6. insert( ): Used to insert a value at a given index in the list. It has two arguments. The first argument is the index
at which to insert, and the second argument is the value to be inserted. Different possibilities are:
7. remove( ): Used to remove the first occurrence (from left) of a value in the list. The value to remove is to be
given. THE REMOVED VALUE IS NOT RETURNED. If value is not present in the list, then error message given:
9. pop( ): Used to remove a value from the list. THE POPPED VALUE IS RETURNED (unlike the remove() method).
Index of value to be popped is to be given. If no index given, then by default removes the LAST VALUE from
the list. If index is out of range, then error message given.
10. count( ): Counts number of occurrences of a value in a list and returns the count:
11. sum( ): The function finds the sum of values in the list and returns the sum. List must have all numeric values.
12. max( ): The function finds the maximum value in a list and returns the maximum. List must have all values of
the same data type
13. min( ): The function finds the minimum values in a list and returns the minimum. List must have all values of
the same data type
14. The del statement: The del statement can be used to delete:
• A single element from the list
• A slice of elements from the list
• The entire list
Problems on List
1. To input a list and find the average of values in the list.
Normally the append function is used to create a list in the manner shown
2. To input a list and find the frequency of a given element in the list without using the count function.
3. To search a given value from the list without using count function
4. To input a list and find the maximum value from the list without using max function
5. Input a list. Next add the value 10 to every element of the list.
7. Input a list. Next multiply each element at an even index in the list, by 2.
8. Program to create two lists from a given list. The first list will contain values which occur multiple times and
the second list will contain values that occur only once in the main list.
• The value input will be first input as a string by the input() function.
• This string will then be converted to a tuple using eval() function
• Unlike the tuple() functions the eval() function will read the string and convert it to a proper tuple keeping
the data types same and as input by the user
Inputting a Tuple using a Loop
REMEMBER: You CANNOT use the
append( ) method to input elements of a
tuple.
• First an empty tuple is to be created [ T=tuple() can also be used for this ]
• Next, a for loop can be used to input the values to be stored, from the user
• The value val is then added to the tuple as a single element
• Note that for a tuple, the new value is added as a single element TUPLE with a comma as (val,)
Tuple index System
• Tuples also follow an index system to access an element from the tuple
• The first element is given an index of 0 and the last element, an index of length-1
• With the negative index, the last element has a negative index -1 and first element –(length)
Example:
T = ( 6.2, 9.1, 5, 8.2, ‘ab’, 7 )
Length = total elements = 6
First element +ve index = 0
First element -ve index = -(len) = -6
Last element +ve index = (6-1) = 5
Last element -ve index = -1
Accessing an Element of a Tuple
Once you create a tuple, the individual elements of a tuple can be accessed using a pair of square brackets
(NOT ( ) brackets). The following examples will make this clear:
2. index( ): Returns the index of the first matched item (given by user) from the tuple.
3. count( ): Counts number of occurrences of a value in a tuple and returns the count.
4. sum( ): The function finds the sum of the values in the tuple and returns the sum. Note: The tuple must have
all numeric values.
5. max( ): The function finds the maximum value in a tuple and returns the maximum. Tuple must have all values
of the same data type
6. min( ): The function finds the minimum values in a tuple and returns the minimum. Tuple must have all values
of the same data type
7. sorted( ): The function returns a sorted list of the specified iterable object like a tuple. You can specify the
ascending or descending order. Tuple must have all values of the same data type.
Problems on Tuples
1. Program to find the mean of values in a tuple.
2. clear( ): Used to empty the content of a dictionary and make it a null dictionary (address does not change)
3. get( ): Is used to return the value corresponding to a given key. In case the key is not present, you can put an
error message to display. This is unlike the normal way to display a value using a key, where Python shows
error if key is not present.
4. items( ): The method returns all the items in the dictionary as a sequence or iterable object of (key,value)
tuples (in no particular order)
We can use the concept of tuple unpacking to use two loop variables to extract the values from the tuples that
are part of the sequence.
5. keys( ): The method returns all the keys in a dictionary as a sequence of keys. You can extract the keys using a
loop from the iterative object.
6. values( ): The method returns all the values in a dictionary as a sequence. You can extract the values using a
loop from the iterative object.
7. update( ): The method merges the key:value pairs from a new dictionary into the original dictionary. The
process adds or replaces the key:values as required in the original dictionary.
The common elements 'e':5 and 'u':1 in D1 are updated by 'e':8 and 'u':3 in D2. The element 'y':1 which is not
present in D1 is getting added to D1 from D2. The other elements 'a':3, 'i':2 and 'o':2 remain as it is in D1.
8. fromkeys( ): Returns a dictionary with the specified keys and a specified value. Can be used to set a
given/common value for all the keys in a dictionary. The keys are provided as a tuple or list.
Example: The following example counts the vowels separately in a sentence. It uses the dictionary vowCount
for storing each individual count. The same starting count value 0 is assigned to all the keys using the
fromkeys() method.
9. copy( ): Returns a shallow copy of a dictionary.
Remember that in case the value is an immutable data type (int, float, string, tuple), then changes in original
will not affect the corresponding value in the copy. If the value is a mutable data type (list, dictionary), any
changes made in the original will affect the copy also.
10.pop(): You can delete a particular key:value from a dictionary using pop method. The value is returned by
pop(). You can insert an error message also.
11.popitem( ): Remove the last item inserted from the dictionary, and returns it as a tuple
12.setdefault( ): The method returns the value of a key (if the key is in the dictionary). If the key is not present, it
inserts the key with a None value to the dictionary. In this way it is different from the get() method.
13.sorted( ): The function is used to sort a dictionary. You can sort by both keys and values. The function returns
a list with the sorted keys or values.
14.del command: You can delete a particular key:value from a dictionary using del command
15.max() and min(): These functions can be used to get the maximum and the minimum key from a dictionary
Nesting a Dictionary
The value part of the key of a dictionary can be a dictionary itself. The following example illustrates the operation.
The keys of the dictionaries are to be arranged from outside-in up to the innermost key to get the value
corresponding to the inner-most key.
Extracting the keys and values from the dictionary
We can extract the keys and values using the keys() and values() methods and convert them to lists.
Traversing a Dictionary
You can use a for loop to iterate through a dictionary. The for loop will take out the keys from the dictionary one
by one and store them in the loop variable k. So D[k] will give the corresponding value.
Dictionary Problems:
1. Write a program to find the frequency of different alphabets in a string input by the user.
2. Given two dictionaries D1 and D2, write a program to list the overlapping keys of the two dictionaries
P.T.O.
3. Store a set of item and prices in a dictionary
4. Write a program to exchange the key:value pairs and form a new dictionary where the keys of the first
dictionary become the values of the second dictionary, and the values become the keys.
5. Create a LIST, where each element of the list is a DICTIONARY. Each dictionary stores the Name, Class, and
Section of a student. After the entire data is input from the user for a given number of students, the program
displays the data for students of class 12.
6. Find the maximum value stored against a key in the dictionary.
CAUTION: While importing an object using a from statement, DO NOT USE the module name with the
imported object name. It will produce ERROR
randint() function
• randint ( a, b ) : Returns a random integer N in the range [ a , b ] i.e. a <= N <=b
• Probable outputs of the following code can be: random.randint (3, 6)
o 3
o 4
o 5
o 6
randrange() function
• Returns a random number in range, where the number generated is from a start-value and goes up to one
less than stop-value, in steps of the step-value ( start, stop, step )
• The function can take from 1 to 3 arguments.
• All arguments must be integer values
• The different options are shown below:
One argument randrange() function:
• One argument (default starts at 0, stops at 1 less than stop value, step is 1):
random.randrange ( stop )
Probable outputs for: random.randrange (5)
o 0
o 1
o 2
o 3
Two argument randrange() function:
• Two arguments (starts from start, stops at 1 less than stop value, step is 1):
random.randrange ( start, stop )
Probable outputs for: random.randrange (2, 6)
o 2
o 3
o 4
o 5
Three argument randrange() function:
• Three arguments (starts from start, stops at 1 less than stop value, step is step):
random.randrange ( start, stop, step )
Probable outputs for: random.randrange (-10, -35, -5)
o -10
o -15
o -20
o -25
o -30
Functions from the statistics module
• The statistics module in Python provides many statistics related functions
• To use these functions first import the statistics module: import statistics
• The different functions under this module are:
mean( ) function:
• Returns the average value of the sequence of values passed to it:
o x = statistics.mean ( [ 5, 8, 3, 4, 8, 3, 1, 3 ] )
o print ( x ) → 4.375
median( ) function:
• Returns the middle value of the sequence of values passed to it.
• Before calculating the median, Python sorts the data in the list/tuple in ascending order
• Two possibilities are there:
o If number of values n in list is odd, then Median = (n+1)/2 th term
▪ x = statistics.median( [3, 9, 5, 7, 1, 4, 2] ) #sorted list = [1, 2, 3, 4, 5, 7, 9]
▪ print(x) → 4 #Result is 4
o If number of values n in list is even, then Median = [ (n/2)th term + (n/2+1)th term ] /2
▪ y = statistics.median ( [ 5, 8, 3, 4, 8, 3, 1, 3 ] ) #sorted list = [1, 3, 3, 3, 4, 5, 8, 8]
▪ print ( y ) → 3.5 #Result is (3+4)/2
mode( ) function:
• Returns the most often repeated value of sequence of values passed
o z = statistics.mode ( [ 5, 8, 3, 4, 8, 3, 1, 3 ] )
o print ( z ) → 3
• Returns the first most often repeated value of sequence of values passed, in case more than one values have
the highest frequency
o w = statistics.mode ( [ 5, 8, 8, 4, 3, 8, 3, 1, 3 ] )
o print ( w ) → 8 #Here both 8 and 3 have same highest frequency of 3. Hence the first value
from the left with the highest frequency i.e. 8 is returned