Elementary Symbol Tables

Elementary Symbol Tables

Algorithms ROBERT SEDGEWICK | KEVIN WAYNE 3.1 SYMBOL TABLES 3.1 SYMBOL TABLES ‣ API ‣ API ‣ elementary implementations ‣ elementary implementations Algorithms ‣ ordered operations Algorithms ‣ ordered operations FOURTH EDITION ROBERT SEDGEWICK | KEVIN WAYNE ROBERT SEDGEWICK | KEVIN WAYNE http://algs4.cs.princeton.edu http://algs4.cs.princeton.edu Symbol tables Symbol table applications Key-value pair abstraction. ・Insert a value with specified key. application purpose of search key value Given a key, search for the corresponding value. ・ dictionary find definition word definition book index find relevant pages term list of page numbers Ex. DNS lookup. ・Insert domain name with specified IP address. file share find song to download name of song computer ID ・Given domain name, find corresponding IP address. financial account process transactions account number transaction details web search find relevant web pages keyword list of page names domain name IP address compiler find properties of variables variable name type and value www.cs.princeton.edu 128.112.136.11 route Internet packets destination best route www.princeton.edu 128.112.128.15 routing table www.yale.edu 130.132.143.21 DNS find IP address domain name IP address www.harvard.edu 128.103.060.55 reverse DNS find domain name IP address domain name www.simpsons.com 209.052.165.60 genomics find markers DNA string known positions file system find file on disk filename location on disk key value 3 4 Symbol tables: context Basic symbol table API Also known as: maps, dictionaries, associative arrays. Associative array abstraction. Associate one value with each key. Generalizes arrays. Keys need not be between 0 and N – 1. public class ST<Key, Value> ST() Language support. create an empty symbol table ・External libraries: C, VisualBasic, Standard ML, bash, ... void put(Key key, Value val) put key-value pair into the table a[key] = val; ・Built-in libraries: Java, C#, C++, Scala, ... Value get(Key key) value paired with key a[key] ・Built-in to language: Awk, Perl, PHP, Tcl, JavaScript, Python, Ruby, Lua. boolean contains(Key key) is there a value paired with key? every array is an every object is an table is the only void delete(Key key) remove key (and its value) from table associative array associative array primitive data structure boolean isEmpty() is the table empty? int size() number of key-value pairs in the table hasNiceSyntaxForAssociativeArrays["Python"] = true Iterable<Key> keys() all the keys in the table hasNiceSyntaxForAssociativeArrays["Java"] = false legal Python code 5 6 Conventions Keys and values ・Values are not null. Java allows null value Value type. Any generic type. ・Method get() returns null if key not present. ・Method put() overwrites old value with new value. specify Comparable in API. Key type: several natural assumptions. ・Assume keys are Comparable, use compareTo(). Intended consequences. ・Assume keys are any generic type, use equals() to test equality. ・Easy to implement contains(). ・Assume keys are any generic type, use equals() to test equality; use hashCode() to scramble key. public boolean contains(Key key) { return get(key) != null; } built-in to Java (stay tuned) ・Can implement lazy version of delete(). Best practices. Use immutable types for symbol table keys. public void delete(Key key) ・Immutable in Java: Integer, Double, String, java.io.File, … { put(key, null); } ・Mutable in Java: StringBuilder, java.net.URL, arrays, ... 7 8 Equality test Implementing equals for user-defined types All Java classes inherit a method equals(). Seems easy. public class Date implements Comparable<Date> { Java requirements. For any references x, y and z: private final int month; private final int day; Reflexive: x.equals(x) is true. private final int year; ・ equivalence ... ・Symmetric: x.equals(y) iff y.equals(x). relation ・Transitive: if x.equals(y) and y.equals(z), then x.equals(z). public boolean equals(Date that) { ・Non-null: x.equals(null) is false. do x and y refer to the same object? Default implementation. (x == y) Customized implementations. Integer, Double, String, java.io.File, … if (this.day != that.day ) return false; check that all significant User-defined implementations. Some care needed. if (this.month != that.month) return false; fields are the same if (this.year != that.year ) return false; return true; } } 9 10 Implementing equals for user-defined types Equals design Seems easy, but requires some care. typically unsafe to use equals() with inheritance "Standard" recipe for user-defined types. (would violate symmetry) ・Optimization for reference equality. public final class Date implements Comparable<Date> { ・Check against null. private final int month; must be Object. Check that two objects are of the same type and cast. private final int day; ・ Why? Experts still debate. private final int year; ・Compare each significant field: ... but use Double.compare() with double – if field is a primitive type, use == (or otherwise deal with -0.0 and NaN) public boolean equals(Object y) – if field is an object, use equals() apply rule recursively { can use Arrays.deepEquals(a, b) if (y == this) return true; optimize for true object equality – if field is an array, apply to each entry but not a.equals(b) if (y == null) return false; check for null objects must be in the same class if (y.getClass() != this.getClass()) e.g., cached Manhattan distance (religion: getClass() vs. instanceof) Best practices. return false; ・No need to use calculated fields that depend on other fields. Date that = (Date) y; cast is guaranteed to succeed ・Compare fields mostly likely to differ first. if (this.day != that.day ) return false; check that all significant if (this.month != that.month) return false; fields are the same ・Make compareTo() consistent with equals(). if (this.year != that.year ) return false; return true; } x.equals(y) if and only if (x.compareTo(y) == 0) } 11 12 ST test client for traces ST test client for analysis Build ST by associating value i with ith string from standard input. Frequency counter. Read a sequence of strings from standard input and print out one that occurs with highest frequency. public static void main(String[] args) { % more tinyTale.txt ST<String, Integer> st = new ST<String, Integer>(); it was the best of times for (int i = 0; !StdIn.isEmpty(); i++) it was the worst of times { keys S E A R C H E X A M P L E it was the age of wisdom String key = StdIn.readString(); values 0 1 2 3 4 5 6 7 8 9 10 11 12 it was the age of foolishness st.put(key, i); it was the epoch of belief output for outputoutput for } basic symbol table ordered it was the epoch of incredulity for (String s : st.keys()) (one possibility) symbol table it was the season of light StdOut.println(s + " " + st.get(s)); L 11 A 8 it was the season of darkness } P 10 C 4 it was the spring of hope M 9 E 12 it was the winter of despair X 7 H 5 % java FrequencyCounter 1 < tinyTale.txt tiny example L 11 H 5 it 10 (60 words, 20 distinct) C 4 M 9 keys S E A R C H E X A M P L E R 3 P 10 % java FrequencyCounter 8 < tale.txt real example (135,635 words, 10,769 distinct) values 0 1 2 3 4 5 6 7 8 9 10 11 12A 8 R 3 business 122 S 0 output for E 12 real example output for % java FrequencyCounter 10 < leipzig1M.txt basic symbol table ordered S 0 X 7 (21,191,455 words, 534,580 distinct) government 24763 (one possibility) symbol table Keys, values, and output for test client 13 14 L 11 A 8 P 10 C 4 M 9 E 12 Frequency counter implementation X 7 H 5 H 5 L 11 C 4 M 9 public class FrequencyCounterR 3 P 10 { public static void main(String[]A 8 args) R 3 { E 12 S 0 int minlen = Integer.parseInt(args[0]); S 0 X 7 ST<String, Integer> st = new ST<String, Integer>(); create ST 3.1 SYMBOL TABLES while (!StdIn.isEmpty()) { Keys, values, and output for test client String word = StdIn.readString(); ignore short strings ‣ API if (word.length() < minlen) continue; read string and if (!st.contains(word)) st.put(word, 1); update frequency ‣ elementary implementations else st.put(word, st.get(word) + 1); } ‣ ordered operations String max = ""; Algorithms st.put(max, 0); for (String word : st.keys()) print a string if (st.get(word) > st.get(max)) with max freq ROBERT SEDGEWICK | KEVIN WAYNE max = word; http://algs4.cs.princeton.edu StdOut.println(max + " " + st.get(max)); } } 15 Sequential search in a linked list Elementary ST implementations: summary Data structure. Maintain an (unordered) linked list of key-value pairs. Search. Scan through all keys until find a match. guarantee average case key ST implementation Insert. Scan through all keys until find a match; if no match add to front. interface search insert search hit insert key value first sequential search red nodes N N N / 2 N equals() S 0 S 0 are new (unordered list) black nodes E 1 E 1 S 0 are accessed in search A 2 A 2 E 1 S 0 R 3 R 3 A 2 E 1 S 0 C 4 C 4 R 3 A 2 E 1 S 0 circled entries are H 5 H 5 C 4 R 3 A 2 E 1 S 0 changed values E 6 H 5 C 4 R 3 A 2 E 6 S 0 X 7 X 7 H 5 C 4 R 3 A 2 E 6 S 0 gray nodes A 8 X 7 H 5 C 4 R 3 A 8 E 6 S 0 are untouched M 9 M 9 X 7 H 5 C 4 R 3 A 8 E 6 S 0 P 10 P 10 M 9 X 7 H 5 C 4 R 3 A 8 E 6 S 0 L 11 L 11 P 10 M 9 X 7 H 5 C 4 R 3 A 8 E 6 S 0 Challenge.

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    7 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us