Tutorial 10 Dictionaries and Classes. Reminder Assignment 09 is due FRIDAY, Dec 4 at 4:00 pm.

Slides:



Advertisements
Similar presentations
Intro to Scala Lists. Scala Lists are always immutable. This means that a list in Scala, once created, will remain the same.
Advertisements

Python Mini-Course University of Oklahoma Department of Psychology Lesson 28 Classes and Methods 6/17/09 Python Mini-Course: Lesson 28 1.
CS 116 Tutorial 2 Functional Abstraction. Reminders Assignment 2 is due this Wednesday at Noon.
Fundamentals of Python: From First Programs Through Data Structures
Python Dictionary.
Dictionaries Last half of Chapter 5. Dictionary A sequence of key-value pairs – Key is usually a string or integer – Value can be any python object There.
Tutorial 10 Dictionaries and Classes. Reminder Assignment 09 is due April 6 at 11:55pm (last day of classes) Next tutorial is on April 6 (Monday)
Working with Numbers in Alice - Converting to integers and to strings - Rounding numbers. - Truncating Numbers Samantha Huerta under the direction of Professor.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
“Everything Else”. Find all substrings We’ve learned how to find the first location of a string in another string with find. What about finding all matches?
Classes 3 COMPSCI 105 S Principles of Computer Science.
The if statement and files. The if statement Do a code block only when something is True if test: print "The expression is true"
Introduction to Python
General Computer Science for Engineers CISC 106 Lecture 02 Dr. John Cavazos Computer and Information Sciences 09/03/2010.
Strings CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
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.
Python Lists and Such CS 4320, SPRING List Functions len(s) is the length of list s s + t is the concatenation of lists s and t s.append(x) adds.
Fall Week 4 CSCI-141 Scott C. Johnson.  Computers can process text as well as numbers ◦ Example: a news agency might want to find all the articles.
If statements while loop for loop
Lecture 131 CS110 Lecture 13 Thursday, March 11, 2004 Announcements –hw5 due tonight –Spring break next week –hw6 due two weeks from tonight Agenda –questions.
Built-in Data Structures in Python An Introduction.
Recap form last time How to do for loops map, filter, reduce Next up: dictionaries.
ICAPRG301A Week 2 Strings and things Charles Babbage Developed the design for the first computer which he called a difference engine, though.
CS116 – Tutorial 11 Reading and Writing Files. Reminder Assignment 10 due July 28 th (Tuesday) 10:00am.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
More about Strings. String Formatting  So far we have used comma separators to print messages  This is fine until our messages become quite complex:
TUTORIAL 8 Generative Recursion. Reminders  Deadline of midterm remark  Assignment 7 due Wed, Mar 18 th.
Strings Mr. Smith AP Computer Science A. What are Strings? Name some of the characteristics of strings: A string is a sequence of characters, such as.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
Compsci 101.2, Fall Plan for October 29 l Review dictionaries and their use  Very efficient, easy to use  Efficiency doesn't matter much for.
Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Eight String Manipulation.
Lecture 09 – Classes.  At the end of this lecture, students should be able to:  Define a new class  Store state information about instances of the.
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])
Maps Nick Mouriski.
Tutorial 9 Iteration. Reminder Assignment 8 is due Wednesday.
CSE 130 : Winter 2009 Programming Languages Lecture 11: What’s in a Name ?
02/03/ Strings Left, Right and Trim. 202/03/2016 Learning Objectives Explain what the Left, Right and Trim functions do.
Lakshit Dhanda. Output Formatting Python has ways to convert any value to a string. 2 Methods repr() – meant to generate representations of values read.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
Introduction to Programming Oliver Hawkins. BACKGROUND TO PROGRAMMING LANGUAGES Introduction to Programming.
CS100 - PYTHON – EXAM 2 REVIEW -ONLY THE VITAL STUFF- PYTHON STRING METHODS, LOOPS, FILES, AND DICTIONARIES.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
13/06/ Strings Left, Right and Trim. 213/06/2016 Learning Objectives Explain what the Left, Right and Trim functions do.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
Lists/Dictionaries. What we are covering Data structure basics Lists Dictionaries Json.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Section06: Sequences Chapter 4 and 5. General Description "Normal" variables x = 19 – The name "x" is associated with a single value Sequence variables:
ENGINEERING 1D04 Tutorial 2. What we’re doing today More on Strings String input Strings as lists String indexing Slice Concatenation and Repetition len()
COMPSCI 107 Computer Science Fundamentals
Working with Collections of Data
CMSC201 Computer Science I for Majors Lecture 17 – Dictionaries
CMSC201 Computer Science I for Majors Lecture 21 – Dictionaries
Containers and Lists CIS 40 – Introduction to Programming in Python
Python’s input and output
Introduction to Programming
CSC 108H: Introduction to Computer Programming
Engineering Innovation Center
File Handling Programming Guides.
Topics Introduction to File Input and Output
CISC101 Reminders Quiz 2 graded. Assn 2 sample solution is posted.
Recitation Outline C++ STL associative containers Examples
Fundamentals of Python: First Programs
Topics Introduction to File Input and Output
“Everything Else”.
Data Types Every variable has a given data type. The most common data types are: String - Text made up of numbers, letters and characters. Integer - Whole.
Topics Introduction to File Input and Output
Introduction to Object-Oriented Programming (OOP) II
Dictionary.
Presentation transcript:

Tutorial 10 Dictionaries and Classes

Reminder Assignment 09 is due FRIDAY, Dec 4 at 4:00 pm

Review Dictionary Classes ◦ __init__ ◦ __repr__ ◦ __eq__ File Input File Output

Dictionary {key1:value1, key2:value2, …} Each element has a key (a way to look up info) and a value associated with the key Similar to an unordered list (with each element being a key-value pair) Like a dictionary (word = key, definition = value)

Useful dictionary functions D[k] -> Get the value of k D[k] = v -> Add key-value pair or change value to be v if k already exists in D D.keys() -> Creates a view of all the keys in D D.values() -> Creates a view of all the values in D D.pop(k) -> Removes key-value pair of k from D and produces the value of k k in D -> produce True if k is a key in D

Classes Python’s version of structures in Scheme Allows related info to be grouped together We’ll use __init__, __repr__, and __eq__ with the class

__init__ class name: def __init__(self, f1, f2, …): self.field1 = f1 self.field2 = f2... … Creates the class Call the fields by: x=name(field1,field2,…) x.field1 Scheme’s version: (define-struct name (field1 field2 …)) (name-field1 x) Field of class you want to use

__repr__ def __repr__(self): return “name: {0},{1},…”\.format(self.field1, self.field2,…) If we try to print a class object, we’d get something like We can print a more informative message by including __repr__ function within the class definition You can put the class representation into any form you like, so long as you understand what each field is

__eq__ def __eq__(self, other): return type(self)==type(other) and \ self.field1 = other.field1 and\ self.field2 = other.field2 and If two classes have the same fields (and are not aliases), it is used to ensure that they produce True. Without __eq__, == actual tests for aliases (is)

Review - Files Find – same folder Open Read Writing a file Close -> Str -> (listof Str) Str (listof Str)

Writing a File To write to a file you must include the string “w” in your call to the file function, open(filename, “w”) If filename does not exist, a new file with that name will be created If filename does exist, its contents will be erased when opened

Question 1 – list_multiples Consumes a string s and produces a list containing every character in s that appears more than once in sorted order. Use dictionaries. Examples: list_multiples(“abcd”) => [] list_multiples(“bacaba”) => [a,b] list_multiples(“gtddyucaadsa”) => [“a”,”d”]

Question 2 - xor Write a function xor that consumes two dictionaries ( d1 and d2 ) and produces a dictionary. The produced dictionary will contain all the keys that appear in one of d1 and d2 but not both. The value associated with each key will be the same as the one found in the original dictionary.

Examples If d1 = {1:'a', 2:'b', 3:'c', 4:'d'} and d2 = {5:'e', 6:'f', 7:'g', 8:'h'} Then xor(d1,d2) => {1:'a', 2:'b', 3:'c', 4:'d', 5:'e', 6:'f', 7:'g', 8:'h'} If d3 = {5:’q', 6:’l', 7:’c', 8:’e'} Then xor(d2,d3) => {}

Class Definition The remaining questions will use the following class: - A Person is a class with fields name, parents, and children -name is a non-empty string representing the person's name -parents is a list of at most two Person objects representing the person's parents (if the parents are unknown, the list will be empty) -children is a list of Person objects representing the person's children

Examples: george = Person("George", [], [elizabeth] ) elizabeth = Person("Elizabeth", [george], [charles, andrew, edward]) philip = Person("Philip", [], [charles, andrew, edward]) charles = Person("Charles", [elizabeth, philip], [] ) andrew = Person("Andrew", [philip, elizabeth],[]) edward = Person("Edward", [philip, elizabeth],[])

Question 4 – full_siblings Write a function full_siblings which consumes two Person objects and produces True if they have the same set of known parents (i.e. their only parent is the same, or their two parents are the same - though possibly in a different order), and False otherwise.

Question 5 – no_kids Write a function no_kids which consumes a list of Person objects and produces the number of people who have no children. Write the solution using a loop.

Question 6 – new_child Consumes a string new_name representing the name of a newly born child, and two Person objects ( parent1 and parent2 ) representing the child’s parents Does two things: ◦ Produces a new person structure to represent the child ◦ Updates the ‘children’ field of each parent to include the new child

Question 7 & 8 – CD Class class CD: ''' Fields: artist, duration, songs * artist is a string * duration is an integer * songs is a list of strings ''' def __init__(self, artist, dur, los): ''' [purpose]: Initializes a CD [fields]: * artist (artist's name) - str * duration (duration of CD in seconds) - int * songs (list of artist's songs) - (listof str) ''' self.artist = artist self.duration = dur self.songs = los

def __repr__(self): ''' [purpose]: Represents a CD [format]: Artist's Name: XXX Duration: XXX Songs: XXX ''' songstr = "" for song in self.songs: songstr += song + ", " songstr = songstr[:-2] return "Artist Name: %s\nDuration: %s\nSongs: %s" % \ (self.artist, self.duration, songstr)

def __eq__(self, other): return isinstance(self, CD) \ and isinstance(other, CD) \ and self.artist == other.artist \ and self.duration == other.duration \ and self.songs == other.songs

Question 7 Write the Python function make_cd_dict that reads the data from a text file and converts the data into a dictionary of CD objects, with keys equal to the name of the CD. { album title: CD(artist, duration, [listof songs])} You may assume that each CD has a unique name. The files will be formatted in the following way: name of artist, name of CD, length in seconds, song titles (separated by a comma and at least one space)

Example file name of artist, name of CD, length in seconds, song titles Yes, Close to the Edge, 2266, Close to the Edge, And You and I, Siberian Khatru Various, Disney Mix, 912, You'll Be in My Heart, Kiss the Girl, Circle of Life, I'll Make a Man Out of You, Whole New World, Go the Distance Pink Floyd, Wish You Were Here (Side 1), 1268, Shine On You Crazy Diamond (1-5), Welcome to the Machine Jonathan Coulton, Code Monkey, 203, Code Monkey The Beatles, Abbey Road, 255, Mean Mr. Mustard, Polythene Pam, She Came in Through the Bathroom Window

Using readline

Using readlines

Question 8 Write the Python function output_CD_info that consumes a dictionary of CD objects (like the one produced in Q1) and a string. If the string is not a key in the dictionary, the function should do nothing. If the string is a key in the dictionary, the function should create a text file named "Artist - Title".txt, where Artist and Title relate to the cd found at cd_dict[name]. The text file should contain (each on its own line) ◦ the title of the CD in uppercase, ◦ then the artist, ◦ then the duration of the CD (formatted like in question 1), ◦ then a blank line, and ◦ then the index of the song with name of each track in the CD.

Example - "Various - Disney Mix.txt" d3 = {"Disney Mix": CD("Various", 912, ["You'll Be in My Heart", "Kiss the Girl", "Circle of Life", "I'll Make a Man Out of You", "Whole New World", "Go the Distance”])} >> output_CD_info(d3, "Disney Mix") DISNEY MIX Various 912 s 1. You'll Be in My Heart 2. Kiss the Girl 3. Circle of Life 4. I'll Make a Man Out of You 5. Whole New World 6. Go the Distance

Using writeline

Using writelines