COMPSCI 107 Computer Science Fundamentals

Slides:



Advertisements
Similar presentations
Lecture 07 – Iterating through a list of numbers.
Advertisements

Lecture 04 – Classes.  Python has a number of classes built-in  lists, dictionaries, sets, int, float, boolean, strings  We can define our own classes.
Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
Python Dictionary.
Lecture 05 – Dictionaries.  Consider the following methods of sorting information in a sequence. What is the output produced by each program? 2COMPSCI.
Lecture 03 – Sequences of data.  At the end of this lecture, students should be able to:  Define and use functions  Import functions from modules 
COMPSCI 101 Principles of Programming Lecture 24 – Using dictionaries to manage a small file of information.
C++ for Engineers and Scientists Third Edition
Lecture 23 – Python dictionaries 1 COMPSCI 101 Principles of Programming.
Python Programming Chapter 10: Dictionaries Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Lecture 16 – Open, read, write and close files.  At the end of this lecture, students should be able to:  understand file structure  open and close.
Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group.
Introduction. 2COMPSCI Computer Science Fundamentals.
Lecture 06 – Reading and Writing Text Files.  At the end of this lecture, students should be able to:  Read text files  Write text files  Example.
Lecture 21 - Tuples COMPSCI 101 Principles of Programming.
Built-in Data Structures in Python An Introduction.
Daniel Jung. Types of Data Structures  Lists Stacks Queues  Tuples  Sets  Dictionaries.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 Dictionaries and Sets.
Tuples and Dictionaries Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
Lists COMPSCI 105 S Principles of Computer Science.
FILES. open() The open() function takes a filename and path as input and returns a file object. file object = open(file_name [, access_mode][, buffering])
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
Dictionaries Intro to Computer Science CS 1510 Dr. Sarah Diesburg.
Data Abstraction UW CSE 160 Spring What is a program? – A sequence of instructions to achieve some particular purpose What is a library? – A collection.
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
String and Lists Dr. José M. Reyes Álamo.
COMPSCI 107 Computer Science Fundamentals
10 - Python Dictionary John R. Woodward.
Python Variable Types.
Topics Dictionaries Sets Serializing Objects. Topics Dictionaries Sets Serializing Objects.
Python – May 18 Quiz Relatives of the list: Tuple Dictionary Set
COMPSCI 107 Computer Science Fundamentals
CMSC201 Computer Science I for Majors Lecture 17 – Dictionaries
CMSC201 Computer Science I for Majors Lecture 21 – Dictionaries
When to use Tuples instead of Lists
Containers and Lists CIS 40 – Introduction to Programming in Python
CSc 120 Introduction to Computer Programing II
Department of Computer Science,
Python’s input and output
Lecture 10 Data Collections
JavaScript: Functions.
Introduction to Python
CMSC201 Computer Science I for Majors Lecture 20 – Dictionaries
Intro to Computer Science CS 1510 Dr. Sarah Diesburg
Lecture 13 Input/Output Files.
Introduction to Python
Topics Introduction to File Input and Output
Intro to Computer Science CS 1510 Dr. Sarah Diesburg
CS190/295 Programming in Python for Life Sciences: Lecture 6
4. sequence data type Rocky K. C. Chang 16 September 2018
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Topics Dictionaries Sets Serializing Objects. Topics Dictionaries Sets Serializing Objects.
Dictionaries Dictionary: object that stores a collection of data
Files Handling In today’s lesson we will look at:
Fundamentals of Python: First Programs
Python Primer 1: Types and Operators
JavaScript: Arrays.
15-110: Principles of Computing
Topics Introduction to File Input and Output
CISC101 Reminders Assignment 2 due today.
CHAPTER 4: Lists, Tuples and Dictionaries
15-110: Principles of Computing
CSE 231 Lab 8.
Winter 2019 CISC101 5/26/2019 CISC101 Reminders
Topics Introduction to File Input and Output
Introduction to Python
CMSC201 Computer Science I for Majors Lecture 19 – Dictionaries
Dictionary.
Introduction to Computer Science
Presentation transcript:

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

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 107 - Computer Science Fundamentals

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 107 - Computer Science Fundamentals

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 107 - Computer Science Fundamentals

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 107 - Computer Science Fundamentals

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 107 - Computer Science Fundamentals

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 107 - Computer Science Fundamentals

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 107 - Computer Science Fundamentals

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 107 - Computer Science Fundamentals

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 107 - Computer Science Fundamentals

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 107 - Computer Science Fundamentals

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 107 - Computer Science Fundamentals

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 107 - Computer Science Fundamentals

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 107 - Computer Science Fundamentals

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

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 107 - Computer Science Fundamentals

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 107 - Computer Science Fundamentals

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: 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 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 107 - Computer Science Fundamentals

Example: Sparse matrix Alternative implementation Use a dictionary Use the location as the key Store location as a tuple (x, y) 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 matrix = { (1, 1) : 1, (2, 3) : 7, (3, 2) : 3, (5, 4) : 2, (6, 3) : 4 } COMPSCI 107 - Computer Science Fundamentals

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 107 - Computer Science Fundamentals

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 107 - Computer Science Fundamentals

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 107 - Computer Science Fundamentals