Presentation is loading. Please wait.

Presentation is loading. Please wait.

COMPSCI 107 Computer Science Fundamentals

Similar presentations


Presentation on theme: "COMPSCI 107 Computer Science Fundamentals"— Presentation transcript:

1 COMPSCI 107 Computer Science Fundamentals
Lecture 06 Tuples Reading and Writing Text Files Dictionaries

2 Learning outcomes At the end of this lecture, students should be able to: Assign tuples to variables Pass tuples are parameter and return values Access elements of tuples Read text files Write text files Create dictionaries Obtain values associated with keys in a dictionary Iterate through views of a dictionary COMPSCI Computer Science Fundamentals

3 Tuples A tuple is a sequence, much like a list A tuple is immutable
Enclosed in brackets (x, y) >>> point = (1, 2) >>> point (1, 2) >>> point[0] 1 >>> point + (3, 4) (1, 2, 3, 4) COMPSCI Computer Science Fundamentals

4 Returning multiple values
def translate(point, vector): """Translate a point by a given vector Arguments: point – a tuple representing an (x, y) point on the cartesian plane vector – a tuple representing a translation of (dx, dy) on the cartesian plane >>> translate((0, 0), (4, 5)) (4, 5) """ x = point[0] + vector[0] y = point[1] + vector[1] return (x, y) >>> new_x, new_y = translate((1, 2), (3, 4)) COMPSCI Computer Science Fundamentals

5 Exercise: Difference between two points
Write a function that calculates the difference between two points and returns a vector (dx, dy) to translate from one to the other. dx) (x1, y1) dy (x2, y2) COMPSCI Computer Science Fundamentals

6 Reading a file Get a reference to the file on disk Modes
open(filename, mode) Modes ‘r’ = read ‘w’ = write ‘r+’ = read and write Default is text mode, append ‘b’ for binary f = open(filename) f = open(filename, 'r') f = open(filename, 'wb') COMPSCI Computer Science Fundamentals

7 Reading a text file Different ways to read the contents of the file
When the end of file is reached, empty string is returned f.read() # returns the entire file as a string f.readlines() # returns a list of lines (strings) from the file f.readline() # returns a single line (string) from the file for line in f: print(line) #do something with the line COMPSCI Computer Science Fundamentals

8 Reading data from a file
def read_data(filename): '''Reads data from a file Given the name of a file, reads all the data from a file and return the data as a list where each element in the list is a single piece of datum from the file. test2.txt contains the text: This is a small test file with a few words. >>> read_data('test2.txt') ['This', 'is', 'a', 'small', 'test', 'file', 'with', 'a', 'few', 'words.'] ''' f = open(filename) contents = f.read() data = contents.split() return data COMPSCI Computer Science Fundamentals

9 Reading numbers from file
Read data as text Convert text to number Functions that change types int() float() str() for line in f: number = int(line) #one value per line COMPSCI Computer Science Fundamentals

10 Exercise Write a function that returns the word count for a text file.
Write a function that returns the number of unique words in a text file (where words are defined as a sequence of characters separated by white space). COMPSCI Computer Science Fundamentals

11 Writing data to a file Similar to reading data Write all the data
Close the file after all the data is written. f.write( string_to_write ) f.close() COMPSCI Computer Science Fundamentals

12 Exercise Write a function called word_list that accepts the name of a text file as an argument and produces a list of all the words in that file, sorted in order with one word per line. COMPSCI Computer Science Fundamentals

13 Dictionary An unordered set of key : value pairs
keys must be unique (within a given dictionary) keys must be immutable my_dict = { 'alux001' : 'Andrew', 'afer023' : 'Adriana', 'rshe001' : 'Robert' } >>> my_dict['alux001'] 'Andrew' >>> my_dict['rshe001'] 'Robert' >>> my_dict['afer023'] 'Adriana' COMPSCI Computer Science Fundamentals

14 Adding entries to a dictionary
Variables are created when you assign a value for the first time Assigning a value to a new dictionary entry creates that entry Assigning a value to an existing dictionary entry changes that entry my_dict = {} my_dict['alux001'] = 'Andrew' my_dict['rshe001'] = 'Robert' my_dict['afer023'] = 'Adriana' my_dict['alux001'] = 'Andrew Luxton-Reilly' COMPSCI Computer Science Fundamentals

15 Deleting an element from a dictionary
Use the del operator Use the pop method del my_dict['alux001'] my_dict.pop('alux001') COMPSCI Computer Science Fundamentals

16 Iterating through the dictionary
Order of items in a dictionary is undefined Can get a "view" of the keys, values, or (key, value) pairs Can iterate through the "view" Views are dynamic, so they change when the dictionary changes for k in my_dict.keys(): print(k) for v in my_dict.values(): print(v) for i in my_dict.items(): print(i) COMPSCI Computer Science Fundamentals

17 Getting a value from the dictionary
Get a value associated with a given key Use the index, use get, or use get with default value >>> my_dict['alux001'] 'Andrew' >>> my_dict['ALUX999'] KeyError: 'ALUX999' >>> my_dict.get('alux001') 'Andrew' >>> my_dict.get('ALUX999') >>> >>> my_dict.get('alux001', 'Not valid') 'Andrew' >>> my_dict.get('ALUX999', 'Not valid') 'Not valid' COMPSCI Computer Science Fundamentals

18 Example: Sparse Matrix
A sparse matrix is a matrix with few non-zero values. The most obvious way to represent the matrix is a list of lists: matrix = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 3, 0, 0, 0], [0, 0, 7, 0, 0, 0, 4], [0, 0, 0, 0, 0, 2, 0] ] COMPSCI Computer Science Fundamentals

19 Example: Sparse matrix
Alternative implementation Use a dictionary Use the location as the key Store location as a tuple (x, y) matrix = { (1, 1) : 1, (2, 3) : 7, (3, 2) : 3, (5, 4) : 2, (6, 3) : 4 } COMPSCI Computer Science Fundamentals

20 Accessing the sparse matrix
Use the location (x, y) as the index Use the location (x, y) as the index, but use a default value matrix = { (1, 1) : 1, (2, 3) : 7, (3, 2) : 3, (5, 4) : 2, (6, 3) : 4 } >>> matrix[(3, 2)] 3 >>> matrix[(0, 0)] KeyError: (0, 0) >>> matrix.get((4, 3), 0) COMPSCI Computer Science Fundamentals

21 Summary Files need to be opened before you can read or write to them
f = open( filename[, mode] ) Files should be closed when you finish with them. f.close() Reading text from a file f.read() f.readline() Writing text to a file f.write( string ) COMPSCI Computer Science Fundamentals

22 Summary Dictionaries are also known as associative arrays or hash tables Consist of key : value pairs keys must be immutable Syntax is {a : b, c : d, …} Adding an item d[key] = value Deleting an item d.pop(key) Getting an item d.get(key, default) COMPSCI Computer Science Fundamentals


Download ppt "COMPSCI 107 Computer Science Fundamentals"

Similar presentations


Ads by Google