Download presentation
Presentation is loading. Please wait.
Published byAlexander Ball Modified over 9 years ago
1
Tutorial 10 Dictionaries and Classes
2
Reminder Assignment 09 is due FRIDAY, Dec 4 at 4:00 pm
3
Review Dictionary Classes ◦ __init__ ◦ __repr__ ◦ __eq__ File Input File Output
4
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)
5
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
6
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
7
__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
8
__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
9
__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)
10
Review - Files Find – same folder Open Read Writing a file Close -> Str -> (listof Str) Str (listof Str)
11
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
12
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”]
13
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.
14
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) => {}
15
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
16
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],[])
17
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.
18
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.
19
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
20
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
21
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)
22
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
23
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)
24
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
25
Using readline
26
Using readlines
27
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.
28
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
29
Using writeline
30
Using writelines
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.