Updated functions and dictionaries script.
authorSantosh G. Vattam <vattam.santosh@gmail.com>
Tue, 04 May 2010 17:21:12 +0530
changeset 119 7dc53e6c8065
parent 118 2f247bcfae8b
child 120 50716c7c4c0c
Updated functions and dictionaries script.
dictionary.org
functions.org
lists.org
--- a/dictionary.org	Tue May 04 16:52:38 2010 +0530
+++ b/dictionary.org	Tue May 04 17:21:12 2010 +0530
@@ -1,114 +1,121 @@
-* Lists
+* Dictionaries
 *** Outline
-***** Lists
-***** Tuples
+***** Dictionaries
+***** Sets
 ***** Arsenal Required
 *** Script
     Welcome friends. 
     
-    In previous tutorial we covered Lists and Tuples and related 
-    functions. In this session we will continue with Python supported
+    In previous tutorial we covered Lists, Tuples and related 
+    functions. In this session we shall continue with Python
     data structures and cover Dictionaries and sets. We have already 
     covered some basics of Dictionaries in session on Statistics. Here
-    we will revisit those concepts and some new ones. 
+    we shall revisit those concepts and some new ones. 
     
-    We give it a name and it should return a corresponding number. 
+    We give it a name and it returns a corresponding number. 
     Dictionaries are just key-value pair. For each 'key' there is
-    corresponding 'value'. In lists we have indexes to access elements,
-    here we have 'key'. 
+    corresponding 'value' associated with it. In lists we use indexes 
+    to access elements, here we use the 'key'. 
     
-    '{}' are used to create Python dictionaries. Lets start by opening 
-    IPython interpreter. Lets create a dictionary say
+    Lets start by opening IPython interpreter. 
+    '{}' are used to create Python dictionaries. Lets create a dictionary say
 
     player = {'Mat': 134,'Inn': 233,
     'Runs': 10823, 'Avg': 52.53}
-    Its dictionary storing statistics of a cricket player.
-    Now to get the 'average' of this player we have to simply write
+    Its a dictionary storing statistics of a cricket player.
+    Here 'Mat', 'Inn' etc are the keys. Now in order to get the 'average' of
+    this player we simply type
     print player['Avg']
     52.53
 
-    To add a new key-value to this dictionary we have to something like
+    To add a new key-value pair to this dictionary we type
     player['Name'] = 'Rahul Dravid'
-    print player    
-    Please remember that Python dictionaries dont maintain the order
-    in which the key-value pair are stored it might change as we add new
-    entries.
+    print player
+    Please note that Python dictionaries don't maintain the order
+    in which the key-value pairs are stored. The order might change
+    as we add new entries.
 
     In dictionaries Duplicate keys are overwritten, that is when we do 
     player['Mat'] = 139
     It wont create a new entry, rather it will simply overwrite previous
-    value with new one. So
+    value with the new one. So
     print player
     will have updated value
 
-    As we covered in one of previous sessions to iterate through lists 
-    we use 'for'. In case of dictionaries we can iterate over them using 
-    'keys' for example
+    As we covered in one of previous sessions 'for' can be used to iterate
+    through lists. The same is possible in case of dictionaries too. We can
+    iterate over them using the 'keys', for example:
     for key in player:
         print key, player[key]
-    We saw how containership works in lists, there we can check if a 
-    value is present in list or not, in case of Dictionaries it works
-    only for keys. so
+    This prints the keys in the dictionary along with their corresponding 
+    values. Notice that the order is not the same as we entered it.
+    
+    We saw how containership works in lists. There we can check if a 
+    value is present in a list or not but in case of Dictionaries we
+    can only check for the containership of the keys. so
     'Inn' in player
     returns True
     'Econ' in Player
     returns False as there is no such 'key'
-    If you try to look or search 'value' it wont work.
-    Dictionaries supports some functions to retrieve keys and values 
-    like
+    If you try to look or search for a 'value' it will not work.
+    Dictionaries support functions to retrieve keys and values 
+    such as
     player.keys()
     returns the list of all 'keys'
     player.values()
     return list of all 'values'    
 
-    Next we shall look at 'sets'. Sets in Python are unordered 
-    collection of unique elements. This data structure comes handy in
+    Now we shall move on to 'sets'. Sets in Python are an unordered 
+    collection of unique elements. This data structure comes in handy in
     situations while removing duplicates from a sequence, and computing 
     standard math operations on sets such as intersection, union, 
     difference, and symmetric difference. 
     
     Lets start by creating a set
     f10 = set([1,2,3,5,8])
-    f10 is set of Fibonacci numbers less then 10
-    lets print value of f10
+    And thats how a set is created.
+    f10 is the set of Fibonacci numbers less than 10
+    lets print the value of f10
     print f10
 
     As we mentioned earlier, these are unordered structure so order of
-    elements are not maintained, and output order is different than 
-    input order. Lets create one more set of all prime numbers less than
-    10
+    elements is not maintained, and output order is different than 
+    input order, just as in dictionaries. Lets create one more set, a set of
+    all prime numbers less than 10
     p10 = set([2,3,5,7])
     print p10.
     
-    To get union of these two sets we use '|' operator
+    To get union of these two sets we use the or '|' operator
     f10 | p10
     
-    For intersection & operator is used:
+    For intersection we use the and '&' operator:
     f10 & p10
     
-    f10 - p10 gives difference between f10 and p10, which is, elements
-    present in f10 but not present in p10.
-    ^ operator gives us symmetric difference that is p10 union f10 minus
-    f10 intersection p10
+    f10 - p10 gives difference between f10 and p10, that is, the set of all elements
+    present in f10 but not in p10.
+    The carat '^' operator gives us the symmetric difference of 2 sets. That is
+    f10 union p10 minus f10 intersection p10
     f10 ^ p10
 
-    To check if a set is super set or subset greater than and lesser than
-    operators can be used
+    To check if a set is the super set or a subset of another set, the greater than 
+    and the lesser than operators are used
     set([2,3]) < p10
     returns True as p10 is superset of given set
     
-    Similar to lists and dictionaries sets also supports containership so
+    Similar to lists and dictionaries, sets also supports containership so
     2 in p10
     returns True as 2 is part of set p10 and 
     4 in p10
     returns False.
     
-    len function works with sets also:
-    len(f10) returns the length, that is 5
-    We can also use 'for' loops to iterate through a set.
+    The 'len' function works with sets also:
+    len(f10) returns the length, which is 5 in this case.
+    We can also use 'for' loops to iterate through a set just as with dictionaries and lists.
     
     With this we come to the end of this tutorial on Dictionaries and 
-    sets. We have covered some of properties of both data types and 
-    functions supported by them. Thank you.
+    sets. We have seen how to initialize dictionaries, how to index them using keys
+    and a few functions supported by dictionaries. We then saw how to initialize
+    sets, perform various set operations and a few functions supported
+    by sets. Hope you have enjoyed it, Thank you.
 
 *** Notes
--- a/functions.org	Tue May 04 16:52:38 2010 +0530
+++ b/functions.org	Tue May 04 17:21:12 2010 +0530
@@ -17,10 +17,10 @@
 *** Script
     Welcome friends. 
 
-    In this tutorial we shall be looking at Functions. We already have
-    looked at the basics of functions in the tutorial on solving
-    equations. We shall first review these basics. Next we shall look
-    at other details like doc-strings, default arguments and keyword
+    In this tutorial we shall be looking at Functions in Python. We already
+    have looked at the basics of functions in the tutorial on solving
+    equations. We shall first review these basics. Then we shall move on to
+    other details such as doc-strings, default arguments and keyword
     arguments. 
 
     Let's write a simple function that prints a Hello message, after
@@ -35,38 +35,38 @@
     defined within an indented block, similar to any other block. Our
     function welcome just has one line in it's definition.  
     
-    We can call our function by passing, as follows -
+    We can call our function, as follows -
         welcome("World")
 
-    (arguments are local to a function)
+    (all arguments are local to a function)
 
     In general functions should be accompanied by documentation on how
-    to use it. Python provides a convenient way of writing within the
-    function itself, using doc strings. They were mentioned in the
+    to use them. Python provides a convenient way of writing this within the
+    function itself, using what are called doc strings. They were mentioned in the
     tutorial on strings. Let's look at how to write them here. 
 
     Let us add a simple doc string to our welcome function. 
 
         def welcome(name):
-	    """ Prints a hello message to a person,
-	        given a name. """
+	    """ Prints a hello message given a name, 
+	        passed as argument. """
 	    print "Hello", name 
     
     Notice that the doc string uses triple quotes. If the doc-string
-    exceeded one line, we could have used new line characters in
-    it. Also, as expected the doc-string is indented as is required
+    exceeds one line, we can use new line characters in it. 
+    Also, as expected the doc-string is indented as is required
     for anything within a block. 
 
     We shall now look at default arguments. 
     [show slide with examples of functions with default arguments]
     The split function has been used in two different ways in the
     previous tutorials - one for splitting on spaces and the other for
-    splitting on commas. 
+    splitting on semicolons. 
 
     The function split is being called with no arguments and one
     argument, respectively. In the first case, white space is being
     used as a default value. Let's now edit our function, welcome, to
-    use default values. (For convenience, we have dropped the doc-string)
+    use default values. (For convenience sake, we have dropped the doc-string)
 
         def welcome(name="World!"):
 	    print "Hello", name 
@@ -75,49 +75,34 @@
     to it. 
         welcome()
 
-    "World!" is used as a default argument, when no name argument is
-    passed to 'welcome'. 
+    As you can see the output is "Hello World!". Here "World!" is used as a
+    default argument, when no name argument is passed to 'welcome'. 
 
     Let's now look at the use of keyword arguments. 
     [show slide with examples of functions with keyword arguments]
     We have already looked at functions and keyword arguments in these
     examples. loc, linewidth, xy, labels are all keywords. 
 
-    Let's now see, how we can call our function 'welcome', using
+    Let's now customize our function so that it displays a custom 
+    greeting message as well. 
+
+    def welcome( greet = 'Hello', name = 'World!'):
+        print greet, name
+
+    Let's now see, how we can call our updated 'welcome' function, using
     keyword arguments. We can call the function in a variety of ways.
         welcome("Hello", "James")
 	welcome("Hi", name="Guido")
 	welcome(name="Guido", greet="Hello")
 
-    Keyword arguments allow us to call functions by passing arguments 
-    in any order and removes need to remember the order of arguments
+    Keyword arguments allow us to call functions by passing arguments
+    in any order and removes the need to remember the order of arguments
     in the function definition. 
- 
-    Let us look at an example function. This will both act as a code
-    reading exercise and tell us an important point about return
-    values in python's functions. Pause the video for a while and
-    ponder about what this piece of code does. 
-    [show slide?]
 
-    def what( n ):
-        i = 1
-	while i * i < n:
-  	    i += 1
-	return i * i == n, i
-
-    The function takes an integer as an argument and returns the
-    boolean True, and the square of the number, if it is a perfect
-    square OR the boolean False and the square root of the next
-    perfect square of the number. 
-    Note that this function is returning two values. Functions in
-    Python are capable of returning any number of values. 
-
-***** arguments are local to a function
-
-    Python follows the philosophy of batteries included. It comes
-    with a rich and versatile standard library with whole gamut of
-    functions. Do check out the standard library, before you sit down
-    to write functions of your own. 
+    
+    In Python there is no restriction on the number of values returned by
+    a function. When a function returns more than one value, the multiple
+    values are packed into one single tuple and that single tuple is returned.
 
     We come to the end of this tutorial on functions. In this tutorial
     we have learnt about functions in a greater detail. We looked at
--- a/lists.org	Tue May 04 16:52:38 2010 +0530
+++ b/lists.org	Tue May 04 17:21:12 2010 +0530
@@ -12,9 +12,8 @@
 	shall look at them in little more detail.
 
 	The list type is a container that holds a number of other 
-	objects, in the given order. The list type implements the sequence
-	protocol, and also allows you to add and remove objects from 
-	the sequence. 
+	objects, in the given order. Lists allow you to add and
+	remove objects from the sequence. 
 	
 	First lets start the interpreter by typing ipython in terminal.
 	We create our first list by typing 
@@ -25,39 +24,44 @@
 	type in them. We can have a list something like:
 	var = [1, 1.2, 'string']
 	print var
-	and with this list we can perform most of list operations.
-	Python lists are very versatile, that is we can change it as we 
-	wish. It supports features like removal, addition, sort, etc. 
 
 	Similar to strings, we can concatenate two lists using '+' 
 	operator
-	so num + var will return a new list with 'var' added in end of
-	'num'
-	We have already covered the append function.
+	so num + var will return a new list with the contents of both 
+	'num' and 'var' one after the other.
+	Let's look at what num contains now
+	print num 
+	As you can see num is unchanged by the '+' operator.
+
+	We have already covered the append function in one of our previous
+	tutorials.
 	To add single object at the end of a list the 'append' 
 	function is used
-	num
+	Let's now append -5 to it.
 	num.append(-5)
-	num
+	The contents of num have been changed now.
+	print num
 	append takes only one argument. And append behaves different 
-	from + operator. While + will return new list with two lists 
-	added if we try similar with append function like:
+	from + operator. While + returns a new list with two lists 
+	added, append will simply add the entire object to the 
+	end of the list:
 	num.append([9, 10, 11])
-	num
-	It changes original list and add the argument as one element
-	and not separate elements.
-	To extend list with new list elements we use 'extend' function
+	print num
+	It adds the entire list as one element and not separate elements.
+	In order to add separate elements we use the 'extend' function
+	Let's reinitialize num
 	num = [1, 4, -6]
 	num.extend([2, 8, 0])
-	num
-	As we can notice extend and append behave differently.
-	To reverse a list 'reverse' function is available. 
-	num
-	This is current content of list
+	print num	
+	
+	Let's now move on to see more functions available 
+	with lists.
+	To reverse a list, we have the 'reverse' function.
+	Please note the order of the elements in num. Let's now do:
 	num.reverse()
 	Now after using reverse function, lets check the value of 'num'
-	num
-	Please note, reverse actually manipulated the list. 
+	print num
+	Please note, the reverse() function actually manipulated the list. 
 	To remove a particular element from the list Python provides
 	the remove() function
 	num.remove(8)
@@ -67,40 +71,49 @@
 	The Slicing and Striding concepts which we covered for Arrays work
 	with lists as well. Lets revisit the concept by looking at some examples
 	a = [1, 2, 3, 4, 5]
-	a[1:3] returns a list with second and third element of 'a'
+	print a[1:3] returns a list with second and third element of 'a'
 	One important feature of list indexing is the negative index. In
 	Lists -1 indicates last element of the list
-	a[-1]
+	print a[-1]
 	similarly -2 will be second last and so forth. Now these 
 	negative indexes can also be used with slicing. If we try
-	a[1:-1]
+	print a[1:-1]
 	we get list which excludes first and last element of a.
 	and if we do not specify the start or the end index value the default 
 	values are taken. The default values being the first element and the 
 	last element.
-	a[:3] will return a list from beginning upto the fourth element of a.
+	print a[:3] will return a list from beginning upto the fourth element of a.
 	We can perform striding as well, by specifying the step size
-	a[1:-1:2]
+	print a[1:-1:2]
 	This gives second, fourth and so on items of a till we reach 
 	last item of list.
-	a[::2] will skip all the even placed elements of a
+	print a[::2] will skip all the even placed elements of a
 	With step sizes, if we specify negative values we get some 
 	interesting results. Lets try
-	a[::-1]
-	It returns reversed 'a'
-	We can check for containership with lists as well.
+	print a[4:1:-1]
+	Here we begin at the 5th element and go upto the 2nd element in the
+	reverse order since step size is -1
+	print a[::-1]
+	This returns a slice with all the elements in 'a' reversed in order.
+	Here the negative step indicates that the start point has to be the 
+	last element and the end point has to be the first element and the order
+	has to be reversed.
+
+	Let's now move on to other functionality
+	We can check for containership of elements within lists as well.
 	Let's look at the contents of num
-	num
+	print num
 	To check if the number 4 is present in the list we type
-	4 in a
+	4 in num
 	True
 	
+	Now let's move onto Tuples.
 	Python provides support for special immutable lists known as
 	'tuple'	To create a tuple instead we use normal brackets '('
 	unlike '[' for lists.
 	t = (1, 2, 3, 4, 5, 6, 7, 8)
-	its elements can also be accessed using indexes
-	t[0] + t[3] + t[-1]
+	its elements can also be accessed using indexes just like lists.
+	print t[0] + t[3] + t[-1]
 	but operation like
 	t[4] = 7 are not allowed
 	These features of tuples have their advantages. To see where 
@@ -119,8 +132,10 @@
 	that Python does called	as tuple packing and unpacking.
 	
 	With this we come to the end of this tutorial on Lists and 
-	tuples. In this tutorial we have learnt some more operations 
-	on lists and tuples. In next session we will cover more on 
-	Python supported data structures. Thank you!
+	tuples. In this tutorial we have learnt about initializing, 
+	various list operations, slicing and striding. We learnt 
+	about tuple initialization, packing and unpacking. In next
+	session we will cover more on Python supported data 
+	structures. Thank you!
 
 *** Notes