631 \end{frame} |
631 \end{frame} |
632 |
632 |
633 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
633 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
634 % TIME: 20 m, running 80m |
634 % TIME: 20 m, running 80m |
635 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
635 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
636 |
|
637 \begin{frame} |
|
638 \frametitle{Problem set 1} |
|
639 \begin{itemize} |
|
640 \item All the problems can be\\ |
|
641 solved using \kwrd{if} and \kwrd{while} |
|
642 \end{itemize} |
|
643 \end{frame} |
|
644 |
|
645 \begin{frame}{Problem 1.1} |
|
646 Write a program that displays all three digit numbers that are equal to the sum of the cubes of their digits. That is, print numbers $abc$ that have the property $abc = a^3 + b^3 + c^3$\\ |
|
647 These are called $Armstrong$ numbers. |
|
648 \end{frame} |
|
649 |
|
650 \begin{frame}{Problem 1.2 - Collatz sequence} |
|
651 \begin{enumerate} |
|
652 \item Start with an arbitrary (positive) integer. |
|
653 \item If the number is even, divide by 2; if the number is odd multiply by 3 and add 1. |
|
654 \item Repeat the procedure with the new number. |
|
655 \item It appears that for all starting values there is a cycle of 4, 2, 1 at which the procedure loops. |
|
656 \end{enumerate} |
|
657 Write a program that accepts the starting value and prints out the Collatz sequence. |
|
658 |
|
659 \end{frame} |
|
660 |
|
661 \begin{frame}{Problem 1.3 - Kaprekar's constant} |
|
662 \begin{enumerate} |
|
663 \item Take a four digit number--with at least two digits different. |
|
664 \item Arrange the digits in ascending and descending order, giving A and D respectively. |
|
665 \item Leave leading zeros in A! |
|
666 \item Subtract A from D. |
|
667 \item With the result, repeat from step 2. |
|
668 \end{enumerate} |
|
669 Write a program to accept a 4-digit number and display the progression to Kaprekar's constant. |
|
670 \end{frame} |
|
671 |
|
672 \begin{frame}[fragile]{Problem 1.4} |
|
673 Write a program that prints the following pyramid on the screen. |
|
674 \begin{lstlisting} |
|
675 1 |
|
676 2 2 |
|
677 3 3 3 |
|
678 4 4 4 4 |
|
679 \end{lstlisting} |
|
680 The number of lines must be obtained from the user as input.\\ |
|
681 \pause |
|
682 When can your code fail? |
|
683 \only<2->{\inctime{25}} |
|
684 \end{frame} |
|
685 |
|
686 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
687 % TIME: 25 m, running 105m |
|
688 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
689 |
|
690 \subsection{Functions} |
|
691 \begin{frame}[fragile] |
|
692 \frametitle{Functions: examples} |
|
693 \begin{lstlisting} |
|
694 def signum( r ): |
|
695 """returns 0 if r is zero |
|
696 -1 if r is negative |
|
697 +1 if r is positive""" |
|
698 if r < 0: |
|
699 return -1 |
|
700 elif r > 0: |
|
701 return 1 |
|
702 else: |
|
703 return 0 |
|
704 \end{lstlisting} |
|
705 \end{frame} |
|
706 |
|
707 \begin{frame}[fragile] |
|
708 \frametitle{Functions: examples} |
|
709 \begin{lstlisting} |
|
710 def pad( n, size ): |
|
711 """pads integer n with spaces |
|
712 into a string of length size |
|
713 """ |
|
714 SPACE = ' ' |
|
715 s = str( n ) |
|
716 padSize = size - len( s ) |
|
717 return padSize * SPACE + s |
|
718 \end{lstlisting} |
|
719 \pause |
|
720 What about \%3d? |
|
721 \end{frame} |
|
722 |
|
723 \begin{frame}[fragile] |
|
724 {What does this function do?} |
|
725 \begin{lstlisting} |
|
726 def what( n ): |
|
727 if n < 0: n = -n |
|
728 while n > 0: |
|
729 if n % 2 == 1: |
|
730 return False |
|
731 n /= 10 |
|
732 return True |
|
733 \end{lstlisting} |
|
734 \end{frame} |
|
735 |
|
736 \begin{frame}[fragile] |
|
737 {What does this function do?} |
|
738 \begin{lstlisting} |
|
739 def what( n ): |
|
740 i = 1 |
|
741 while i * i < n: |
|
742 i += 1 |
|
743 return i * i == n, i |
|
744 \end{lstlisting} |
|
745 \end{frame} |
|
746 |
|
747 \begin{frame}[fragile] |
|
748 {What does this function do?} |
|
749 \begin{lstlisting} |
|
750 def what( n, x ): |
|
751 z = 1.0 |
|
752 if n < 0: |
|
753 x = 1.0 / x |
|
754 n = -n |
|
755 while n > 0: |
|
756 if n % 2 == 1: |
|
757 z *= x |
|
758 n /= 2 |
|
759 x *= x |
|
760 return z |
|
761 \end{lstlisting} |
|
762 \end{frame} |
|
763 |
|
764 \begin{frame} |
|
765 {Before writing a function} |
|
766 \begin{itemize} |
|
767 \item Builtin functions for various and sundry |
|
768 \item \typ{abs, any, all, len, max, min} |
|
769 \item \typ{pow, range, sum, type} |
|
770 \item Refer here: |
|
771 \url{http://docs.python.org/library/functions.html} |
|
772 \end{itemize} |
|
773 \inctime{15} |
|
774 \end{frame} |
|
775 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
776 % TIME: 15 m, running 120m |
|
777 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
778 |
|
779 \begin{frame}{Problem set 2} |
|
780 The focus is on writing functions and calling them. |
|
781 \end{frame} |
|
782 |
|
783 \begin{frame}{Problem 2.1} |
|
784 Write a function to return the gcd of two numbers. |
|
785 \end{frame} |
|
786 |
|
787 \begin{frame}{Problem 2.2} |
|
788 A pythagorean triad $(a,b,c)$ has the property $a^2 + b^2 = c^2$.\\By primitive we mean triads that do not `depend' on others. For example, (4,3,5) is a variant of (3,4,5) and hence is not primitive. And (10,24,26) is easily derived from (5,12,13) and should not be displayed by our program. \\ |
|
789 Write a program to print primitive pythagorean triads. The program should generate all triads with a, b values in the range 0---100 |
|
790 \end{frame} |
|
791 |
|
792 \begin{frame}{Problem 2.3} |
|
793 Write a program that generates a list of all four digit numbers that have all their digits even and are perfect squares.\\For example, the output should include 6400 but not 8100 (one digit is odd) or 4248 (not a perfect square). |
|
794 \end{frame} |
|
795 |
|
796 \begin{frame}{Problem 2.4} |
|
797 The aliquot of a number is defined as: the sum of the \emph{proper} divisors of the number. For example, the aliquot(12) = 1 + 2 + 3 + 4 + 6 = 16.\\ |
|
798 Write a function that returns the aliquot number of a given number. |
|
799 \end{frame} |
|
800 |
|
801 \begin{frame}{Problem 2.5} |
|
802 A pair of numbers (a, b) is said to be \alert{amicable} if the aliquot number of a is b and the aliquot number of b is a.\\ |
|
803 Example: \texttt{220, 284}\\ |
|
804 Write a program that prints all five digit amicable pairs. |
|
805 \inctime{30} |
|
806 \end{frame} |
|
807 |
|
808 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
809 % TIME: 30 m, running 150m |
|
810 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
811 |
|
812 \subsection{Lists} |
|
813 |
|
814 \begin{frame}[fragile] |
|
815 \frametitle{List creation and indexing} |
|
816 \begin{lstlisting} |
|
817 >>> a = [] # An empty list. |
|
818 >>> a = [1, 2, 3, 4] # More useful. |
|
819 >>> len(a) |
|
820 4 |
|
821 >>> a[0] + a[1] + a[2] + a[-1] |
|
822 10 |
|
823 \end{lstlisting} |
|
824 \begin{itemize} |
|
825 \item Indices start with ? |
|
826 \item Negative indices indicate ? |
|
827 \end{itemize} |
|
828 \end{frame} |
|
829 |
|
830 \begin{frame}[fragile] |
|
831 \frametitle{List: slices} |
|
832 \begin{itemize} |
|
833 \item Slicing is a basic operation |
|
834 \item \typ{list[initial:final:step]} |
|
835 \item The step is optional |
|
836 \end{itemize} |
|
837 \begin{lstlisting} |
|
838 >>> a[1:3] # A slice. |
|
839 [2, 3] |
|
840 >>> a[1:-1] |
|
841 [2, 3, 4] |
|
842 >>> a[1:] == a[1:-1] |
|
843 False |
|
844 \end{lstlisting} |
|
845 Explain last result |
|
846 \end{frame} |
|
847 |
|
848 \begin{frame}[fragile] |
|
849 \frametitle{List: more slices} |
|
850 \begin{lstlisting} |
|
851 >>> a[0:-1:2] # Notice the step! |
|
852 [1, 3] |
|
853 >>> a[::2] |
|
854 [1, 3] |
|
855 >>> a[-1::-1] |
|
856 \end{lstlisting} |
|
857 What do you think the last one will do? |
|
858 \emphbar{Note: Strings also use same indexing and slicing.} |
|
859 \end{frame} |
|
860 |
|
861 \begin{frame}[fragile] |
|
862 \frametitle{List: examples} |
|
863 \begin{lstlisting} |
|
864 >>> a = [1, 2, 3, 4] |
|
865 >>> a[:2] |
|
866 [1, 3] |
|
867 >>> a[0:-1:2] |
|
868 [1, 3] |
|
869 \end{lstlisting} |
|
870 \pause |
|
871 \alert{Lists are mutable (unlike strings)} |
|
872 \begin{lstlisting} |
|
873 >>> a[1] = 20 |
|
874 >>> a |
|
875 [1, 20, 3, 4] |
|
876 \end{lstlisting} |
|
877 \end{frame} |
|
878 |
|
879 \begin{frame}[fragile] |
|
880 \frametitle{Lists are mutable and heterogenous} |
|
881 \begin{lstlisting} |
|
882 >>> a = ['spam', 'eggs', 100, 1234] |
|
883 >>> a[2] = a[2] + 23 |
|
884 >>> a |
|
885 ['spam', 'eggs', 123, 1234] |
|
886 >>> a[0:2] = [1, 12] # Replace items |
|
887 >>> a |
|
888 [1, 12, 123, 1234] |
|
889 >>> a[0:2] = [] # Remove items |
|
890 >>> a.append( 12345 ) |
|
891 >>> a |
|
892 [123, 1234, 12345] |
|
893 \end{lstlisting} |
|
894 \end{frame} |
|
895 |
|
896 \begin{frame}[fragile] |
|
897 \frametitle{List methods} |
|
898 \begin{lstlisting} |
|
899 >>> a = ['spam', 'eggs', 1, 12] |
|
900 >>> a.reverse() # in situ |
|
901 >>> a |
|
902 [12, 1, 'eggs', 'spam'] |
|
903 >>> a.append(['x', 1]) |
|
904 >>> a |
|
905 [12, 1, 'eggs', 'spam', ['x', 1]] |
|
906 >>> a.extend([1,2]) # Extend the list. |
|
907 >>> a.remove( 'spam' ) |
|
908 >>> a |
|
909 [12, 1, 'eggs', ['x', 1], 1, 2] |
|
910 \end{lstlisting} |
|
911 \end{frame} |
|
912 |
|
913 \begin{frame}[fragile] |
|
914 \frametitle{List containership} |
|
915 \begin{lstlisting} |
|
916 >>> a = ['cat', 'dog', 'rat', 'croc'] |
|
917 >>> 'dog' in a |
|
918 True |
|
919 >>> 'snake' in a |
|
920 False |
|
921 >>> 'snake' not in a |
|
922 True |
|
923 >>> 'ell' in 'hello world' |
|
924 True |
|
925 \end{lstlisting} |
|
926 \end{frame} |
|
927 |
|
928 \begin{frame}[fragile] |
|
929 \frametitle{Tuples: immutable} |
|
930 \begin{lstlisting} |
|
931 >>> t = (0, 1, 2) |
|
932 >>> print t[0], t[1], t[2], t[-1] |
|
933 0 1 2 2 |
|
934 >>> t[0] = 1 |
|
935 Traceback (most recent call last): |
|
936 File "<stdin>", line 1, in ? |
|
937 TypeError: object does not support item |
|
938 assignment |
|
939 \end{lstlisting} |
|
940 \begin{itemize} |
|
941 \item Multiple return values are actually a tuple. |
|
942 \item Exchange is tuple (un)packing |
|
943 \end{itemize} |
|
944 |
|
945 \end{frame} |
|
946 |
|
947 \begin{frame}[fragile] |
|
948 \frametitle{\typ{range()} function} |
|
949 \begin{lstlisting} |
|
950 >>> range(7) |
|
951 [0, 1, 2, 3, 4, 5, 6] |
|
952 >>> range( 3, 9) |
|
953 [3, 4, 5, 6, 7, 8] |
|
954 >>> range( 4, 17, 3) |
|
955 [4, 7, 10, 13, 16] |
|
956 >>> range( 5, 1, -1) |
|
957 [5, 4, 3, 2] |
|
958 >>> range( 8, 12, -1) |
|
959 [] |
|
960 \end{lstlisting} |
|
961 \end{frame} |
|
962 |
|
963 \begin{frame}[fragile] |
|
964 \frametitle{\typ{for\ldots range(\ldots)} idiom} |
|
965 \begin{lstlisting} |
|
966 In [83]: for i in range(5): |
|
967 ....: print i, i * i |
|
968 ....: |
|
969 ....: |
|
970 0 0 |
|
971 1 1 |
|
972 2 4 |
|
973 3 9 |
|
974 4 16 |
|
975 \end{lstlisting} |
|
976 \end{frame} |
|
977 |
|
978 \begin{frame}[fragile] |
|
979 \frametitle{\typ{for}: the list companion} |
|
980 |
|
981 \begin{lstlisting} |
|
982 In [84]: a = ['a', 'b', 'c'] |
|
983 In [85]: for x in a: |
|
984 ....: print x, chr( ord(x) + 10 ) |
|
985 ....: |
|
986 a k |
|
987 b l |
|
988 c m |
|
989 \end{lstlisting} |
|
990 Iterating over the list and not the index + reference\\ |
|
991 what if you want the index? |
|
992 \end{frame} |
|
993 |
|
994 \begin{frame}[fragile] |
|
995 \frametitle{\typ{for}: the list companion} |
|
996 \begin{lstlisting} |
|
997 In [89]: for p, ch in enumerate( a ): |
|
998 ....: print p, ch |
|
999 ....: |
|
1000 ....: |
|
1001 0 a |
|
1002 1 b |
|
1003 2 c |
|
1004 \end{lstlisting} |
|
1005 Try: \typ{print enumerate(a)} |
|
1006 \inctime{20} |
|
1007 \end{frame} |
|
1008 |
|
1009 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
1010 % TIME: 20 m, running 170m |
|
1011 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
1012 |
|
1013 \begin{frame} |
|
1014 {Problem set 3} |
|
1015 As you can guess, idea is to use \kwrd{for}! |
|
1016 \end{frame} |
|
1017 |
|
1018 \begin{frame}{Problem 3.1} |
|
1019 Which of the earlier problems is simpler when we use \kwrd{for} instead of \kwrd{while}? |
|
1020 \end{frame} |
|
1021 |
|
1022 \begin{frame}{Problem 3.2} |
|
1023 Given an empty chessboard and one Bishop placed in any square, say (r, c), generate the list of all squares the Bishop could move to. |
|
1024 \end{frame} |
|
1025 |
|
1026 \begin{frame}[fragile] |
|
1027 \frametitle{Problem 3.3} |
|
1028 |
|
1029 Given two real numbers \typ{a, b}, and an integer \typ{N}, write a |
|
1030 function named \typ{linspace( a, b, N)} that returns an ordered list |
|
1031 of \typ{N} points starting with \typ{a} and ending in \typ{b} and |
|
1032 equally spaced.\\ |
|
1033 |
|
1034 For example, \typ{linspace(0, 5, 11)}, should return, \\ |
|
1035 \begin{lstlisting} |
|
1036 [ 0.0 , 0.5, 1.0 , 1.5, 2.0 , 2.5, |
|
1037 3.0 , 3.5, 4.0 , 4.5, 5.0 ] |
|
1038 \end{lstlisting} |
|
1039 \end{frame} |
|
1040 |
|
1041 \begin{frame}[fragile] |
|
1042 \frametitle{Problem 3.4a (optional)} |
|
1043 |
|
1044 Use the \typ{linspace} function and generate a list of N tuples of the form\\ |
|
1045 \typ{[($x_1$,f($x_1$)),($x_2$,f($x_2$)),\ldots,($x_N$,f($x_N$))]}\\for the following functions,\begin{itemize} |
|
1046 \item \typ{f(x) = sin(x)} |
|
1047 \item \typ{f(x) = sin(x) + sin(10*x)}. |
|
1048 \end{itemize} |
|
1049 \end{frame} |
|
1050 |
|
1051 \begin{frame}[fragile] |
|
1052 \frametitle{Problem 3.4b (optional)} |
|
1053 |
|
1054 Using the tuples generated earlier, determine the intervals where the roots of the functions lie. |
|
1055 |
|
1056 \inctime{15} |
|
1057 \end{frame} |
|
1058 |
|
1059 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
1060 % TIME: 15 m, running 185m |
|
1061 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
1062 |
|
1063 \subsection{IO} |
|
1064 |
|
1065 \begin{frame}[fragile] |
|
1066 \frametitle{Simple tokenizing and parsing} |
|
1067 \begin{lstlisting} |
|
1068 s = """The quick brown fox jumped |
|
1069 over the lazy dog""" |
|
1070 for word in s.split(): |
|
1071 print word.capitalize() |
|
1072 \end{lstlisting} |
|
1073 \end{frame} |
|
1074 |
|
1075 \begin{frame}[fragile] |
|
1076 \frametitle{Problem 4.1} |
|
1077 Given a string like, ``1, 3-7, 12, 15, 18-21'', produce the list \\ |
|
1078 \begin{lstlisting} |
|
1079 [1,3,4,5,6,7,12,15,18,19,20,21] |
|
1080 \end{lstlisting} |
|
1081 \end{frame} |
|
1082 |
|
1083 \begin{frame}[fragile] |
|
1084 \frametitle{File handling} |
|
1085 \begin{lstlisting} |
|
1086 >>> f = open('/path/to/file_name') |
|
1087 >>> data = f.read() # Read entire file. |
|
1088 >>> line = f.readline() # Read one line. |
|
1089 >>> f.close() # close the file. |
|
1090 \end{lstlisting} |
|
1091 Writing files |
|
1092 \begin{lstlisting} |
|
1093 >>> f = open('/path/to/file_name', 'w') |
|
1094 >>> f.write('hello world\n') |
|
1095 >>> f.close() |
|
1096 \end{lstlisting} |
|
1097 \begin{itemize} |
|
1098 \item Everything read or written is a string |
|
1099 \end{itemize} |
|
1100 \emphbar{Try \typ{file?} for more help} |
|
1101 \end{frame} |
|
1102 |
|
1103 \begin{frame}[fragile] |
|
1104 \frametitle{File and \kwrd{for}} |
|
1105 \begin{lstlisting} |
|
1106 >>> f = open('/path/to/file_name') |
|
1107 >>> for line in f: |
|
1108 ... print line |
|
1109 ... |
|
1110 \end{lstlisting} |
|
1111 \end{frame} |
|
1112 |
|
1113 \begin{frame}{Problem 4.2} |
|
1114 The given file has lakhs of records in the form:\\ |
|
1115 \typ{RGN;ID;NAME;MARK1;\ldots;MARK5;TOTAL;PFW}\\ |
|
1116 Some entries may be empty. Read the data from this file and print the |
|
1117 name of the student with the maximum total marks. |
|
1118 \end{frame} |
|
1119 |
|
1120 \begin{frame}{Problem 4.3} |
|
1121 For the same data file compute the average marks in different |
|
1122 subjects, the student with the maximum mark in each subject and also |
|
1123 the standard deviation of the marks. Do this efficiently. |
|
1124 |
|
1125 \inctime{20} |
|
1126 \end{frame} |
|
1127 |
|
1128 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
1129 % TIME: 20 m, running 205m |
|
1130 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
1131 |
|
1132 \subsection{Modules} |
|
1133 |
|
1134 \begin{frame}[fragile] |
|
1135 {Modules} |
|
1136 \begin{lstlisting} |
|
1137 >>> sqrt(2) |
|
1138 Traceback (most recent call last): |
|
1139 File "<stdin>", line 1, in <module> |
|
1140 NameError: name 'sqrt' is not defined |
|
1141 >>> import math |
|
1142 >>> math.sqrt(2) |
|
1143 1.4142135623730951 |
|
1144 \end{lstlisting} |
|
1145 \end{frame} |
|
1146 |
|
1147 \begin{frame}[fragile] |
|
1148 {Modules} |
|
1149 \begin{itemize} |
|
1150 \item The \kwrd{import} keyword ``loads'' a module |
|
1151 \item One can also use: |
|
1152 \begin{lstlisting} |
|
1153 >>> from math import sqrt |
|
1154 >>> from math import * |
|
1155 \end{lstlisting} |
|
1156 \item What is the difference? |
|
1157 \item \alert{Use the later only in interactive mode} |
|
1158 \end{itemize} |
|
1159 \emphbar{Package hierarchies} |
|
1160 \begin{lstlisting} |
|
1161 >>> from os.path import exists |
|
1162 \end{lstlisting} |
|
1163 \end{frame} |
|
1164 |
|
1165 \begin{frame} |
|
1166 \frametitle{Modules: Standard library} |
|
1167 \begin{itemize} |
|
1168 \item Very powerful, ``Batteries included'' |
|
1169 \item Some standard modules: |
|
1170 \begin{itemize} |
|
1171 \item Math: \typ{math}, \typ{random} |
|
1172 \item Internet access: \typ{urllib2}, \typ{smtplib} |
|
1173 \item System, Command line arguments: \typ{sys} |
|
1174 \item Operating system interface: \typ{os} |
|
1175 \item Regular expressions: \typ{re} |
|
1176 \item Compression: \typ{gzip}, \typ{zipfile}, and \typ{tarfile} |
|
1177 \item And a whole lot more! |
|
1178 \end{itemize} |
|
1179 \item Check out the Python Library reference: |
|
1180 \url{http://docs.python.org/library/} |
|
1181 \end{itemize} |
|
1182 \end{frame} |
|
1183 |
|
1184 \begin{frame}[fragile] |
|
1185 {Modules of special interest} |
|
1186 \begin{description}[matplotlibfor2d] |
|
1187 |
|
1188 \item[\typ{numpy}] Efficient, powerful numeric arrays |
|
1189 |
|
1190 \item[\typ{matplotlib}] Easy, interactive, 2D plotting |
|
1191 |
|
1192 \item[\typ{scipy}] statistics, optimization, integration, linear |
|
1193 algebra, Fourier transforms, signal and image processing, |
|
1194 genetic algorithms, ODE solvers, special functions, and more |
|
1195 |
|
1196 \item[Mayavi] Easy, interactive, 3D plotting |
|
1197 |
|
1198 \end{description} |
|
1199 \end{frame} |
|
1200 |
|
1201 \begin{frame}[fragile] |
|
1202 {Creating your own modules} |
|
1203 \begin{itemize} |
|
1204 \item Define variables, functions and classes in a file with a |
|
1205 \typ{.py} extension |
|
1206 \item This file becomes a module! |
|
1207 \item Accessible when in the current directory |
|
1208 \item Use \typ{cd} in IPython to change directory |
|
1209 |
|
1210 \item Naming your module |
|
1211 \end{itemize} |
|
1212 \end{frame} |
|
1213 |
|
1214 \begin{frame}[fragile] |
|
1215 \frametitle{Modules: example} |
|
1216 \begin{lstlisting} |
|
1217 # --- arith.py --- |
|
1218 def gcd(a, b): |
|
1219 if a%b == 0: return b |
|
1220 return gcd(b, a%b) |
|
1221 def lcm(a, b): |
|
1222 return a*b/gcd(a, b) |
|
1223 # ------------------ |
|
1224 >>> import arith |
|
1225 >>> arith.gcd(26, 65) |
|
1226 13 |
|
1227 >>> arith.lcm(26, 65) |
|
1228 130 |
|
1229 \end{lstlisting} |
|
1230 \end{frame} |
|
1231 |
|
1232 \begin{frame}[fragile] |
|
1233 \frametitle{Problem 5.1} |
|
1234 |
|
1235 Put all the functions you have written so far as part of the problems |
|
1236 into one module called \typ{iitb.py} and use this module from IPython. |
|
1237 |
|
1238 \inctime{20} |
|
1239 \end{frame} |
|
1240 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
1241 % TIME: 20 m, running 225m |
|
1242 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
1243 |
|
1244 \begin{frame} |
|
1245 \frametitle{Did we meet the goal?} |
|
1246 \tableofcontents |
|
1247 % You might wish to add the option [pausesections] |
|
1248 \end{frame} |
|
1249 |
|
1250 \begin{frame} |
|
1251 {Tomorrow} |
|
1252 \begin{itemize} |
|
1253 \item Plotting: 2D, 3D |
|
1254 \item NumPy, SciPy |
|
1255 \item Dictionary, Set |
|
1256 \item Debugging |
|
1257 \item Testing |
|
1258 \item \ldots |
|
1259 \end{itemize} |
|
1260 11:30--13:00 Discussion of answers to problems OPTIONAL |
|
1261 \end{frame} |
|
1262 \end{document} |
636 \end{document} |
1263 |
|
1264 |
|
1265 \begin{frame}[fragile] |
|
1266 \frametitle{More on functions} |
|
1267 \begin{itemize} |
|
1268 \item Support default and keyword arguments |
|
1269 \item Scope of variables in the function is local |
|
1270 \item Mutable items are \alert{passed by reference} |
|
1271 \item First line after definition may be a documentation string |
|
1272 (\alert{recommended!}) |
|
1273 \item Function definition and execution defines a name bound to the |
|
1274 function |
|
1275 \item You \emph{can} assign a variable to a function! |
|
1276 \end{itemize} |
|
1277 \end{frame} |
|
1278 |
|
1279 |
|
1280 \begin{frame}[fragile] |
|
1281 \frametitle{Functions: default arguments} |
|
1282 \begin{lstlisting} |
|
1283 def ask_ok(prompt, retries=4, complaint='Yes or no!'): |
|
1284 while True: |
|
1285 ok = raw_input(prompt) |
|
1286 if ok in ('y', 'ye', 'yes'): |
|
1287 return True |
|
1288 if ok in ('n', 'no', 'nop', 'nope'): |
|
1289 return False |
|
1290 retries = retries - 1 |
|
1291 if retries < 0: |
|
1292 raise IOError, 'bad user' |
|
1293 print complaint |
|
1294 \end{lstlisting} |
|
1295 \end{frame} |
|
1296 |
|
1297 \begin{frame}[fragile] |
|
1298 \frametitle{Functions: keyword arguments} |
|
1299 \begin{lstlisting} |
|
1300 def parrot(voltage, state='a stiff', |
|
1301 action='voom', type='Norwegian Blue'): |
|
1302 print "-- This parrot wouldn't", action, |
|
1303 print "if you put", voltage, "Volts through it." |
|
1304 print "-- Lovely plumage, the", type |
|
1305 print "-- It's", state, "!" |
|
1306 |
|
1307 parrot(1000) |
|
1308 parrot(action = 'VOOOOOM', voltage = 1000000) |
|
1309 parrot('a thousand', state = 'pushing up the daisies') |
|
1310 parrot('a million', 'bereft of life', 'jump') |
|
1311 \end{lstlisting} |
|
1312 \end{frame} |
|
1313 |
|
1314 \begin{frame}[fragile] |
|
1315 \frametitle{Functions: arbitrary argument lists} |
|
1316 \begin{itemize} |
|
1317 \item Arbitrary number of arguments using \verb+*args+ or |
|
1318 \verb+*whatever+ |
|
1319 \item Keyword arguments using \verb+**kw+ |
|
1320 \item Given a tuple/dict how do you call a function? |
|
1321 \begin{itemize} |
|
1322 \item Using argument unpacking |
|
1323 \item For positional arguments: \verb+foo(*[5, 10])+ |
|
1324 \item For keyword args: \verb+foo(**{'a':5, 'b':10})+ |
|
1325 \end{itemize} |
|
1326 \end{itemize} |
|
1327 \begin{lstlisting} |
|
1328 def foo(a=10, b=100): |
|
1329 print a, b |
|
1330 def func(*args, **keyword): |
|
1331 print args, keyword |
|
1332 # Unpacking: |
|
1333 args = [5, 10] |
|
1334 foo(*args) |
|
1335 kw = {'a':5, 'b':10} |
|
1336 foo(**kw) |
|
1337 \end{lstlisting} |
|
1338 \end{frame} |
|
1339 |
|
1340 \subsection{Modules, exceptions, classes} |
|
1341 |
|
1342 \begin{frame} |
|
1343 \frametitle{Modules} |
|
1344 \begin{itemize} |
|
1345 \item Define variables, functions and classes in a file with a |
|
1346 \typ{.py} extension |
|
1347 \item This file becomes a module! |
|
1348 \item Modules are searched in the following: |
|
1349 \begin{itemize} |
|
1350 \item Current directory |
|
1351 \item Standard: \typ{/usr/lib/python2.3/site-packages/} etc. |
|
1352 \item Directories specified in PYTHONPATH |
|
1353 \item \typ{sys.path}: current path settings (from the \typ{sys} |
|
1354 module) |
|
1355 \end{itemize} |
|
1356 \item The \typ{import} keyword ``loads'' a module |
|
1357 \item One can also use: |
|
1358 \mbox{\typ{from module import name1, name2, name2}}\\ |
|
1359 where \typ{name1} etc. are names in the module, ``module'' |
|
1360 \item \typ{from module import *} \ --- imports everything from module, |
|
1361 \alert{use only in interactive mode} |
|
1362 \end{itemize} |
|
1363 \end{frame} |
|
1364 |
|
1365 \begin{frame}[fragile] |
|
1366 \frametitle{Modules: example} |
|
1367 \begin{lstlisting} |
|
1368 # --- foo.py --- |
|
1369 some_var = 1 |
|
1370 def fib(n): # write Fibonacci series up to n |
|
1371 """Print a Fibonacci series up to n.""" |
|
1372 a, b = 0, 1 |
|
1373 while b < n: |
|
1374 print b, |
|
1375 a, b = b, a+b |
|
1376 # EOF |
|
1377 |
|
1378 >>> import foo |
|
1379 >>> foo.fib(10) |
|
1380 1 1 2 3 5 8 |
|
1381 >>> foo.some_var |
|
1382 1 |
|
1383 \end{lstlisting} |
|
1384 \end{frame} |
|
1385 |
|
1386 \begin{frame}[fragile] |
|
1387 \frametitle{Namespaces} |
|
1388 \begin{itemize} |
|
1389 \item A mapping from names to objects |
|
1390 \item Modules introduce a namespace |
|
1391 \item So do classes |
|
1392 \item The running script's namespace is \verb+__main__+ |
|
1393 \item A modules namespace is identified by its name |
|
1394 \item The standard functions (like \typ{len}) are in the |
|
1395 \verb+__builtin__+ namespace |
|
1396 \item Namespaces help organize different names and their bindings to |
|
1397 different objects |
|
1398 \end{itemize} |
|
1399 \end{frame} |
|
1400 |
|
1401 \begin{frame} |
|
1402 \frametitle{Exceptions} |
|
1403 \begin{itemize} |
|
1404 \item Python's way of notifying you of errors |
|
1405 \item Several standard exceptions: \typ{SyntaxError}, \typ{IOError} |
|
1406 etc. |
|
1407 \item Users can also \typ{raise} errors |
|
1408 \item Users can create their own exceptions |
|
1409 \item Exceptions can be ``caught'' via \typ{try/except} blocks |
|
1410 \end{itemize} |
|
1411 \end{frame} |
|
1412 |
|
1413 \begin{frame}[fragile] |
|
1414 \frametitle{Exception: examples} |
|
1415 \begin{lstlisting} |
|
1416 >>> 10 * (1/0) |
|
1417 Traceback (most recent call last): |
|
1418 File "<stdin>", line 1, in ? |
|
1419 ZeroDivisionError: integer division or modulo by zero |
|
1420 >>> 4 + spam*3 |
|
1421 Traceback (most recent call last): |
|
1422 File "<stdin>", line 1, in ? |
|
1423 NameError: name 'spam' is not defined |
|
1424 >>> '2' + 2 |
|
1425 Traceback (most recent call last): |
|
1426 File "<stdin>", line 1, in ? |
|
1427 TypeError: cannot concatenate 'str' and 'int' objects |
|
1428 \end{lstlisting} |
|
1429 \end{frame} |
|
1430 |
|
1431 \begin{frame}[fragile] |
|
1432 \frametitle{Exception: examples} |
|
1433 \begin{lstlisting} |
|
1434 >>> while True: |
|
1435 ... try: |
|
1436 ... x = int(raw_input("Enter a number: ")) |
|
1437 ... break |
|
1438 ... except ValueError: |
|
1439 ... print "Invalid number, try again..." |
|
1440 ... |
|
1441 >>> # To raise exceptions |
|
1442 ... raise ValueError, "your error message" |
|
1443 Traceback (most recent call last): |
|
1444 File "<stdin>", line 2, in ? |
|
1445 ValueError: your error message |
|
1446 \end{lstlisting} |
|
1447 \end{frame} |
|
1448 |
|
1449 \begin{frame}[fragile] |
|
1450 \frametitle{Classes: the big picture} |
|
1451 \begin{itemize} |
|
1452 \item Lets you create new data types |
|
1453 \item Class is a template for an object belonging to that class |
|
1454 \item Note: in Python a class is also an object |
|
1455 \item Instantiating a class creates an instance (an object) |
|
1456 \item An instance encapsulates the state (data) and behavior |
|
1457 (methods) |
|
1458 \item Allows you to define an inheritance hierarchy |
|
1459 \begin{itemize} |
|
1460 \item ``A Honda car \alert{is a} car.'' |
|
1461 \item ``A car \alert{is an} automobile.'' |
|
1462 \item ``A Python \alert{is a} reptile.'' |
|
1463 \end{itemize} |
|
1464 \item Programmers need to think OO |
|
1465 \end{itemize} |
|
1466 \end{frame} |
|
1467 |
|
1468 \begin{frame}[fragile] |
|
1469 \frametitle{Classes: what's the big deal?} |
|
1470 \begin{itemize} |
|
1471 \item Lets you create objects that mimic a real problem being |
|
1472 simulated |
|
1473 \item Makes problem solving more natural and elegant |
|
1474 \item Easier to create code |
|
1475 \item Allows for code-reuse |
|
1476 \item Polymorphism |
|
1477 \end{itemize} |
|
1478 \end{frame} |
|
1479 |
|
1480 \begin{frame}[fragile] |
|
1481 \frametitle{Class definition and instantiation} |
|
1482 \begin{itemize} |
|
1483 \item Class definitions when executed create class objects |
|
1484 \item Instantiating the class object creates an instance of the |
|
1485 class |
|
1486 \end{itemize} |
|
1487 \footnotesize |
|
1488 \begin{lstlisting} |
|
1489 class Foo(object): |
|
1490 pass |
|
1491 # class object created. |
|
1492 # Create an instance of Foo. |
|
1493 f = Foo() |
|
1494 # Can assign an attribute to the instance |
|
1495 f.a = 100 |
|
1496 print f.a |
|
1497 100 |
|
1498 \end{lstlisting} |
|
1499 \end{frame} |
|
1500 |
|
1501 \begin{frame}[fragile] |
|
1502 \frametitle{Classes \ldots} |
|
1503 \begin{itemize} |
|
1504 \item All attributes are accessed via the \typ{object.attribute} |
|
1505 syntax |
|
1506 \item Both class and instance attributes are supported |
|
1507 \item \emph{Methods} represent the behavior of an object: crudely |
|
1508 think of them as functions ``belonging'' to the object |
|
1509 \item All methods in Python are ``virtual'' |
|
1510 \item Inheritance through subclassing |
|
1511 \item Multiple inheritance is supported |
|
1512 \item No special public and private attributes: only good |
|
1513 conventions |
|
1514 \begin{itemize} |
|
1515 \item \verb+object.public()+: public |
|
1516 \item \verb+object._private()+ \& \verb+object.__priv()+: |
|
1517 non-public |
|
1518 \end{itemize} |
|
1519 \end{itemize} |
|
1520 \end{frame} |
|
1521 |
|
1522 \begin{frame}[fragile] |
|
1523 \frametitle{Classes: examples} |
|
1524 \begin{lstlisting} |
|
1525 class MyClass(object): |
|
1526 """Example class (this is the class docstring).""" |
|
1527 i = 12345 # A class attribute |
|
1528 def f(self): |
|
1529 """This is the method docstring""" |
|
1530 return 'hello world' |
|
1531 |
|
1532 >>> a = MyClass() # creates an instance |
|
1533 >>> a.f() |
|
1534 'hello world' |
|
1535 >>> # a.f() is equivalent to MyClass.f(a) |
|
1536 ... # This also explains why f has a 'self' argument. |
|
1537 ... MyClass.f(a) |
|
1538 'hello world' |
|
1539 \end{lstlisting} |
|
1540 \end{frame} |
|
1541 |
|
1542 \begin{frame}[fragile] |
|
1543 \frametitle{Classes (continued)} |
|
1544 \begin{itemize} |
|
1545 \item \typ{self} is \alert{conventionally} the first argument for a |
|
1546 method |
|
1547 \item In previous example, \typ{a.f} is a method object |
|
1548 \item When \typ{a.f} is called, it is passed the instance \typ{a} as |
|
1549 the first argument |
|
1550 \item If a method called \verb+__init__+ exists, it is called when |
|
1551 the object is created |
|
1552 \item If a method called \verb+__del__+ exists, it is called before |
|
1553 the object is garbage collected |
|
1554 \item Instance attributes are set by simply ``setting'' them in |
|
1555 \typ{self} |
|
1556 \item Other special methods (by convention) like \verb+__add__+ let |
|
1557 you define numeric types: |
|
1558 {\footnotesize \url{http://docs.python.org/ref/specialnames.html} |
|
1559 \\ \url{http://docs.python.org/ref/numeric-types.html} |
|
1560 } |
|
1561 \end{itemize} |
|
1562 \end{frame} |
|
1563 |
|
1564 \begin{frame}[fragile] |
|
1565 \frametitle{Classes: examples} |
|
1566 \begin{lstlisting} |
|
1567 class Bag(MyClass): # Shows how to derive classes |
|
1568 def __init__(self): # called on object creation. |
|
1569 self.data = [] # an instance attribute |
|
1570 def add(self, x): |
|
1571 self.data.append(x) |
|
1572 def addtwice(self, x): |
|
1573 self.add(x) |
|
1574 self.add(x) |
|
1575 >>> a = Bag() |
|
1576 >>> a.f() # Inherited method |
|
1577 'hello world' |
|
1578 >>> a.add(1); a.addtwice(2) |
|
1579 >>> a.data |
|
1580 [1, 2, 2] |
|
1581 \end{lstlisting} |
|
1582 \end{frame} |
|
1583 |
|
1584 \begin{frame}[fragile] |
|
1585 \frametitle{Derived classes} |
|
1586 \begin{itemize} |
|
1587 \item Call the parent's \verb+__init__+ if needed |
|
1588 \item If you don't need a new constructor, no need to define it in subclass |
|
1589 \item Can also use the \verb+super+ built-in function |
|
1590 \end{itemize} |
|
1591 \begin{lstlisting} |
|
1592 class AnotherBag(Bag): |
|
1593 def __init__(self): |
|
1594 # Must call parent's __init__ explicitly |
|
1595 Bag.__init__(self) |
|
1596 # Alternatively use this: |
|
1597 super(AnotherBag, self).__init__() |
|
1598 # Now setup any more data. |
|
1599 self.more_data = [] |
|
1600 \end{lstlisting} |
|
1601 \end{frame} |
|
1602 |
|
1603 \begin{frame}[fragile] |
|
1604 \frametitle{Classes: polymorphism} |
|
1605 \begin{lstlisting} |
|
1606 class Drawable(object): |
|
1607 def draw(self): |
|
1608 # Just a specification. |
|
1609 pass |
|
1610 \end{lstlisting} |
|
1611 \mode<presentation>{\pause} |
|
1612 \begin{lstlisting} |
|
1613 class Square(Drawable): |
|
1614 def draw(self): |
|
1615 # draw a square. |
|
1616 class Circle(Drawable): |
|
1617 def draw(self): |
|
1618 # draw a circle. |
|
1619 \end{lstlisting} |
|
1620 \mode<presentation>{\pause} |
|
1621 \begin{lstlisting} |
|
1622 class Artist(Drawable): |
|
1623 def draw(self): |
|
1624 for obj in self.drawables: |
|
1625 obj.draw() |
|
1626 \end{lstlisting} |
|
1627 \end{frame} |
|
1628 |
|
1629 \subsection{Miscellaneous} |
|
1630 |
|
1631 \begin{frame}[fragile] |
|
1632 \frametitle{Stand-alone scripts} |
|
1633 Consider a file \typ{f.py}: |
|
1634 \begin{lstlisting} |
|
1635 #!/usr/bin/env python |
|
1636 """Module level documentation.""" |
|
1637 # First line tells the shell that it should use Python |
|
1638 # to interpret the code in the file. |
|
1639 def f(): |
|
1640 print "f" |
|
1641 |
|
1642 # Check if we are running standalone or as module. |
|
1643 # When imported, __name__ will not be '__main__' |
|
1644 if __name__ == '__main__': |
|
1645 # This is not executed when f.py is imported. |
|
1646 f() |
|
1647 \end{lstlisting} |
|
1648 \end{frame} |
|
1649 |
|
1650 \begin{frame}[fragile] |
|
1651 \frametitle{List comprehensions} |
|
1652 \begin{lstlisting} |
|
1653 >>> veg = ['tomato', 'cabbage', 'carrot', 'potato'] |
|
1654 >>> [x.upper() for x in veg] |
|
1655 ['TOMATO', 'CABBAGE', 'CARROT', 'POTATO'] |
|
1656 >>> vec = range(0, 8) |
|
1657 >>> even = [x for x in vec if x%2 == 0] |
|
1658 >>> even |
|
1659 [0, 2, 4, 6] |
|
1660 >>> [x*x for x in even] |
|
1661 [0, 4, 16, 36] |
|
1662 >>> odd = [x for x in vec if x%2 == 1] |
|
1663 >>> odd |
|
1664 [1, 3, 5, 7] |
|
1665 >>> [x*y for x in even for y in odd] |
|
1666 [0, 0, 0, 0, 2, 6, 10, 14, 4, 12, 20, 28, 6, 18,30,42] |
|
1667 \end{lstlisting} |
|
1668 \end{frame} |
|
1669 |
|
1670 \begin{frame}[fragile] |
|
1671 \frametitle{More IPython features} |
|
1672 \begin{itemize} |
|
1673 \item Input and output caching: |
|
1674 \begin{itemize} |
|
1675 \item \verb+In+: a list of all entered input |
|
1676 \item \verb+Out+: a dict of all output |
|
1677 \item \verb+_+, \verb+__+, \verb+__+ are the last three results as |
|
1678 is \verb+_N+ |
|
1679 \item \verb+%hist [-n]+ macro shows previous history, \verb+-n+ |
|
1680 suppresses line number information |
|
1681 \end{itemize} |
|
1682 \item Log the session using \verb+%logstart+, \verb+%logon+ and |
|
1683 \verb+%logoff+ |
|
1684 \item \verb+%run [options] file[.py]+ -- running Python code |
|
1685 \begin{itemize} |
|
1686 \item \verb+%run -d [-b<N>]+: debug script with pdb |
|
1687 \verb+N+ is the line number to break at (defaults to 1) |
|
1688 \item \verb+%run -t+: time the script |
|
1689 \item \verb+%run -p+: Profile the script |
|
1690 \end{itemize} |
|
1691 \item \verb+%prun+ runs a statement/expression under the profiler |
|
1692 \item \verb+%macro [options] macro_name n1-n2 n3-n4 n6+ save specified |
|
1693 lines to a macro with name \verb+macro_name+ |
|
1694 \end{itemize} |
|
1695 \end{frame} |
|
1696 |
|
1697 \begin{frame}[fragile] |
|
1698 \frametitle{More IPython features \ldots} |
|
1699 \begin{itemize} |
|
1700 \item \verb+%edit [options] [args]+: edit lines of code or file |
|
1701 specified in editor (configure editor via \verb+$EDITOR+) |
|
1702 \item \verb+%cd+ changes directory, see also \verb+%pushd, %popd, %dhist+ |
|
1703 \item Shell access |
|
1704 \begin{itemize} |
|
1705 \item \verb+!command+ runs a shell command and returns its output |
|
1706 \item \verb+files = %sx ls+ or \verb+files = !ls+ sets |
|
1707 \verb+files+ to all result of the \verb+ls+ command |
|
1708 \item \verb+%sx+ is quiet |
|
1709 \item \verb+!ls $files+ passes the \verb+files+ variable to the |
|
1710 shell command |
|
1711 \item \verb+%alias alias_name cmd+ creates an alias for a system |
|
1712 command |
|
1713 \end{itemize} |
|
1714 \item \verb+%colors+ lets you change the color scheme to |
|
1715 \verb+NoColor, Linux, LightBG+ |
|
1716 \end{itemize} |
|
1717 \end{frame} |
|
1718 |
|
1719 \begin{frame}[fragile] |
|
1720 \frametitle{More IPython features \ldots} |
|
1721 \begin{itemize} |
|
1722 \item Use \verb+;+ at the end of a statement to suppress printing |
|
1723 output |
|
1724 \item \verb+%bookmark+: store a bookmarked location, for use with \verb+%cd+ |
|
1725 \item \verb+%who, %whos+: print information on variables |
|
1726 \item \verb+%save [options] filename n1-n2 n3-n4+: save lines to a |
|
1727 file |
|
1728 \item \verb+%time statement+: Time execution of a Python statement or |
|
1729 expression |
|
1730 \item \verb+%timeit [-n<N> -r<R> [-t|-c]] statement+: time execution |
|
1731 using Python's timeit module |
|
1732 \item Can define and use profiles to setup IPython differently: |
|
1733 \verb+math, scipy, numeric, pysh+ etc. |
|
1734 \item \verb+%magic+: \alert{Show help on all magics} |
|
1735 \end{itemize} |
|
1736 \end{frame} |
|
1737 |
|
1738 \begin{frame}[fragile] |
|
1739 \frametitle{File handling} |
|
1740 \begin{lstlisting} |
|
1741 >>> # Reading files: |
|
1742 ... f = open('/path/to/file_name') |
|
1743 >>> data = f.read() # Read entire file. |
|
1744 >>> line = f.readline() # Read one line. |
|
1745 >>> # Read entire file appending each line into a list |
|
1746 ... lines = f.readlines() |
|
1747 >>> f.close() # close the file. |
|
1748 >>> # Writing files: |
|
1749 ... f = open('/path/to/file_name', 'w') |
|
1750 >>> f.write('hello world\n') |
|
1751 \end{lstlisting} |
|
1752 \begin{itemize} |
|
1753 \item \typ{tell()}: returns int of current position |
|
1754 \item \typ{seek(pos)}: moves current position to specified byte |
|
1755 \item Call \typ{close()} when done using a file |
|
1756 \end{itemize} |
|
1757 \end{frame} |
|
1758 |
|
1759 \begin{frame}[fragile] |
|
1760 \frametitle{Math} |
|
1761 \begin{itemize} |
|
1762 \item \typ{math} module provides basic math routines for |
|
1763 floats |
|
1764 \item \typ{cmath} module provides math routies for complex |
|
1765 numbers |
|
1766 \item \typ{random}: provides pseudo-random number generators |
|
1767 for various distributions |
|
1768 \item These are always available and part of the standard library |
|
1769 \item More serious math is provided by the NumPy/SciPy modules -- |
|
1770 these are not standard and need to be installed separately |
|
1771 \end{itemize} |
|
1772 \end{frame} |
|
1773 |
|
1774 \begin{frame}[fragile] |
|
1775 \frametitle{Timing and profiling} |
|
1776 \begin{itemize} |
|
1777 \item Timing code: use the \typ{time} module |
|
1778 \item Read up on \typ{time.time()} and \typ{time.clock()} |
|
1779 \item \typ{timeit}: is a better way of doing timing |
|
1780 \item IPython has handy \typ{time} and \typ{timeit} macros (type |
|
1781 \typ{timeit?} for help) |
|
1782 \item IPython lets you debug and profile code via the \typ{run} |
|
1783 macro (type \typ{run?} on the prompt to learn more) |
|
1784 \end{itemize} |
|
1785 \end{frame} |
|
1786 |
|
1787 \begin{frame}[fragile] |
|
1788 \frametitle{Odds and ends} |
|
1789 \begin{itemize} |
|
1790 \item \typ{dir([object])} function: attributes of given object |
|
1791 \item \typ{type(object)}: returns type information |
|
1792 \item \typ{str(), repr()}: convert object to string representation |
|
1793 \item \typ{isinstance, issubclass} |
|
1794 \item \typ{assert} statements let you do debugging assertions in |
|
1795 code |
|
1796 \item \typ{csv} module: reading and writing CSV files |
|
1797 \item \typ{pickle}: lets you save and load Python objects |
|
1798 (\alert{serialization}) |
|
1799 \item \typ{sys.argv}: command line arguments |
|
1800 \item \typ{os.path}: common path manipulations |
|
1801 \item Check out the Python Library reference: |
|
1802 \url{http://docs.python.org/lib/lib.html} |
|
1803 \end{itemize} |
|
1804 \end{frame} |
|
1805 |
|
1806 \begin{frame}[fragile] |
|
1807 \frametitle{Test driven development (TDD)} |
|
1808 \begin{itemize} |
|
1809 \item Why? |
|
1810 \begin{itemize} |
|
1811 |
|
1812 \item Forces you to write reusable code! |
|
1813 |
|
1814 \item Think about the API |
|
1815 |
|
1816 \item More robust |
|
1817 |
|
1818 \item Makes refactoring very easy |
|
1819 |
|
1820 \end{itemize} |
|
1821 \item How? Python offers three major ways of doing this |
|
1822 \begin{itemize} |
|
1823 \item doctest |
|
1824 \item unittest |
|
1825 \item nosetest (and similar like py.test) |
|
1826 \end{itemize} |
|
1827 |
|
1828 \item Test every piece of functionality you offer |
|
1829 |
|
1830 \item This isn't a formal introduction but more a practical one |
|
1831 |
|
1832 \end{itemize} |
|
1833 \end{frame} |
|
1834 |
|
1835 \begin{frame}[fragile] |
|
1836 \frametitle{Unit test} |
|
1837 \begin{lstlisting} |
|
1838 import unittest |
|
1839 |
|
1840 class MyTestCase(unittest.TestCase): |
|
1841 def setUp(self): |
|
1842 # Called *before* each test_* |
|
1843 def tearDown(self): |
|
1844 # Called *after* each test_* |
|
1845 def test_something(self): |
|
1846 "docstring" |
|
1847 # Test code. |
|
1848 self.assertEqual(x, y) |
|
1849 self.assertRaises(ValueError, func, arg1, arg2 ...) |
|
1850 |
|
1851 if __name__ == '__main__': |
|
1852 unittest.main() |
|
1853 \end{lstlisting} |
|
1854 \end{frame} |
|
1855 |
|
1856 \begin{frame}[fragile] |
|
1857 \frametitle{Nosetest} |
|
1858 \begin{lstlisting} |
|
1859 import particle |
|
1860 def test_particle(): |
|
1861 # Use asserts here. |
|
1862 p = particle.Particle(1.0) |
|
1863 assert p.property[0] == 1.0 |
|
1864 assert p.property[2] == 0.0 |
|
1865 |
|
1866 if __name__ == '__main__': |
|
1867 import nose |
|
1868 nose.main() |
|
1869 \end{lstlisting} |
|
1870 \end{frame} |
|
1871 |
|
1872 \begin{frame}[fragile] |
|
1873 \frametitle{Testing} |
|
1874 \begin{itemize} |
|
1875 \item More details: see library reference and search for nosetest |
|
1876 \end{itemize} |
|
1877 \end{frame} |
|
1878 |
|
1879 \section{Numerics \& Plotting} |
|
1880 |
|
1881 \subsection{NumPy Arrays} |
|
1882 |
|
1883 \newcommand{\num}{\texttt{numpy}} |
|
1884 |
|
1885 \begin{frame} |
|
1886 \frametitle{The \num\ module} |
|
1887 \begin{itemize} |
|
1888 \item Manipulating large Python lists for scientific computing is |
|
1889 \alert{slow} |
|
1890 \item Most complex computations can be reduced to a few standard |
|
1891 operations |
|
1892 \item The \num\ module provides: |
|
1893 \begin{itemize} |
|
1894 \item An efficient and powerful array type for various common data |
|
1895 types |
|
1896 \item Abstracts out the most commonly used standard operations on |
|
1897 arrays |
|
1898 \end{itemize} |
|
1899 \item Numeric was the first, then came \texttt{numarray}. |
|
1900 \texttt{numpy} is the latest and is the future |
|
1901 \item This course uses \num\ and only covers the absolute basics |
|
1902 \end{itemize} |
|
1903 \end{frame} |
|
1904 |
|
1905 \begin{frame} |
|
1906 \frametitle{Basic concepts} |
|
1907 \begin{itemize} |
|
1908 \item \num\ arrays are of a fixed size (\typ{arr.size}) and have the |
|
1909 same type (\typ{arr.dtype}) |
|
1910 \item \num\ arrays may have arbitrary dimensionality |
|
1911 \item The \typ{shape} of an array is the extent (length) of the |
|
1912 array along each dimension |
|
1913 \item The \typ{rank(arr)} of an array is the ``dimensionality'' of the |
|
1914 array |
|
1915 \item The \typ{arr.itemsize} is the number of bytes (8-bits) used for |
|
1916 each element of the array |
|
1917 \item \alert{Note:} The \typ{shape} and \typ{rank} may change as |
|
1918 long as the \typ{size} of the array is fixed |
|
1919 \item \alert{Note:} \typ{len(arr) != arr.size} in general |
|
1920 \item \alert{Note:} By default array operations are performed |
|
1921 \alert{elementwise} |
|
1922 \item Indices start from 0 |
|
1923 \end{itemize} |
|
1924 \end{frame} |
|
1925 |
|
1926 \begin{frame}[fragile] |
|
1927 \frametitle{Examples of \num} |
|
1928 \begin{lstlisting} |
|
1929 # Simple array math example |
|
1930 >>> from numpy import * |
|
1931 >>> a = array([1,2,3,4]) |
|
1932 >>> b = array([2,3,4,5]) |
|
1933 >>> a + b # Element wise addition! |
|
1934 array([3, 5, 7, 9]) |
|
1935 |
|
1936 >>> print pi, e # Pi and e are defined. |
|
1937 3.14159265359 2.71828182846 |
|
1938 # Create array from 0 to 10 |
|
1939 >>> x = arange(0.0, 10.0, 0.05) |
|
1940 >>> x *= 2*pi/10 # multiply array by scalar value |
|
1941 array([ 0.,0.0314,...,6.252]) |
|
1942 # apply functions to array. |
|
1943 >>> y = sin(x) |
|
1944 \end{lstlisting} |
|
1945 \end{frame} |
|
1946 |
|
1947 \begin{frame}[fragile] |
|
1948 \frametitle{More examples of \num} |
|
1949 \vspace*{-8pt} |
|
1950 \begin{lstlisting} |
|
1951 # Size, shape, rank, type etc. |
|
1952 >>> x = array([1., 2, 3, 4]) |
|
1953 >>> size(x) |
|
1954 4 |
|
1955 >>> x.dtype # or x.dtype.char |
|
1956 'd' |
|
1957 >>> x.shape |
|
1958 (4,) |
|
1959 >>> print rank(x), x.itemsize |
|
1960 1 8 |
|
1961 >>> x.tolist() |
|
1962 [1.0, 2.0, 3.0, 4.0] |
|
1963 # Array indexing |
|
1964 >>> x[0] = 10 |
|
1965 >>> print x[0], x[-1] |
|
1966 10.0 4.0 |
|
1967 \end{lstlisting} |
|
1968 \end{frame} |
|
1969 |
|
1970 \begin{frame}[fragile] |
|
1971 \frametitle{Multi-dimensional arrays} |
|
1972 \begin{lstlisting} |
|
1973 >>> a = array([[ 0, 1, 2, 3], |
|
1974 ... [10,11,12,13]]) |
|
1975 >>> a.shape # (rows, columns) |
|
1976 (2, 4) |
|
1977 # Accessing and setting values |
|
1978 >>> a[1,3] |
|
1979 13 |
|
1980 >>> a[1,3] = -1 |
|
1981 >>> a[1] # The second row |
|
1982 array([10,11,12,-1]) |
|
1983 |
|
1984 # Flatten/ravel arrays to 1D arrays |
|
1985 >>> a.flat # or ravel(a) |
|
1986 array([0,1,2,3,10,11,12,-1]) |
|
1987 # Note: flat references original memory |
|
1988 \end{lstlisting} |
|
1989 \end{frame} |
|
1990 |
|
1991 \begin{frame}[fragile] |
|
1992 \frametitle{Slicing arrays} |
|
1993 \begin{lstlisting} |
|
1994 >>> a = array([[1,2,3], [4,5,6], [7,8,9]]) |
|
1995 >>> a[0,1:3] |
|
1996 array([2, 3]) |
|
1997 >>> a[1:,1:] |
|
1998 array([[5, 6], |
|
1999 [8, 9]]) |
|
2000 >>> a[:,2] |
|
2001 array([3, 6, 9]) |
|
2002 # Striding... |
|
2003 >>> a[0::2,0::2] |
|
2004 array([[1, 3], |
|
2005 [7, 9]]) |
|
2006 # All these slices are references to the same memory! |
|
2007 \end{lstlisting} |
|
2008 \end{frame} |
|
2009 |
|
2010 % \begin{frame}[fragile] |
|
2011 % \frametitle{Array types and typecodes} |
|
2012 % \begin{tabular}[c]{|c|c|p{2.75in}|} |
|
2013 % \hline |
|
2014 % Character & Bits (bytes) & Type name \\ |
|
2015 % \hline |
|
2016 % D & 128 (16) & \typ{Complex, Complex64}\\ |
|
2017 % F & 64 (8) & \typ{Complex0, Complex8, Complex16} \\ |
|
2018 % d & 64 (8) & \typ{Float, Float64} \\ |
|
2019 % f & 32 (4) & \typ{Float0, Float8, Float16} \\ |
|
2020 % i & 32 (4) & \typ{Int32} \\ |
|
2021 % l & 32 (4) & \typ{Int} \\ |
|
2022 % O & 4 (1) & \typ{PyObject} \\ |
|
2023 % %b 8 (1) UnsignedInt8 |
|
2024 % %1 (one) 8 (1) Int8 |
|
2025 % %s 16 (2) Int16 |
|
2026 % \hline |
|
2027 % \end{tabular} |
|
2028 % \begin{lstlisting} |
|
2029 % # Examples |
|
2030 % >>> f = array([1,2,3], Float32) |
|
2031 % >>> c = array([1,2,3], Complex32) |
|
2032 % >>> print f, c |
|
2033 % [ 1. 2. 3.] [ 1.+0.j 2.+0.j 3.+0.j] |
|
2034 % \end{lstlisting} |
|
2035 % \end{frame} |
|
2036 |
|
2037 \begin{frame}[fragile] |
|
2038 \frametitle{Array creation functions} |
|
2039 \begin{itemize} |
|
2040 \item \typ{array(object, dtype=None, copy=1,order=None, subok=0,ndmin=0)} |
|
2041 \item \typ{arange(start, stop=None, step=1, dtype=None)} |
|
2042 \item \typ{linspace(start, stop, num=50, endpoint=True, retstep=False)} |
|
2043 \item \typ{ones(shape, dtype=None, order='C')} |
|
2044 \item \typ{zeros((d1,...,dn),dtype=float,order='C')} |
|
2045 \item \typ{identity(n)} |
|
2046 \item \typ{empty((d1,...,dn),dtype=float,order='C')} |
|
2047 \item \typ{ones\_like(x)}, \typ{zeros\_like(x)}, \typ{empty\_like(x)} |
|
2048 \end{itemize} |
|
2049 \end{frame} |
|
2050 |
|
2051 \begin{frame}[fragile] |
|
2052 \frametitle{Array math} |
|
2053 \begin{itemize} |
|
2054 \item Basic \alert{elementwise} math (given two arrays \typ{a, b}): |
|
2055 \begin{itemize} |
|
2056 \item \typ{a + b $\rightarrow$ add(a, b)} |
|
2057 \item \typ{a - b, $\rightarrow$ subtract(a, b)} |
|
2058 \item \typ{a * b, $\rightarrow$ multiply(a, b)} |
|
2059 \item \typ{a / b, $\rightarrow$ divide(a, b)} |
|
2060 \item \typ{a \% b, $\rightarrow$ remainder(a, b)} |
|
2061 \item \typ{a ** b, $\rightarrow$ power(a, b)} |
|
2062 \end{itemize} |
|
2063 \item Inplace operators: \typ{a += b}, or \typ{add(a, b, |
|
2064 a)} etc. |
|
2065 \item Logical operations: \typ{equal (==)}, \typ{not\_equal (!=)}, |
|
2066 \typ{less (<)}, \typ{greater (>)} etc. |
|
2067 \item Trig and other functions: \typ{sin(x), arcsin(x), sinh(x), |
|
2068 exp(x), sqrt(x)} etc. |
|
2069 \item \typ{sum(x, axis=0), product(x, axis=0)}: sum and product of array elements |
|
2070 \item \typ{dot(a, b)} |
|
2071 \end{itemize} |
|
2072 \end{frame} |
|
2073 |
|
2074 \begin{frame}[fragile] |
|
2075 \frametitle{Advanced} |
|
2076 \begin{itemize} |
|
2077 \item Only scratched the surface of \num |
|
2078 \item Ufunc methods: \typ{reduce, accumulate, outer, reduceat} |
|
2079 \item Typecasting |
|
2080 \item More functions: \typ{take, choose, where, compress, |
|
2081 concatenate} |
|
2082 \item Array broadcasting and \typ{None} |
|
2083 \end{itemize} |
|
2084 \end{frame} |
|
2085 |
|
2086 \subsection{Plotting: Matplotlib} |
|
2087 |
|
2088 \begin{frame} |
|
2089 \frametitle{About \texttt{matplotlib}} |
|
2090 \begin{itemize} |
|
2091 \item Easy to use, scriptable, ``Matlab-like'' 2D plotting |
|
2092 \item Publication quality figures and interactive capabilities |
|
2093 \item Plots, histograms, power spectra, bar charts, errorcharts, |
|
2094 scatterplots, etc. |
|
2095 \item Also does polar plots, maps, contours |
|
2096 \item Support for simple \TeX\ markup |
|
2097 \item Multiple output backends (images, EPS, SVG, wx, Agg, Tk, GTK) |
|
2098 \item Cross-platform: Linux, Win32, Mac OS X |
|
2099 \item Good idea to use via IPython: \typ{ipython -pylab} |
|
2100 \item From scripts use: \typ{import pylab} |
|
2101 \end{itemize} |
|
2102 \end{frame} |
|
2103 |
|
2104 \begin{frame} |
|
2105 \frametitle{More information} |
|
2106 \begin{itemize} |
|
2107 \item More information here: \url{http://matplotlib.sf.net} |
|
2108 \item \url{http://matplotlib.sf.net/tutorial.html} |
|
2109 \item \url{http://matplotlib.sf.net/screenshots.html} |
|
2110 \end{itemize} |
|
2111 \end{frame} |
|
2112 |
|
2113 \begin{frame}[fragile] |
|
2114 \frametitle{Basic plotting with \texttt{matplotlib}} |
|
2115 \begin{lstlisting} |
|
2116 >>> x = arange(0, 2*pi, 0.05) |
|
2117 >>> plot(x, sin(x)) # Same as plot(x, sin(x), 'b-') |
|
2118 >>> plot(x, sin(x), 'ro') |
|
2119 >>> axis([0,2*pi, -1,1]) |
|
2120 >>> xlabel(r'$\chi$', color='g') |
|
2121 >>> ylabel(r'sin($\chi$)', color='r') |
|
2122 >>> title('A simple figure', fontsize=20) |
|
2123 >>> savefig('/tmp/test.eps') |
|
2124 # Multiple plots in one figure |
|
2125 >>> t = arange(0.0, 5.2, 0.2) |
|
2126 # red dashes, blue squares and green triangles |
|
2127 >>> plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') |
|
2128 \end{lstlisting} |
|
2129 \end{frame} |
|
2130 |
|
2131 \begin{frame}[fragile] |
|
2132 \frametitle{Basic plotting \ldots} |
|
2133 \begin{lstlisting} |
|
2134 # Set properties of objects: |
|
2135 >>> plot(x, sin(x), linewidth=2.0, color='r') |
|
2136 >>> l, = plot(x, sin(x)) |
|
2137 >>> setp(l, linewidth=2.0, color='r') |
|
2138 >>> l.set_linewidth(2.0); l.set_color('r') |
|
2139 >>> draw() # Redraws current figure. |
|
2140 >>> setp(l) # Prints available properties |
|
2141 >>> close() # Closes the figure. |
|
2142 # Multiple figures: |
|
2143 >>> figure(1); plot(x, sin(x)) |
|
2144 >>> figure(2); plot(x, tanh(x)) |
|
2145 >>> figure(1); title('Easy as 1,2,3') |
|
2146 \end{lstlisting} |
|
2147 \end{frame} |
|
2148 |
|
2149 \begin{frame}[fragile] |
|
2150 \frametitle{Basic plotting \ldots} |
|
2151 \begin{lstlisting} |
|
2152 >>> figure(1) |
|
2153 >>> subplot(211) # Same as subplot(2, 1, 1) |
|
2154 >>> plot(x, cos(5*x)*exp(-x)) |
|
2155 >>> subplot(2, 1, 2) |
|
2156 >>> plot(x, cos(5*x), 'r--', label='cosine') |
|
2157 >>> plot(x, sin(5*x), 'g--', label='sine') |
|
2158 >>> legend() # Or legend(['cosine', 'sine']) |
|
2159 >>> text(1,0, '(1,0)') |
|
2160 >>> axes = gca() # Current axis |
|
2161 >>> fig = gcf() # Current figure |
|
2162 \end{lstlisting} |
|
2163 \end{frame} |
|
2164 |
|
2165 \begin{frame}[fragile] |
|
2166 \frametitle{X-Y plot} |
|
2167 \begin{columns} |
|
2168 \column{0.5\textwidth} |
|
2169 \hspace*{-0.5in} |
|
2170 \includegraphics[height=2in, interpolate=true]{data/xyplot} |
|
2171 \column{0.45\textwidth} |
|
2172 \begin{block}{Example code} |
|
2173 \tiny |
|
2174 \begin{lstlisting} |
|
2175 t1 = arange(0.0, 5.0, 0.1) |
|
2176 t2 = arange(0.0, 5.0, 0.02) |
|
2177 t3 = arange(0.0, 2.0, 0.01) |
|
2178 subplot(211) |
|
2179 plot(t1, cos(2*pi*t1)*exp(-t1), 'bo', |
|
2180 t2, cos(2*pi*t2)*exp(-t2), 'k') |
|
2181 grid(True) |
|
2182 title('A tale of 2 subplots') |
|
2183 ylabel('Damped') |
|
2184 subplot(212) |
|
2185 plot(t3, cos(2*pi*t3), 'r--') |
|
2186 grid(True) |
|
2187 xlabel('time (s)') |
|
2188 ylabel('Undamped') |
|
2189 \end{lstlisting} |
|
2190 \end{block} |
|
2191 \end{columns} |
|
2192 \end{frame} |
|
2193 |
|
2194 \begin{frame}[fragile] \frametitle{Errorbar} |
|
2195 \begin{columns} |
|
2196 \column{0.5\textwidth} |
|
2197 \hspace*{-0.5in} |
|
2198 \includegraphics[height=2in, interpolate=true]{data/errorbar} |
|
2199 \column{0.45\textwidth} |
|
2200 \begin{block}{Example code} |
|
2201 \tiny |
|
2202 \begin{lstlisting} |
|
2203 t = arange(0.1, 4, 0.1) |
|
2204 s = exp(-t) |
|
2205 e = 0.1*abs(randn(len(s))) |
|
2206 f = 0.1*abs(randn(len(s))) |
|
2207 g = 2*e |
|
2208 h = 2*f |
|
2209 errorbar(t, s, [e,g], f, fmt='o') |
|
2210 xlabel('Distance (m)') |
|
2211 ylabel('Height (m)') |
|
2212 title('Mean and standard error '\ |
|
2213 'as a function of distance') |
|
2214 \end{lstlisting} |
|
2215 \end{block} |
|
2216 \end{columns} |
|
2217 \end{frame} |
|
2218 |
|
2219 \begin{frame}[fragile] \frametitle{Semi-log and log-log plots} |
|
2220 \begin{columns} |
|
2221 \column{0.5\textwidth} |
|
2222 \hspace*{-0.5in} |
|
2223 \includegraphics[height=2in, interpolate=true]{data/log} |
|
2224 \column{0.45\textwidth} |
|
2225 \begin{block}{Example code} |
|
2226 \tiny |
|
2227 \begin{lstlisting} |
|
2228 dt = 0.01 |
|
2229 t = arange(dt, 20.0, dt) |
|
2230 subplot(311) |
|
2231 semilogy(t, exp(-t/5.0)) |
|
2232 ylabel('semilogy') |
|
2233 grid(True) |
|
2234 subplot(312) |
|
2235 semilogx(t, sin(2*pi*t)) |
|
2236 ylabel('semilogx') |
|
2237 grid(True) |
|
2238 # minor grid on too |
|
2239 gca().xaxis.grid(True, which='minor') |
|
2240 subplot(313) |
|
2241 loglog(t, 20*exp(-t/10.0), basex=4) |
|
2242 grid(True) |
|
2243 ylabel('loglog base 4 on x') |
|
2244 \end{lstlisting} |
|
2245 \end{block} |
|
2246 \end{columns} |
|
2247 \end{frame} |
|
2248 |
|
2249 \begin{frame}[fragile] \frametitle{Histogram} |
|
2250 \begin{columns} |
|
2251 \column{0.5\textwidth} |
|
2252 \hspace*{-0.5in} |
|
2253 \includegraphics[height=2in, interpolate=true]{data/histogram} |
|
2254 \column{0.45\textwidth} |
|
2255 \begin{block}{Example code} |
|
2256 \tiny |
|
2257 \begin{lstlisting} |
|
2258 mu, sigma = 100, 15 |
|
2259 x = mu + sigma*randn(10000) |
|
2260 # the histogram of the data |
|
2261 n, bins, patches = hist(x, 100, normed=1) |
|
2262 # add a 'best fit' line |
|
2263 y = normpdf( bins, mu, sigma) |
|
2264 l = plot(bins, y, 'r--', linewidth=2) |
|
2265 xlim(40, 160) |
|
2266 xlabel('Smarts') |
|
2267 ylabel('P') |
|
2268 title(r'$\rm{IQ:}\/ \mu=100,\/ \sigma=15$') |
|
2269 \end{lstlisting} |
|
2270 \end{block} |
|
2271 \end{columns} |
|
2272 \end{frame} |
|
2273 |
|
2274 \begin{frame}[fragile] \frametitle{Bar charts} |
|
2275 \begin{columns} |
|
2276 \column{0.5\textwidth} |
|
2277 \hspace*{-0.5in} |
|
2278 \includegraphics[height=2in, interpolate=true]{data/barchart} |
|
2279 \column{0.45\textwidth} |
|
2280 \begin{block}{Example code} |
|
2281 \tiny |
|
2282 \begin{lstlisting} |
|
2283 N = 5 |
|
2284 menMeans = (20, 35, 30, 35, 27) |
|
2285 menStd = ( 2, 3, 4, 1, 2) |
|
2286 # the x locations for the groups |
|
2287 ind = arange(N) |
|
2288 # the width of the bars |
|
2289 width = 0.35 |
|
2290 p1 = bar(ind, menMeans, width, |
|
2291 color='r', yerr=menStd) |
|
2292 womenMeans = (25, 32, 34, 20, 25) |
|
2293 womenStd = ( 3, 5, 2, 3, 3) |
|
2294 p2 = bar(ind+width, womenMeans, width, |
|
2295 color='y', yerr=womenStd) |
|
2296 ylabel('Scores') |
|
2297 title('Scores by group and gender') |
|
2298 xticks(ind+width, |
|
2299 ('G1', 'G2', 'G3', 'G4', 'G5')) |
|
2300 xlim(-width,len(ind)) |
|
2301 yticks(arange(0,41,10)) |
|
2302 legend((p1[0], p2[0]), |
|
2303 ('Men', 'Women'), shadow=True) |
|
2304 \end{lstlisting} |
|
2305 \end{block} |
|
2306 \end{columns} |
|
2307 \end{frame} |
|
2308 |
|
2309 \begin{frame}[fragile] \frametitle{Pie charts} |
|
2310 \begin{columns} |
|
2311 \column{0.5\textwidth} |
|
2312 \hspace*{-0.4in} |
|
2313 \includegraphics[height=2.0in, interpolate=true]{data/piechart} |
|
2314 \column{0.45\textwidth} |
|
2315 \begin{block}{Example code} |
|
2316 \tiny |
|
2317 \begin{lstlisting} |
|
2318 # make a square figure and axes |
|
2319 figure(1, figsize=(8,8)) |
|
2320 ax = axes([0.1, 0.1, 0.8, 0.8]) |
|
2321 labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' |
|
2322 fracs = [15,30,45, 10] |
|
2323 explode=(0, 0.05, 0, 0) |
|
2324 pie(fracs, explode=explode, labels=labels, |
|
2325 autopct='%1.1f%%', shadow=True) |
|
2326 title('Raining Hogs and Dogs', |
|
2327 bbox={'facecolor':'0.8', 'pad':5}) |
|
2328 \end{lstlisting} |
|
2329 \end{block} |
|
2330 \end{columns} |
|
2331 \end{frame} |
|
2332 |
|
2333 \begin{frame}[fragile] \frametitle{Scatter plots} |
|
2334 \begin{columns} |
|
2335 \column{0.5\textwidth} |
|
2336 \hspace*{-0.4in} |
|
2337 \includegraphics[height=2in, interpolate=true]{data/scatter} |
|
2338 \column{0.45\textwidth} |
|
2339 \begin{block}{Example code} |
|
2340 \tiny |
|
2341 \begin{lstlisting} |
|
2342 N = 30 |
|
2343 x = 0.9*rand(N) |
|
2344 y = 0.9*rand(N) |
|
2345 # 0 to 10 point radiuses |
|
2346 area = pi*(10 * rand(N))**2 |
|
2347 volume = 400 + rand(N)*450 |
|
2348 scatter(x,y,s=area, marker='o', c=volume, |
|
2349 alpha=0.75) |
|
2350 xlabel(r'$\Delta_i$', size='x-large') |
|
2351 ylabel(r'$\Delta_{i+1}$', size='x-large') |
|
2352 title(r'Volume and percent change') |
|
2353 grid(True) |
|
2354 colorbar() |
|
2355 savefig('scatter') |
|
2356 \end{lstlisting} |
|
2357 \end{block} |
|
2358 \end{columns} |
|
2359 \end{frame} |
|
2360 |
|
2361 \begin{frame}[fragile] \frametitle{Polar} |
|
2362 \begin{columns} |
|
2363 \column{0.5\textwidth} |
|
2364 \hspace*{-0.5in} |
|
2365 \includegraphics[height=2in, interpolate=true]{data/polar} |
|
2366 \column{0.45\textwidth} |
|
2367 \begin{block}{Example code} |
|
2368 \tiny |
|
2369 \begin{lstlisting} |
|
2370 figure(figsize=(8,8)) |
|
2371 ax = axes([0.1, 0.1, 0.8, 0.8], polar=True, |
|
2372 axisbg='#d5de9c') |
|
2373 r = arange(0,1,0.001) |
|
2374 theta = 2*2*pi*r |
|
2375 polar(theta, r, color='#ee8d18', lw=3) |
|
2376 # the radius of the grid labels |
|
2377 setp(ax.thetagridlabels, y=1.075) |
|
2378 title(r"$\theta=4\pi r", fontsize=20) |
|
2379 \end{lstlisting} |
|
2380 \end{block} |
|
2381 \end{columns} |
|
2382 \end{frame} |
|
2383 |
|
2384 \begin{frame}[fragile] \frametitle{Contours} |
|
2385 \begin{columns} |
|
2386 \column{0.45\textwidth} |
|
2387 \hspace*{-0.5in} |
|
2388 \includegraphics[height=2in, interpolate=true]{data/contour} |
|
2389 \column{0.525\textwidth} |
|
2390 \begin{block}{Example code} |
|
2391 \tiny |
|
2392 \begin{lstlisting} |
|
2393 x = arange(-3.0, 3.0, 0.025) |
|
2394 y = arange(-2.0, 2.0, 0.025) |
|
2395 X, Y = meshgrid(x, y) |
|
2396 Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) |
|
2397 Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1) |
|
2398 # difference of Gaussians |
|
2399 Z = 10.0 * (Z2 - Z1) |
|
2400 im = imshow(Z, interpolation='bilinear', |
|
2401 origin='lower', |
|
2402 cmap=cm.gray, extent=(-3,3,-2,2)) |
|
2403 levels = arange(-1.2, 1.6, 0.2) |
|
2404 # label every second level |
|
2405 clabel(CS, levels[1::2], inline=1, |
|
2406 fmt='%1.1f', fontsize=14) |
|
2407 CS = contour(Z, levels, |
|
2408 origin='lower', |
|
2409 linewidths=2, |
|
2410 extent=(-3,3,-2,2)) |
|
2411 # make a colorbar for the contour lines |
|
2412 CB = colorbar(CS, shrink=0.8, extend='both') |
|
2413 title('Lines with colorbar') |
|
2414 hot(); flag() |
|
2415 \end{lstlisting} |
|
2416 \end{block} |
|
2417 \end{columns} |
|
2418 \end{frame} |
|
2419 |
|
2420 \begin{frame}[fragile] \frametitle{Velocity vectors} |
|
2421 \begin{columns} |
|
2422 \column{0.5\textwidth} |
|
2423 \hspace*{-0.5in} |
|
2424 \includegraphics[height=2in, interpolate=true]{data/quiver} |
|
2425 \column{0.45\textwidth} |
|
2426 \begin{block}{Example code} |
|
2427 \tiny |
|
2428 \begin{lstlisting} |
|
2429 X,Y = meshgrid(arange(0,2*pi,.2), |
|
2430 arange(0,2*pi,.2) ) |
|
2431 U = cos(X) |
|
2432 V = sin(Y) |
|
2433 Q = quiver(X[::3, ::3], Y[::3, ::3], |
|
2434 U[::3, ::3], V[::3, ::3], |
|
2435 color='r', units='x', |
|
2436 linewidths=(2,), |
|
2437 edgecolors=('k'), |
|
2438 headaxislength=5 ) |
|
2439 qk = quiverkey(Q, 0.5, 0.03, 1, '1 m/s', |
|
2440 fontproperties= |
|
2441 {'weight': 'bold'}) |
|
2442 axis([-1, 7, -1, 7]) |
|
2443 title('triangular head; scale '\ |
|
2444 'with x view; black edges') |
|
2445 \end{lstlisting} |
|
2446 \end{block} |
|
2447 \end{columns} |
|
2448 \end{frame} |
|
2449 |
|
2450 \begin{frame}[fragile] \frametitle{Maps} |
|
2451 \includegraphics[height=2.5in, interpolate=true]{data/plotmap} |
|
2452 \begin{center} |
|
2453 \tiny |
|
2454 For details see \url{http://matplotlib.sourceforge.net/screenshots/plotmap.py} |
|
2455 \end{center} |
|
2456 \end{frame} |
|
2457 |
|
2458 |
|
2459 \subsection{SciPy} |
|
2460 |
|
2461 \begin{frame} |
|
2462 \frametitle{Using \texttt{SciPy}} |
|
2463 \begin{itemize} |
|
2464 \item SciPy is Open Source software for mathematics, science, and |
|
2465 engineering |
|
2466 \item \typ{import scipy} |
|
2467 \item Built on NumPy |
|
2468 \item Provides modules for statistics, optimization, integration, |
|
2469 linear algebra, Fourier transforms, signal and image processing, |
|
2470 genetic algorithms, ODE solvers, special functions, and more |
|
2471 \item Used widely by scientists world over |
|
2472 \item Details are beyond the scope of this tutorial |
|
2473 \end{itemize} |
|
2474 \end{frame} |
|
2475 |
|
2476 \section{Standard library} |
|
2477 |
|
2478 \subsection{Quick Tour} |
|
2479 |
|
2480 \begin{frame} |
|
2481 \frametitle{Standard library} |
|
2482 \begin{itemize} |
|
2483 \item Very powerful |
|
2484 \item ``Batteries included'' |
|
2485 \item Example standard modules taken from the tutorial |
|
2486 \begin{itemize} |
|
2487 \item Operating system interface: \typ{os} |
|
2488 \item System, Command line arguments: \typ{sys} |
|
2489 \item Regular expressions: \typ{re} |
|
2490 \item Math: \typ{math}, \typ{random} |
|
2491 \item Internet access: \typ{urllib2}, \typ{smtplib} |
|
2492 \item Data compression: \typ{zlib}, \typ{gzip}, \typ{bz2}, |
|
2493 \typ{zipfile}, and \typ{tarfile} |
|
2494 \item Unit testing: \typ{doctest} and \typ{unittest} |
|
2495 \item And a whole lot more! |
|
2496 \end{itemize} |
|
2497 \item Check out the Python Library reference: |
|
2498 \url{http://docs.python.org/lib/lib.html} |
|
2499 \end{itemize} |
|
2500 \end{frame} |
|
2501 |
|
2502 \begin{frame}[fragile] |
|
2503 \frametitle{Stdlib: examples} |
|
2504 \begin{lstlisting} |
|
2505 >>> import os |
|
2506 >>> os.system('date') |
|
2507 Fri Jun 10 22:13:09 IST 2005 |
|
2508 0 |
|
2509 >>> os.getcwd() |
|
2510 '/home/prabhu' |
|
2511 >>> os.chdir('/tmp') |
|
2512 >>> import os |
|
2513 >>> dir(os) |
|
2514 <returns a list of all module functions> |
|
2515 >>> help(os) |
|
2516 <extensive manual page from module's docstrings> |
|
2517 \end{lstlisting} |
|
2518 \end{frame} |
|
2519 |
|
2520 \begin{frame}[fragile] |
|
2521 \frametitle{Stdlib: examples} |
|
2522 \begin{lstlisting} |
|
2523 >>> import sys |
|
2524 >>> # Print the list of command line args to Python |
|
2525 ... print sys.argv |
|
2526 [''] |
|
2527 >>> import re # Regular expressions |
|
2528 >>> re.findall(r'\bf[a-z]*', |
|
2529 ... 'which foot or hand fell fastest') |
|
2530 ['foot', 'fell', 'fastest'] |
|
2531 >>> re.sub(r'(\b[a-z]+) \1', r'\1', |
|
2532 ... 'cat in the the hat') |
|
2533 'cat in the hat' |
|
2534 \end{lstlisting} |
|
2535 \end{frame} |
|
2536 |
|
2537 \begin{frame}[fragile] |
|
2538 \frametitle{Stdlib: examples} |
|
2539 \begin{lstlisting} |
|
2540 >>> import math |
|
2541 >>> math.cos(math.pi / 4.0) |
|
2542 0.70710678118654757 |
|
2543 >>> math.log(1024, 2) |
|
2544 10.0 |
|
2545 >>> import random |
|
2546 >>> random.choice(['apple', 'pear', 'banana']) |
|
2547 'pear' |
|
2548 \end{lstlisting} |
|
2549 \end{frame} |
|
2550 |
|
2551 \begin{frame}[fragile] |
|
2552 \frametitle{Stdlib: examples} |
|
2553 \begin{lstlisting} |
|
2554 >>> import urllib2 |
|
2555 >>> f = urllib2.urlopen('http://www.python.org/') |
|
2556 >>> print f.read(100) |
|
2557 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> |
|
2558 <?xml-stylesheet href="./css/ht2html |
|
2559 \end{lstlisting} |
|
2560 \end{frame} |
|
2561 |
|
2562 \begin{frame}[fragile] |
|
2563 \frametitle{Stdlib: examples} |
|
2564 \begin{lstlisting} |
|
2565 >>> import zlib |
|
2566 >>> s = 'witch which has which witches wrist watch' |
|
2567 >>> len(s) |
|
2568 41 |
|
2569 >>> t = zlib.compress(s) |
|
2570 >>> len(t) |
|
2571 37 |
|
2572 >>> zlib.decompress(t) |
|
2573 'witch which has which witches wrist watch' |
|
2574 >>> zlib.crc32(t) |
|
2575 -1438085031 |
|
2576 \end{lstlisting} |
|
2577 \end{frame} |
|
2578 |
|
2579 \begin{frame} |
|
2580 \frametitle{Summary} |
|
2581 \begin{itemize} |
|
2582 \item Introduced Python |
|
2583 \item Basic syntax |
|
2584 \item Basic types and data structures |
|
2585 \item Control flow |
|
2586 \item Functions |
|
2587 \item Modules |
|
2588 \item Exceptions |
|
2589 \item Classes |
|
2590 \item Standard library |
|
2591 \end{itemize} |
|
2592 \end{frame} |
|
2593 |
|
2594 \end{document} |
|
2595 |
|
2596 \subsection{Basic data structures} |
|
2597 \begin{frame}{Lists} |
|
2598 \begin{itemize} |
|
2599 \item \texttt{species = [ 'humans', 'orcs', 'elves', 'dwarves' ]} |
|
2600 \item \texttt{ ids = [ 107, 109, 124, 141, 142, 144 ]} |
|
2601 \item \texttt{ oneliners = [ 'I will be back', 'Do or do not! No try!!', 42 ] } |
|
2602 \end{itemize} |
|
2603 |
|
2604 \begin{block}{List operations} |
|
2605 ids + [ 100, 102 ]\\ |
|
2606 species.append( 'unicorns')\\ |
|
2607 print oneliners[ 1 ]\\ |
|
2608 look up \alert{docs.python.org/tutorial/datastructures.html} |
|
2609 \end{block} |
|
2610 \end{frame} |
|
2611 \end{document} |
|
2612 \section{Python Tutorial} |
|
2613 \subsection{Preliminaries} |
|
2614 \begin{frame} |
|
2615 \frametitle{Using the interpreter} |
|
2616 \begin{itemize} |
|
2617 \item Starting up: \typ{python} or \typ{ipython} |
|
2618 \item Quitting: \typ{Control-D} or \typ{Control-Z} (on Win32) |
|
2619 \item Can use it like a calculator |
|
2620 \item Can execute one-liners via the \typ{-c} option: |
|
2621 \typ{python -c "print 'hello world'"} |
|
2622 \item Other options via \typ{python -h} |
|
2623 \end{itemize} |
|
2624 \end{frame} |
|
2625 |
|
2626 \begin{frame} |
|
2627 \frametitle{IPython} |
|
2628 \begin{itemize} |
|
2629 \item Recommended interpreter, IPython: |
|
2630 \url{http://ipython.scipy.org} |
|
2631 \item Better than the default Python shell |
|
2632 \item Supports tab completion by default |
|
2633 \item Easier object introspection |
|
2634 \item Shell access! |
|
2635 \item Command system to allow extending its own behavior |
|
2636 \item Supports history (across sessions) and logging |
|
2637 \item Can be embedded in your own Python code |
|
2638 \item Support for macros |
|
2639 \item A flexible framework for your own custom interpreter |
|
2640 \item Other miscellaneous conveniences |
|
2641 \item We'll get back to this later |
|
2642 \end{itemize} |
|
2643 \end{frame} |
|
2644 |
|
2645 \begin{frame}[fragile] |
|
2646 \frametitle{Basic IPython features} |
|
2647 \begin{itemize} |
|
2648 \item Startup: \verb+ipython [options] files+ |
|
2649 \begin{itemize} |
|
2650 \item \verb+ipython [-wthread|-gthread|-qthread]+: |
|
2651 Threading modes to support wxPython, pyGTK and Qt |
|
2652 \item \verb+ipython -pylab+: Support for matplotlib |
|
2653 \end{itemize} |
|
2654 \item TAB completion: |
|
2655 \begin{itemize} |
|
2656 \item Type \verb+object_name.<TAB>+ to see list of options |
|
2657 \item Also completes on file and directory names |
|
2658 \end{itemize} |
|
2659 \item \verb+object?+ shows docstring/help for any Python object |
|
2660 \item \verb+object??+ presents more docs (and source if possible) |
|
2661 \item Debugging with \verb+%pdb+ magic: pops up pdb on errors |
|
2662 \item Access history (saved over earlier sessions also) |
|
2663 \begin{itemize} |
|
2664 \item Use \texttt{<UpArrow>}: move up history |
|
2665 \item Use \texttt{<Ctrl-r> string}: search history backwards |
|
2666 \item Use \texttt{Esc >}: get back to end of history |
|
2667 \end{itemize} |
|
2668 \item \verb+%run [options] file[.py]+ lets you run Python code |
|
2669 \end{itemize} |
|
2670 \end{frame} |
|
2671 % LocalWords: BDFL Guido Rossum PSF Nokia OO Zope CMS RedHat SciPy MayaVi spam |
|
2672 % LocalWords: IPython ipython stdin TypeError dict int elif PYTHONPATH IOError |
|
2673 % LocalWords: namespace Namespaces SyntaxError ZeroDivisionError NameError str |
|
2674 % LocalWords: ValueError subclassed def |
|
2675 |
|
2676 |
|
2677 \item Types are of two kinds: \alert{mutable} and \alert{immutable} |
|
2678 \item Immutable types: numbers, strings, \typ{None} and tuples |
|
2679 \item Immutables cannot be changed ``in-place'' |
|
2680 \item Mutable types: lists, dictionaries, instances, etc. |
|
2681 \item Mutable objects can be ``changed'' |
|
2682 \end{itemize} |
|
2683 |
|
2684 |
|
2685 \begin{frame} |
|
2686 \frametitle{Important!} |
|
2687 \begin{itemize} |
|
2688 \item Assignment to an object is by reference |
|
2689 \item Essentially, \alert{names are bound to objects} |
|
2690 \end{itemize} |
|
2691 \end{frame} |
|
2692 |
|
2693 |
|
2694 \end{document} |
|
2695 \begin{frame}[fragile] |
|
2696 \frametitle{Dictionaries} |
|
2697 \begin{itemize} |
|
2698 \item Associative arrays/mappings |
|
2699 \item Indexed by ``keys'' (keys must be immutable) |
|
2700 \item \typ{dict[key] = value} |
|
2701 \item \typ{keys()} returns all keys of the dict |
|
2702 \item \typ{values()} returns the values of the dict |
|
2703 \item \verb+has_key(key)+ returns if \typ{key} is in the dict |
|
2704 \end{itemize} |
|
2705 \end{frame} |
|
2706 |
|
2707 \begin{frame}[fragile] |
|
2708 \frametitle{Dictionaries: example} |
|
2709 \begin{lstlisting} |
|
2710 >>> tel = {'jack': 4098, 'sape': 4139} |
|
2711 >>> tel['guido'] = 4127 |
|
2712 >>> tel |
|
2713 {'sape': 4139, 'guido': 4127, 'jack': 4098} |
|
2714 >>> tel['jack'] |
|
2715 4098 |
|
2716 >>> del tel['sape'] |
|
2717 >>> tel['irv'] = 4127 |
|
2718 >>> tel |
|
2719 {'guido': 4127, 'irv': 4127, 'jack': 4098} |
|
2720 >>> tel.keys() |
|
2721 ['guido', 'irv', 'jack'] |
|
2722 >>> tel.has_key('guido') |
|
2723 True |
|
2724 \end{lstlisting} |
|
2725 \end{frame} |
|
2726 |
|
2727 \subsection{Control flow, functions} |
|
2728 |
|
2729 |
|
2730 |
|
2731 \begin{frame}[fragile] |
|
2732 \frametitle{\typ{If} example} |
|
2733 \begin{lstlisting} |
|
2734 >>> a = ['cat', 'window', 'defenestrate'] |
|
2735 >>> if 'cat' in a: |
|
2736 ... print "meaw" |
|
2737 ... |
|
2738 meaw |
|
2739 >>> pets = {'cat': 1, 'dog':2, 'croc': 10} |
|
2740 >>> if 'croc' in pets: |
|
2741 ... print pets['croc'] |
|
2742 ... |
|
2743 10 |
|
2744 \end{lstlisting} |
|
2745 \end{frame} |
|
2746 |
|
2747 \begin{frame}[fragile] |
|
2748 \frametitle{\typ{for} example} |
|
2749 \begin{lstlisting} |
|
2750 >>> a = ['cat', 'window', 'defenestrate'] |
|
2751 >>> for x in a: |
|
2752 ... print x, len(x) |
|
2753 ... |
|
2754 cat 3 |
|
2755 window 6 |
|
2756 defenestrate 12 |
|
2757 >>> knights = {'gallahad': 'the pure', |
|
2758 ... 'robin': 'the brave'} |
|
2759 >>> for k, v in knights.iteritems(): |
|
2760 ... print k, v |
|
2761 ... |
|
2762 gallahad the pure |
|
2763 robin the brave |
|
2764 \end{lstlisting} |
|
2765 \end{frame} |
|