Presentation is loading. Please wait.

Presentation is loading. Please wait.

Winter 2019 CISC101 4/29/2019 CISC101 Reminders

Similar presentations


Presentation on theme: "Winter 2019 CISC101 4/29/2019 CISC101 Reminders"— Presentation transcript:

1 Winter 2019 CISC101 4/29/2019 CISC101 Reminders Assignment 3 due next Friday. The next few lectures will focus on what you need to know for this assignment. Winter 2019 CISC101 - Prof. McLeod Prof. Alan McLeod

2 Winter 2019 CISC101 4/29/2019 Today Assignment 3 Topics. For assignment 3 you will build a real spell checker program. Sets. Text File Input/Output. Start Exceptions, if we have time. Winter 2019 CISC101 - Prof. McLeod Prof. Alan McLeod

3 Assn 3 Topics Read a text file into a list.
Use the slice operator with strings. Build lists using the .append() method. Combine lists together (using +). Use set methods .intersection() and .difference(). Use len() BIF with lists and sets. Use in keyword to search sets or lists. Build functions! Winter 2019 CISC101 - Prof. McLeod

4 Assn 3 Topics, Cont. The assignment tells you:
What you need to know to use sets (but we’ll cover them in class, anyways…). What functions you need to write. However, you will need to figure out what arguments the functions need and what they need to return. Winter 2019 CISC101 - Prof. McLeod

5 Assn 3 Topics, Cont. We still need to cover: Sets. Text File Input.
Building Functions. Winter 2019 CISC101 - Prof. McLeod

6 Sets One of the Python collection types.
Makes your work in Assn 3 much easier! See section 5.4 in the Python Tutorial and look at “Set Types” in the “Built-in Types” section in the Python Standard Library. Focus on just those aspects of a set collection that you need for the assignment. Winter 2019 CISC101 - Prof. McLeod

7 Mathematical Set Operations
Set Union operation: Set Intersection operation: All elements from both sets. Duplicates are eliminated. Just elements that are common to both sets. Winter 2019 CISC101 - Prof. McLeod

8 Mathematical Set Operations, Cont.
Set Difference operation: There are other operations, but these are the most common ones. The assignment makes the most use of Intersection, but Difference might also be useful. The elements from set “A” that are not in set “B”. Winter 2019 CISC101 - Prof. McLeod

9 Sets, Cont. Suppose you have a set of candidate words and you have the dictionary of words as a set: In order to find out which of the candidate words are actually words, carry out an Intersection operation. If you have a set of the high probability words and a set of the low probability words carry out a Difference to eliminate the words from the other set that are the same. Winter 2019 CISC101 - Prof. McLeod

10 Sets in Python A set is mutable (use frozenset if you want an immutable set). Use the set() BIF to create a set from a list. Duplicates will be eliminated. A set can contain a mix of numbers and strings. A set is hashed, not indexed. So the slice operator and other operations like sorting and indexing will not work. You cannot order set elements. Things like in, len() and the for loop will work (but you don’t need any of these in the assignment). Winter 2019 CISC101 - Prof. McLeod

11 Aside – What is “Hashing”?
Each element in a hashable collection is assigned a numeric value. The numbers will all be different, since each element is different. The numeric value makes it very easy to quickly find out the memory address of where the element is stored. Access to the element is through its hash code, not through its index value. The dictionary collection type is also hashed. Winter 2019 CISC101 - Prof. McLeod

12 Sets in Python, Cont. To carry out an Intersection, invoke the .intersection method and supply the other set as an argument. For the Difference operation, invoke the .difference method. See some sample code on the next slide: Winter 2019 CISC101 - Prof. McLeod

13 Python Set Interpreter Demo
Winter 2019 CISC101 - Prof. McLeod

14 File I/O (“Input/Output”)
CISC101 File I/O (“Input/Output”) Files provide a convenient way to store and re-store to memory larger amounts of data. Use a data structure like a list to store the data in memory. Three kinds of file I/O: Text Binary Random access For simplicity we will concentrate on text I/O in this course. Text files can be read by Notepad, for example. Winter 2019 CISC101 - Prof. McLeod Prof. Alan McLeod

15 file_variable = open(filename, mode)
Text File I/O, Cont. Syntax: file_variable = open(filename, mode) filename is the name of a file in the same folder as your program, as a string. mode is also a string: ‘r’ for reading only ‘w’ for writing only ‘a’ for appending to a file The default mode is ‘r’, if you don’t supply the second argument. Winter 2019 CISC101 - Prof. McLeod

16 Aside - Other File Modes
+ - read and write (same as w+ or a+) rb - binary read wb - binary write ab - binary append rb+ - binary read and write (same as wb+ and ab+) Winter 2019 CISC101 - Prof. McLeod

17 Another Aside - Newline Support
Different OSs (Linux, Mac, Windows) may use different line termination sequences, such as '\n', '\r\n' or '\r'. If you have difficulty reading individual lines, specify the newline sequence using the keyword argument: newline='\n' in the open() BIF. Try different escape sequences, until the file is read properly. Winter 2019 CISC101 - Prof. McLeod

18 Text File Output Warning: if you open an existing file for writing using mode ‘w’, the old file will be overwritten with a new file - all the old contents will be lost. If you want to add to an existing file without erasing the old contents, use the ‘a’ mode for appending. If you do not provide a path, the file is created in the same folder as your program. If you do put a path in the filename, remember to use \\ as your folder delimiter. Winter 2019 CISC101 - Prof. McLeod

19 Text File Output, Cont. To write information to a file, use the write() method: file_variable.write(a_string) Note that the write() method does not add a line terminator to the end of the string, so if you want to write a line, and have the next output go to the next line, you need something like: file_variable.write(a_string + '\n') Winter 2019 CISC101 - Prof. McLeod

20 Text File Output, Cont. Once you are finished writing to the file don’t forget to close the file using: file_variable.close() If you don’t do this, you run the risk of leaving a corrupted file on your hard disk! This method also releases the file resource back to the OS. Winter 2019 CISC101 - Prof. McLeod

21 Sequential File Access
Text file I/O uses sequential access. Think of having a little “pointer” in the file marking the end of what you have read. As you read (or write), the pointer moves ahead. The pointer cannot move backwards. The only way to re-read something is to close the file and open it again - this moves the “pointer” back to the beginning. start end Winter 2019 CISC101 - Prof. McLeod

22 Aside - Random File Access
This can be used only with binary files: Seek a certain byte location in the file (you must know the exact structure of the file). Read or write data from this location. Seek again… Winter 2019 CISC101 - Prof. McLeod

23 Text File Input Use the open() method as shown above.
Use the readline() method to read a line (up to and including a linefeed character). This method returns a string. You might wish to use something like the string rstrip() method on the string to remove the linefeed, and any other whitespace at the end of the string. Winter 2019 CISC101 - Prof. McLeod

24 Text File Input, Cont. Other file reading methods:
read() – reads entire file and returns a single string. readlines() – reads entire file and returns a list of lines of text. Winter 2019 CISC101 - Prof. McLeod

25 Text File Input, Cont. Invoke the close() method when you are done reading. A for loop can simplify input, because a file object is iterable: for line in inFile: fileContentsList.append(line.rstrip()) Winter 2019 CISC101 - Prof. McLeod

26 File Read and Write Errors
Suppose a problem occurs: File does not exist. Folder does not exist. You do not have read or write access in the folder you are attempting to use. Access fails partway through a read or write attempt. What happens and what should we do about it? See FileInput.py Winter 2019 CISC101 - Prof. McLeod

27 File Read and Write Errors, Cont.
How about using a try/except structure to catch the FileNotFoundError exception? See RobustFileInput.py Winter 2019 CISC101 - Prof. McLeod

28 Back To: The .index() List Method
This method returns the index location of the first match to the supplied argument in a list. What does the method do if it cannot find a match? Winter 2019 CISC101 - Prof. McLeod

29 .index() List Method, Cont.
How can you prevent this method from crashing your program? Two possibilities: Use the in keyword to see if the value is in the list at all, then invoke .index to find the location: if 100 in randNums : print(randNums.index(100)) else : print("100 is not in the list!") Winter 2019 CISC101 - Prof. McLeod

30 .index() List Method, Cont.
The problem with this is that it is “costly” – you have to search through the list twice. How about letting the error occur, but prevent it from crashing your program and then allow the program to carry on? This can be done using a try-except construct. Winter 2019 CISC101 - Prof. McLeod

31 CISC101 Exceptions BIFs and methods throw exceptions as a means of indicating that they cannot do their job. Kind of like a temper tantrum! Observed as all that red coloured font when your program crashes: Winter 2019 CISC101 - Prof. McLeod Prof. Alan McLeod

32 What is an Exception? What do you see if you try something like:
print(int("Hello!")) >>> print(int("Hello")) Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> print(int("Hello")) ValueError: invalid literal for int() with base 10: 'Hello' Winter 2019 CISC101 - Prof. McLeod

33 What is an Exception?, Cont.
A syntax error is what you get when your syntax cannot be recognized by the interpreter. All other errors occur when your code is running. An exception is a run-time error. Every run-time error in Python has a name – this is the type of the exception. For a list of exception types see Chapter 5 in the Python Standard Library documentation. The example on the previous slide was a “ValueError” exception. Winter 2019 CISC101 - Prof. McLeod

34 Crash Prevention! Normally an exception is what you see when your program has crashed from a fatal error. Better programs catch exceptions before this happens! Or – they make sure the exception will never occur by checking for error conditions ahead of time! Catching exceptions gives you a chance to fix the problem. You catch exceptions using try-except statements: Winter 2019 CISC101 - Prof. McLeod


Download ppt "Winter 2019 CISC101 4/29/2019 CISC101 Reminders"

Similar presentations


Ads by Google