Download presentation
Presentation is loading. Please wait.
Published byMartin Roberts Modified over 8 years ago
1
Quiz 4 Topics Aid sheet is supplied with quiz. Functions, loops, conditionals, lists – STILL. New topics: –Default and Keyword Arguments. –Sets. –Strings. –Raising Exceptions. –Passing by Reference. –Dictionaries. os, sys, urllib.request and exec() BIF not on quiz. Winter 2016CISC101 - Prof. McLeod1
2
Today… Lists of lists. Start Algorithms: –Finding extremes. –Timing and comparing code execution. Winter 2016CISC101 - Prof. McLeod2
3
3 Lists of Lists We know a list can hold anything, and the elements do not even have to be of all the same type: ex1 = [1, 4.0, ‘abc’, 2, ‘hello!’] So, there is no reason that an element cannot be another list (or a tuple, or a dictionary). ex2 = [4.5, [1, 2, ‘abc’], 7, ‘hello’] Winter 2016
4
CISC101 - Prof. McLeod4 Lists of Lists, Cont. For example: >>> for value in ex2: print(value) 4.5 [1, 2, 'abc'] 7 hello Winter 2016
5
CISC101 - Prof. McLeod5 Lists of Lists, Cont. How can I display the elements in the list at position 1?: >>> for value in ex2[1]: print(value) 1 2 abc Winter 2016
6
CISC101 - Prof. McLeod6 Lists of Lists, Cont. Nothing new! How do I access just the 'abc' string inside the list at position 1?: >>> ex2[1][2] = 'wxyz' >>> ex2 [4.5, [1, 2, 'wxyz'], 7, 'hello'] Winter 2016
7
CISC101 - Prof. McLeod7 Lists of Lists, Cont. So, a list of lists can be used represent tabular data: ex3 = [['Sam', 18, 4445555], ['Boris', 21, 5554444], ['Ben', 19, 5445444]] You could do it this way, or (better yet) use a dictionary. Winter 2016 Sam184445555 Boris215554444 Ben195445444
8
Lists of Lists, Cont. Don’t forget that list locations are index based, so you can use the slice operator. List elements stay where you put them! So, while you cannot control the order of key : value pairs within a dictionary, you can control the position of dictionaries within a list. Winter 2016CISC101 - Prof. McLeod8
9
Algorithms – Finding Min and Max Values Let’s take a break from Python syntax for a while! Instead – use Python code to explore various useful algorithms. Make comparisons based on ease of coding, flexibility and efficiency (speed!). CISC101 - Prof. McLeod9Winter 2016
10
What is an Algorithm? An algorithm is a set of instructions to solve a particular problem. A computing algorithm can be expressed in code. In any language, including Python! We are going to learn some simple algorithms that every programmer should know. Focus on Searching and Sorting algorithms. (Avoid recursive algorithms.) CISC101 - Prof. McLeod10Winter 2016
11
CISC101 - Prof. McLeod11 Finding Min’s, Max’s and Sums Naturally Python has BIFs for this! min(), max() and sum() Used as min(iter, key=None), or min(arg0, arg1, arg2, …, key=None), and sum(iter[, start]) iter is a list or tuple (or string) (Optional key can point to a function that can be used to determine the order of the elements. We won’t use this.) Winter 2016
12
CISC101 - Prof. McLeod12 Finding Min’s and Max’s, Cont. Sometimes you have to do this yourself. (And sometimes your version will work better!) A function that returns the minimum of a simple list: def findMin(aList): min = aList[0] i = 1 while i < len(aList) : if aList[i] < min : min = aList[i] i = i + 1 return min Winter 2016
13
CISC101 - Prof. McLeod13 Finding Min’s and Max’s, Cont. Maybe you want to know the position of the minimum, not the value. Could you use a for loop instead? Would it be safe to say min = 0 ? See FindMinMaxSumDemo.py Winter 2016
14
Finding Min’s and Max’s, Cont. Note how the functions work with lists of other types. And, note that the built-in sum() works only with lists of numbers – we can modify our sum to work with the other list types. CISC101 - Prof. McLeod14Winter 2016
15
CISC101 - Prof. McLeod15 Finding Min’s and Max’s, Cont. Suppose your list has a mix of types: >>> test = [1, 2, 'abc', 3] >>> sum(test) Traceback (most recent call last): File " ", line 1, in sum(test) TypeError: unsupported operand type(s) for +: 'int' and 'str' >>> min(test) Traceback (most recent call last): File " ", line 1, in min(test) TypeError: unorderable types: str() < int() Winter 2016
16
CISC101 - Prof. McLeod16 Finding Min’s and Max’s, Cont. Hmmmm… If we did this ourselves we could use isinstance() to check types before comparing or summing elements! Winter 2016
17
Summary Finding minimums, maximums and making sums are all very similar algorithms. Python has BIFs for these since they are so often used. Writing our own versions allows us to add flexibility to how the code works. Is our code as fast as the BIF version? CISC101 - Prof. McLeod17Winter 2016
18
Comparing Code Efficiency We are always concerned about making code easily read, repaired and modified. That’s just good style. But we are also concerned about making code efficient. Two measures of interest: memory use and time of execution. CISC101 - Prof. McLeod18Winter 2016
19
Execution Time Code runs very quickly on modern computers. But, sometimes it needs to be faster! (In CISC121). You can make a theoretical analysis of code to predict what algorithm may be faster. Or, You can just measure execution speeds. (In CISC101!) CISC101 - Prof. McLeod19Winter 2016
20
How to Measure Execution Time? One way is to use the clock() function from the time module. It returns the number of seconds elapsed from the first time the function is invoked. We won’t care about the absolute value from the function, we just want the relative change to get the time elapsed by a particular function call. CISC101 - Prof. McLeod20Winter 2016
21
CISC101 - Prof. McLeod21 Timing Code Execution, Cont. So, just for fun, let’s compare our findMax to the max() BIF. First we will have to enlarge the list so that it will take enough time to measure. We can fill it with random numbers as “fodder”. See TimingFindMaxDemo.py. Which one is slower? Can we speed up our findMax() function? Note how timings change from one run to the next. Winter 2016
22
Results These times will depend on other factors such as your microprocessor speed and type as well as your operating system. But, the relative order of the results should not change. BIF max() function0.36 milliseconds Original findMax2.4 msec Original findMax, ver 21.8 msec For loop findMax1.0 msec For loop findMax, ver 20.5 msec CISC101 - Prof. McLeod22Winter 2016
23
findMax() Versions “Original” is the one shown in the previous demo. “Original, ver 2” – the len() BIF call is moved outside the loop. “For loop” – a for loop with the range() BIF “For loop, ver 2” – a simple for loop – the best version we could code! The max() BIF is still a bit faster. Our code is interpreted. The max() BIF is probably already in machine language is some library. Tough to compete with this! CISC101 - Prof. McLeod23Winter 2016
24
Timing Code Execution, Cont. Why is the for loop much faster than the while loop? (Good to know!) Note that the BIF is a bit slower the first time it is called and faster thereafter. CISC101 - Prof. McLeod24Winter 2016
25
Summary Execution time is an important measure of the efficiency of our code. We might not always notice, but sometimes execution speed is the bottleneck of a program and it is worth knowing what can be done to speed things up! Many BIFs exist as binary executable code in dynamic link libraries (*.dll files). This makes them execute as quickly as possible. CISC101 - Prof. McLeod25Winter 2016
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.