Your SlideShare is downloading. ×
Python & Perl: Lecture 08
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Python & Perl: Lecture 08

806

Published on

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
806
On Slideshare
0
From Embeds
0
Number of Embeds
11
Actions
Shares
0
Downloads
0
Comments
0
Likes
1
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Python & Perl Lecture 08 Vladimir Kulyukin Department of Computer Science Utah State Universitywww.youtube.com/vkedco www.vkedco.blogspot.com
  • 2. Outline ● Template Strings ● More Data Abstraction: Auto-Generation of Huffman Trees ● Dictionarieswww.youtube.com/vkedco www.vkedco.blogspot.com
  • 3. Template Stringswww.youtube.com/vkedco www.vkedco.blogspot.com
  • 4. Formatting Strings ● The string module offers a way to format strings with templates ● Template parameters are specified with $, e.g., $x, $z ● Template parameter values are specified as x=10, z=my value ● If tmpl is a string template with the parameters $x and $z, then the parameters can be replaced by their values with the substi- tute method: – tmpl.substitute(x=10) – tmpl.substitute(z=my value)www.youtube.com/vkedco www.vkedco.blogspot.com
  • 5. Example 01 from string import Template header = <head><title>CS 3430 HW $hwn Available</title></head> htmpl = Template(header) >>> htmpl.substitute(hwn=01) <head><title>CS 3430 HW 01 Available</title></head> >>> htmpl.substitute(hwn=02) <head><title>CS 3430 HW 02 Available</title></head> >>> htmpl.substitute(hwn=03) <head><title>CS 3430 HW 03 Available</title></head>www.youtube.com/vkedco www.vkedco.blogspot.com
  • 6. Example 02 header2 = <head><title>CS $cln HW $hwn Available</title></head> htmpl2 = Template(header2) params = {} params[cln] = 5000 params[hwn] = 10 >>> htmpl2.substitute(params) <head><title>CS 5000 HW 10 Available</title></head>www.youtube.com/vkedco www.vkedco.blogspot.com
  • 7. Example 03 def param_template(tmpl, params): return tmpl.substitute(params) header3 = <head> <title>CS $cln HW $hwn Available</title> </head> htmpl3 = Template(header3) >>> param_template(htmpl2, {cln:3430, hwn:01}) <head><title>CS 3430 HW 01 Available</title></head> >>> param_template(htmpl2, {cln:3430, hwn:02}) <head><title>CS 3430 HW 02 Available</title></head>www.youtube.com/vkedco www.vkedco.blogspot.com
  • 8. Auto-Generation of Huffman Treeswww.youtube.com/vkedco www.vkedco.blogspot.com
  • 9. Algorithm ● Basic idea: Build the tree bottom up so that symbols with the smallest fre- quencies are farthest from the root ● Given a sequence of nodes (initially single symbols and their frequencies), find two nodes with the smallest frequencies and combine them into a new node whose symbol list contains the symbols of the two nodes and whose frequency is the sum of the frequencies of the two nodes ● Remove the two combined nodes from the sequence and add the newly constructed node back to the sequence (note that the length of the se- quence is now reduced by 1) ● Keep combining pairs of nodes in the above fashion until there is only one node left in the sequence: this is the root of the Huffman treewww.youtube.com/vkedco www.vkedco.blogspot.com
  • 10. Example ● Initial sequence: [A:4, B:2, C:1, D:1] ● Find two nodes with the smallest frequencies and combine them into a new node whose symbol list contains the symbols of the two nodes and whose frequency is the sum of the frequencies of the two nodes ● The nodes are C:1 and D:1 ● The new node is {C, D}:2 ● After removing C:1 and D:1 and adding {C, D}:2, the sequence be- comes [A:4, B:2, {C, D}:2]www.youtube.com/vkedco www.vkedco.blogspot.com
  • 11. Example ● The Huffman tree so far: {C,D}:2 C:1 D:1www.youtube.com/vkedco www.vkedco.blogspot.com
  • 12. Example ● Current sequence: [A:4, B:2, {C,D}:2] ● Find two nodes with the smallest frequencies and combine them into a new node whose symbol list contains the symbols of the two nodes and whose frequency is the sum of the frequencies of the two nodes ● The nodes are B:2 and {C, D}:2 ● The new node is {B, C, D}:4 ● After removing B:2 and {C, D}:2 and adding {B, C, D}:4, the sequence becomes [A:4, {B, C, D}:4]www.youtube.com/vkedco www.vkedco.blogspot.com
  • 13. Example ● The Huffman tree so far: {B,C,D}:4 {C,D}:2 B:2 C:1 D:1www.youtube.com/vkedco www.vkedco.blogspot.com
  • 14. Example ● Current sequence: [A:4, {B,C,D}:4] ● Find two nodes with the smallest frequencies and combine them into a new node whose symbol list contains the symbols of the two nodes and whose frequency is the sum of the frequencies of the two nodes ● The nodes are A:4 and {B,C, D}:4 ● The new node is {A,B, C, D}:4 ● After removing A:4 and {B,C, D}:4 and adding {A,B, C, D}:8, the se- quence becomes [{A,B, C, D}:8] ● We are done, because the sequence has only one nodewww.youtube.com/vkedco www.vkedco.blogspot.com
  • 15. Example ● The final Huffman tree: {A, B,C,D}:8 {B,C,D}:4 A:4 {C,D}:2 B:2 C:1 D:1www.youtube.com/vkedco www.vkedco.blogspot.com
  • 16. Remarks on the Algorithm ● The algorithm does not specify a unique Huffman tree, because there may be more than two nodes in the sequence with the same frequencies ● How these nodes are combined at each step (e.g., two rightmost nodes, two leftmost nodes, two middle nodes) is arbitrary, and is left for the programmer to decide ● The algorithm does guarantee the same code lengths regardless of which combination method is usedwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 17. Dictionarieswww.youtube.com/vkedco www.vkedco.blogspot.com
  • 18. Construction ● The constructor dict() can be used to create dictionaries from a sequence of two-item sequences >>> my_dict2 = dict([[A, a], [B, b], [C, c]]) >>> my_dict2 {A: a, C: c, B: b} >>> my_dict3 = dict([(A, a), (B, b), (C, c)]) >>> my_dict3 {A: a, C: c, B: b} >>> my_dict4 = dict(((A, a), (B, b), (C, c))) >>> my_dict4 {A: a, C: c, B: b}www.youtube.com/vkedco www.vkedco.blogspot.com
  • 19. Construction ● The constructor dict() can be used to create dictionaries from keyword-value pairs ● The keyword-value pair has the following syntax: keyword = value ● Keywords are converted into strings >>> my_dict5 = dict(first_name = "John", last_name = "Nicholson") >>> my_dict5 {first_name: John, last_name: Nicholson}www.youtube.com/vkedco www.vkedco.blogspot.com
  • 20. Checking for Keys ● Option 1: key in dictionary >>> my_dict = dict(first_name = "Vladimir", last_name = "Kulyukin") >>> "first_name" in my_dict True >>> "middle_name" not in my_dict True ● Option 2: dictionary.has_key(<key>) >>> my_dict.has_key(first_name) Truewww.youtube.com/vkedco www.vkedco.blogspot.com
  • 21. Safe Access with get() ● dict.get() is similar to use dict[] but safer ● Syntax: dict.get(key[, default]) ● dict[key] returns the value of key in dict or throws error if key is not in dict ● dict.get(key) returns value of key in dict or None if key is not in dict ● dict.get(key, default) returns value of key in dict or default if key is not in dictwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 22. Example >>> my_dict = {one : 1, two : [a, b, c]} >>> my_dict[one] 1 >>> my_dict[three] ## error >>> my_dict.get(three) ## None (nothing) returned >>> my_dict.get(three, not in dict) not in dict ## default not in dict returnedwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 23. Example: Keys and Values >>> names = [john, vicki, steve] >>> ages = [18, 19, 20] >>> zip(names, ages) [(john, 18), (vicki, 19), (steve, 20)] >>> my_dict = dict(zip(names, ages)) >>> my_dict.keys() ## get list of keys. [steve, john, vicki] >>> my_dict.values() ## get list of values. [20, 18, 19]www.youtube.com/vkedco www.vkedco.blogspot.com
  • 24. Clearing Dictionaries >>> my_dict = { } >>> my_dict[one] = [1, 2, 3] >>> my_dict[two] = [a, b, c] >>> my_dict {two: [a, b, c], one: [1, 2, 3]} >>> my_dict.clear() >>> my_dict {}www.youtube.com/vkedco www.vkedco.blogspot.com
  • 25. Shallow Copying ● The method copy() returns a shallow copy of the dictionary my_dict = {one : 1, two : [a, b, c]} my_dict2 = my_dict.copy() print shallow copying:, my_dict, my_dict2 del my_dict2[two][-1] print shallow copying:, my_dict, my_dict2 Output: shallow copying: {two: [a, b, c], one: 1} {two: [a, b, c], one: 1} shallow copying: {two: [a, b], one: 1} {two: [a, b], one: 1}www.youtube.com/vkedco www.vkedco.blogspot.com
  • 26. Deep Copying ● The method deepcopy() returns a deep copy of the dictionary from copy import deepcopy my_dict3 = {one : 1, two : [a, b, c]} my_dict4 = deepcopy(my_dict3) print deep copying:, my_dict3, my_dict4 del my_dict4[two][-1] print deep copying:, my_dict3, my_dict4 Output: deep copying: {two: [a, b, c], one: 1} {two: [a, b, c], one: 1} deep copying: {two: [a, b, c], one: 1} {two: [a, b], one: 1}www.youtube.com/vkedco www.vkedco.blogspot.com
  • 27. Dictionary Creation From Keys ● The method fromkeys() creates a dictionary from keys each of which maps to None >>> d = {}.fromkeys([key1, key2]) >>> d {key2: None, key1: None} >>> d[key1] = value1 >>> d[key2] = value2 >>> d {key2: value2, key1: value1}www.youtube.com/vkedco www.vkedco.blogspot.com
  • 28. Iterating over Dictionaries ● Option 1: get the list of keys or values and then iterate over the list >>> my_dict = dict([(x, x*x) for x in range(10)]) >>> my_dict {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81} >>> for k in my_dict.keys(): print k ● Option 2: use iterkeys() or itervalues() without creating the lists >>> for k in my_dict.iterkeys(): print k >>> for v in my_dict.itervalues(): print vwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 29. Deleting Keys with del() ● You can use del() to delete key-value pairs from dictionaries >>> my_dict = dict([(x, x*x) for x in range(4)]) >>> my_dict {0: 0, 1: 1, 2: 4, 3: 9} >>> del my_dict[2] >>> my_dict {0: 0, 1: 1, 3: 9}www.youtube.com/vkedco www.vkedco.blogspot.com
  • 30. Order of Keys ● Keys are not ordered ● The order of the keys is not random but arbitrary ● The order depends on the history of insertions and deletions ● If you need the keys/values ordered for your applicaiton, sort themwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 31. Flexible Lookup Lists ● Dictionaries can be used as flexible lookup lists that map numbers to values ● Lists cannot be used for that purpose, because you cannot insert elements beyond their boundaries >>> x = [zero, two, three] >>> my_dict = dict(enumerate(x)) >>> my_dict {0: zero, 1: two, 2: three} >>> my_dict[500] = five hundred >>> my_dict {0: zero, 1: two, 2: three, 500: five hundred}www.youtube.com/vkedco www.vkedco.blogspot.com
  • 32. Dictionary Useswww.youtube.com/vkedco www.vkedco.blogspot.com
  • 33. Sparse Data Structures ● Sparse matrices: Suppose you have to represent a 2D matrix where only a few values are 1s and the rest are 0s >>> matrix = {} >>> matrix[(10, 15)] = 1 ● Database type records: keys are column names and values are the values for the recordwww.youtube.com/vkedco
  • 34. Format Specifiers ● Dictionaries can be used to format strings with many specifiers ● Tuples can be used here by they are hard to decipher and read ● Here is a tuple example: >>> "%d %d %d %d %d %d %d %d %d %d" % (5,2,6,3,5,6,7,8,3,6)www.youtube.com/vkedco www.vkedco.blogspot.com
  • 35. Format Specifiers ● Tuple method: >>> format_string_1 = "%s has lived in %s for %2d years." >>> print format_string_1 % ("Dave", "San Francisco", 10) Dave has lived in San Francisco for 10 years. ● Dictionary method: >>> format_string_2 = "%(name)s has lived in %(city)s for %(length)2d years." >>> print format_string_2 % { "length" : 10, "name" : "Dave", "city" : "San Francisco" } Dave has lived in San Francisco for 10 years.www.youtube.com/vkedco www.vkedco.blogspot.com
  • 36. Format Specifiers ● Tuples in format strings: – Values must be in the same order as specified in the format string ● Dictionary method: – Order of values does not matter so long as you remember the keys – Same key can be used multiple timeswww.youtube.com/vkedco www.vkedco.blogspot.com
  • 37. Reading & References ● www.python.org ● Ch 02, H. Abelson & J. Sussman. Structure and Interpreta- nd tion of Computer Programs, 2 Ed., MIT Press ● Ch 03 & 04 M. L. Hetland. Beginning Python From Novice to Professional, 2nd Ed., APRESSwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 38. Feedback Bugs, comments to vladimir dot kulyukin at usu dot eduwww.youtube.com/vkedco www.vkedco.blogspot.com

×