diff --git a/cxx/background.js b/cxx/background.js new file mode 100644 index 00000000..2e3c89de --- /dev/null +++ b/cxx/background.js @@ -0,0 +1,473 @@ +// == Helper Prototype Extensions == +Storage.prototype.setObject = function(key, value, opt_expiration) { + var expiration = opt_expiration || 3e9; // defaults to a little bit more than 1 month + if (expiration > 0) { + expiration += Date.now(); + } + this.setItem(key, JSON.stringify(value)); + this.setItem(key + "__expiration", expiration); +}; +Storage.prototype.getObject = function(key) { + return JSON.parse(this.getItem(key)); +}; +Storage.prototype.hasUnexpired = function(key) { + if (!this.getItem(key + "__expiration") || !this.getItem(key)) { + return false; + } + var expiration = +this.getItem(key + "__expiration"); + return expiration < Date.now(); +}; +String.prototype.startsWith = function(str) { + if (str.length > this.length) { + return false; + } + return (String(this).substr(0, str.length) == str); +}; +String.prototype.endsWith = function(str) { + if (str.length > this.length) { + return false; + } + return (String(this).substr(this.length - str.length, this.length) == str); +}; +String.prototype.encode = function() { + return encodeURIComponent(String(this)); +}; +String.prototype.strip = function() { + var str = String(this); + if (!str) { + return ""; + } + var startidx=0; + var lastidx=str.length-1; + while ((startidx=startidx)&&(str.charAt(lastidx)==' ')){ + lastidx--; + } + if (lastidx < startidx) { + return ""; + } + return str.substring(startidx, lastidx+1); +}; + +// == Autocompletion Chrome Extension == +(function(){ + // Issue a new GET request + function xhr(url, ifexists, ifnotexists, retry_interval) { + var retry_time = retry_interval || 5; + var req = new XMLHttpRequest(); + console.log("Fetching: " + url); + req.open("GET", url); + req.onreadystatechange=function(){ + if (req.readyState == 4){ + var status=req.status; + if ((status == 200) || (status == 301) || (status == 302)) { + ifexists(url, req); + } else { + ifnotexists(url, req); + setTimeout(function() { xhr(url, ifexists, ifnotexists, retry_time + 5).send(null); }, retry_time); + } + } + }; + return req; + }; + + // Navigates to the specified URL. + function nav(url) { + console.log("Navigating to: " + url); + chrome.tabs.getSelected(null, function(tab) { + chrome.tabs.update(tab.id, {url: url}); + }); + }; + + // Sets the the default styling for the first search item + function setDefaultSuggestion(text) { + if (text) { + chrome.omnibox.setDefaultSuggestion({"description":"C++ Search " + text}); + } else { + chrome.omnibox.setDefaultSuggestion({"description":"C++ Search"}); + } + }; + + var stl_ = null; + var cpp_ = null; + var clang_ = null; + var ckey_ = null; + + // Prefetch necessary data + chrome.omnibox.onInputStarted.addListener(function(){ + console.log("Input started"); + setDefaultSuggestion(''); + + + if (localStorage.hasUnexpired('stl')) { + stl_ = localStorage.getObject('stl'); + } else { + //xhr("http://www.sgi.com/tech/stl/table_of_contents.html", + xhr("http://tinf2.vub.ac.be/~dvermeir/mirrors/www.sgi.com/Technology/STL/table_of_contents.html", + function(url, req) { + console.log("Received: "+url); + stl_ = {}; + var text = req.responseText; + var matches = text.match(new RegExp("
  • [^<]*[^<]*", "g")); + for (var i = 0; i < matches.length; ++i) { + var match = matches[i]; + var hrefstartidx = match.indexOf("href=\"") + 6; + var hrefendidx = match.indexOf("\"", hrefstartidx); + var contentstartidx = match.indexOf(">", hrefendidx) + 1; + var contentendidx = match.indexOf("", contentstartidx); + var href = match.substring(hrefstartidx, hrefendidx); + var content = match.substring(contentstartidx, contentendidx); + //stl_[content.toLowerCase()] = {"name":content, "url":"http://www.sgi.com/tech/stl/"+href}; + //console.log("href", href, "content", content); + stl_[content.toLowerCase()] = {"name":content, "url":"http://tinf2.vub.ac.be/~dvermeir/mirrors/www.sgi.com/Technology/STL/"+href}; + } + localStorage.setObject('stl', stl_); + }, + function(url, req) { + console.log("Failed to receive: "+url); + }).send(null); + } + + if (localStorage.hasUnexpired('cplusplus_headers')) { + cpp_ = localStorage.getObject('cplusplusheaders'); + } else { + //xhr("http://cplusplus.com/reference/", + xhr("http://en.cppreference.com/w/c", + function(url, req) { + console.log("Received: "+url); + cpp_ = {}; + var text = req.responseText; + //console.log(text); + //var matches = text.match(new RegExp("[^<]*", "g")); + var matches = text.match(new RegExp("[^<]*<\/a>", "g")); + for (var i = 0; i < matches.length; ++i) { + var match = matches[i]; + var hrefstartidx = match.indexOf("href=\"") + 6; + var hrefendidx = match.indexOf("\"", hrefstartidx); + var contentstartidx = match.indexOf(">", hrefendidx) + 1; + var contentendidx = match.indexOf("", contentstartidx); + var href = match.substring(hrefstartidx, hrefendidx); + var content = match.substring(contentstartidx, contentendidx).strip(); + //cpp_.push({'name':content, 'url':'http://cplusplus.com/'+href}); + //console.log("href", href, "content", content); + //cpp_.push({'name':content, 'url':'http://en.cppreference.com'+href}); + cpp_[content.toLowerCase()] = {"name":content, "url":"http://en.cppreference.com"+href}; + + } + localStorage.setObject('cplusplus_headers', cpp_); + }, + function(url, req) { + console.log("Failed to receive: "+url); + }).send(null); + } + + if (localStorage.hasUnexpired('clang')) { + clang_ = localStorage.getObject('clang'); + } else { + //xhr("http://cplusplus.com/reference/", + xhr("http://en.cppreference.com/w/c/language", + function(url, req) { + console.log("Received: "+url); + clang_ = {}; + var text = req.responseText; + //console.log(text); + //var matches = text.match(new RegExp("[^<]*", "g")); + var matches = text.match(new RegExp("[^<]*<\/a>", "g")); + //console.log(matches); + for (var i = 0; i < matches.length; ++i) { + var match = matches[i]; + var hrefstartidx = match.indexOf("href=\"") + 6; + var hrefendidx = match.indexOf("\"", hrefstartidx); + var contentstartidx = match.indexOf(">", hrefendidx) + 1; + var contentendidx = match.indexOf("", contentstartidx); + var href = match.substring(hrefstartidx, hrefendidx); + var content = match.substring(contentstartidx, contentendidx).strip(); + //cpp_.push({'name':content, 'url':'http://cplusplus.com/'+href}); + //console.log("href", href, "content", content); + //cpp_.push({'name':content, 'url':'http://en.cppreference.com'+href}); + clang_[content.toLowerCase()] = {"name":content, "url":"http://en.cppreference.com"+href}; + + } + localStorage.setObject('clang', clang_); + }, + (url, req) => { + console.log("Failed to receive: " + url); + }).send(null); + } + + if (localStorage.hasUnexpired('ckey')) { + ckey_ = localStorage.getObject('ckey'); + } else { + //xhr("http://cplusplus.com/reference/", + xhr("http://en.cppreference.com/w/c/keyword", + function(url, req) { + console.log("Received: "+url); + ckey_ = {}; + var text = req.responseText; + //console.log(text); + //var matches = text.match(new RegExp("[^<]*", "g")); + var matches = text.match(new RegExp("[^<]*<\/a>", "g")); + // console.log(matches); + for (var i = 0; i < matches.length; ++i) { + var match = matches[i]; + var hrefstartidx = match.indexOf("href=\"") + 6; + var hrefendidx = match.indexOf("\"", hrefstartidx); + var contentstartidx = match.indexOf("span>", hrefendidx) + 5; + var contentendidx = match.indexOf("", contentstartidx); + var href = match.substring(hrefstartidx, hrefendidx); + var content = match.substring(contentstartidx, contentendidx).strip(); + var url = "http://en.cppreference.com"+href; + content = content.toLowerCase().strip(); + if (clang_){ + equiv_lang_entry = clang_[`${content}`]; + } + if (equiv_lang_entry) { + + console.log("match found", equiv_lang_entry); + let lang_url = equiv_lang_entry.url; + //console.log("href", href, "content", content, "url", lang_url); + ckey_[content] = {"name":content, "url":lang_url}; + } + else { + //console.log("href", href, "content", content); + ckey_[content] = {"name":content, "url":url}; + } + + } + localStorage.setObject('ckey', ckey_); + }, + (url, req) => { + console.log("Failed to receive: " + url); + }).send(null); + } + + }); + + chrome.omnibox.onInputCancelled.addListener(function() { + console.log("Input cancelled."); + setDefaultSuggestion(''); + }); + + setDefaultSuggestion(''); + + /* + * + * When the input changes, what it does? + * When the input changes, what it does? + * + */ + chrome.omnibox.onInputChanged.addListener(function(text, suggest_callback) { + setDefaultSuggestion(text); + // console.log("changed: text", text); + if (!text) { + return; + } + + var kMaxSuggestions = 20; + var suggestions = []; + var stripped_text = text.strip(); + if (!stripped_text) { + return; + } + var qlower = stripped_text.toLowerCase(); + // console.log("qlower", qlower); + var prefix = ""; + /*if (qlower.startsWith("std::")) { + prefix = "std::"; + qlower = qlower.substr(5); + } + + if (!qlower) { + return; + }*/ + + if (clang_) { + for (var key in clang_) { + if (key.startsWith(qlower) && (key == clang_[key]["name"])) { + var item = clang_[key]; + var name = item["name"]; + var url = item["url"]; + suggestions.push({"content":prefix + name, "description":["", prefix + name, " - ", url, ""].join('')}); + if (suggestions.length > kMaxSuggestions) { + break; + } + } + } + if (prefix.length == 0) { + for (var key in clang_) { + if (key.startsWith(qlower) && (key != clang_[key]["name"])) { + var item = clang_[key]; + var name = item["name"]; + var url = item["url"]; + suggestions.push({"content":name, "description":["", name, " - ", url, ""].join('')}); + if (suggestions.length > kMaxSuggestions) { + break; + } + } + } + } + } + + if (ckey_) { + for (var key in ckey_) { + if (key.startsWith(qlower) && (key == ckey_[key]["name"])) { + var item = ckey_[key]; + var name = item["name"]; + var url = item["url"]; + suggestions.push({"content":prefix + name, "description":["", prefix + name, " - ", url, ""].join('')}); + if (suggestions.length > kMaxSuggestions) { + break; + } + } + } + if (prefix.length == 0) { + for (var key in ckey_) { + if (key.startsWith(qlower) && (key != ckey_[key]["name"])) { + var item = ckey_[key]; + var name = item["name"]; + var url = item["url"]; + suggestions.push({"content":name, "description":["", name, " - ", url, ""].join('')}); + if (suggestions.length > kMaxSuggestions) { + break; + } + } + } + } + } + //console.log(cpp_.length, cpp_); + if (cpp_) { + for (var key in cpp_) { + if (key.startsWith(qlower) && (key == cpp_[key]["name"])) { + var item = cpp_[key]; + var name = item["name"]; + var url = item["url"]; + suggestions.push({"content":prefix + name, "description":["", prefix + name, " - ", url, ""].join('')}); + if (suggestions.length > kMaxSuggestions) { + break; + } + } + } + if (prefix.length == 0) { + for (var key in cpp_) { + if (key.startsWith(qlower) && (key != cpp_[key]["name"])) { + var item = cpp_[key]; + var name = item["name"]; + var url = item["url"]; + suggestions.push({"content":name, "description":["", name, " - ", url, ""].join('')}); + if (suggestions.length > kMaxSuggestions) { + break; + } + } + } + } + } + + if (stl_) { + for (var key in stl_) { + if (key.startsWith(qlower) && (key == stl_[key]["name"])) { + var item = stl_[key]; + var name = item["name"]; + var url = item["url"]; + suggestions.push({"content":prefix + name, "description":["", prefix + name, " - ", url, ""].join('')}); + if (suggestions.length > kMaxSuggestions) { + break; + } + } + } + if (prefix.length == 0) { + for (var key in stl_) { + if (key.startsWith(qlower) && (key != stl_[key]["name"])) { + var item = stl_[key]; + var name = item["name"]; + var url = item["url"]; + suggestions.push({"content":name, "description":["", name, " - ", url, ""].join('')}); + if (suggestions.length > kMaxSuggestions) { + break; + } + } + } + } + } + + + + if (stripped_text.length >= 2) { + suggestions.push({"content":stripped_text + " [Google Code Search]", + "description":["Search for \"", stripped_text, " lang:c\" using Google Code Search - http://code.google.com/codesearch#search/&q=", encodeURIComponent(stripped_text + " lang:c"), ""].join('')}); + suggestions.push({"content":stripped_text + " [Development and Coding Search]", + "description":["Search for \"", stripped_text, "\" using Development and Coding Search - http://www.google.com/cse?cx=005154715738920500810:fmizctlroiw&q=", encodeURIComponent(stripped_text), ""].join('')}); + } + // console.log("changed: suggestions", suggestions); + suggest_callback(suggestions); + }); + + chrome.omnibox.onInputEntered.addListener(function(text) { + console.log("Input entered: " + text); + if (!text) { + nav("https://en.cppreference.com/w/c"); + return; + } + + var stripped_text = text.strip(); + //console.log(stripped_text); + if (!stripped_text) { + nav("https://en.cppreference.com/w/c"); + return; + } + + if (stripped_text.startsWith("http://") || stripped_text.startsWith("https://")) { + nav(stripped_text); + return; + } + + if (stripped_text.startsWith("www.") || stripped_text.endsWith(".com") || stripped_text.endsWith(".net") || stripped_text.endsWith(".org") || stripped_text.endsWith(".edu")) { + nav("http://" + stripped_text); + return; + } + + var google_codesearch_suffix = " [Google Code Search]"; + if (stripped_text.endsWith(google_codesearch_suffix)) { + var newquery = stripped_text.substring(0, stripped_text.length - google_codesearch_suffix.length).strip(); + nav("http://code.google.com/codesearch#search/&q=" + encodeURIComponent(newquery +" lang:c")); + return; + } + + var devsearch_suffix = " [Development and Coding Search]"; + if (stripped_text.endsWith(devsearch_suffix)) { + var newquery = stripped_text.substring(0, stripped_text.length - devsearch_suffix.length).strip(); + nav("http://www.google.com/cse?cx=005154715738920500810:fmizctlroiw&q=" + encodeURIComponent(newquery)); + return; + } + + var qlower = stripped_text.toLowerCase(); + + if (clang_ && clang_[qlower]) { + nav(clang_[qlower]["url"]); + return; + } + + if (ckey_ && ckey_[qlower]) { + nav(ckey_[qlower]["url"]); + return; + } + + if (qlower.startsWith("std::")) { + qlower = qlower.substr(5); + } + + if (cpp_ && cpp_[qlower]) { + nav(cpp_[qlower]["url"]); + return; + } + + if (stl_ && stl_[qlower]) { + nav(stl_[qlower]["url"]); + return; + } + + + nav("http://www.google.com/search?q=" + encodeURIComponent("C++ STL "+stripped_text)); + }); +})(); \ No newline at end of file diff --git a/cxx/icon.png b/cxx/icon.png new file mode 100644 index 00000000..faca8b68 Binary files /dev/null and b/cxx/icon.png differ diff --git a/cxx/icon128.png b/cxx/icon128.png new file mode 100644 index 00000000..ff771552 Binary files /dev/null and b/cxx/icon128.png differ diff --git a/cxx/icon16.png b/cxx/icon16.png new file mode 100644 index 00000000..37fd4879 Binary files /dev/null and b/cxx/icon16.png differ diff --git a/cxx/icon32.png b/cxx/icon32.png new file mode 100644 index 00000000..c1cd17ef Binary files /dev/null and b/cxx/icon32.png differ diff --git a/cxx/manifest.json b/cxx/manifest.json new file mode 100644 index 00000000..34c39ba9 --- /dev/null +++ b/cxx/manifest.json @@ -0,0 +1,18 @@ +{ + "name" : "C++ Search", + "description" : "Adds support to the omnibox to search the C++ reference material.", + "manifest_version" : 2, + "background" : { + "scripts" : [ "background.js" ] + }, + "icons" : { "128" : "icon128.png", "32" : "icon32.png", "16" : "icon16.png" }, + "omnibox" : { "keyword" : "cxx" }, + "permissions" : [ + "tabs", + "*://*.sgi.com/", + "*://*.ac.be/", + "*://cplusplus.com/", + "*://*.cppreference.com/" + ], + "version" : "2.0" +} diff --git a/img/qsortWithPartition.png b/img/qsortWithPartition.png new file mode 100644 index 00000000..b3af0306 Binary files /dev/null and b/img/qsortWithPartition.png differ diff --git a/img/quicksortIn4Lines.png b/img/quicksortIn4Lines.png new file mode 100644 index 00000000..ebab6256 Binary files /dev/null and b/img/quicksortIn4Lines.png differ diff --git a/notes/cs3003-unit4-examples.md b/notes/cs3003-unit4-examples.md index 7c89bc31..6fde389f 100644 --- a/notes/cs3003-unit4-examples.md +++ b/notes/cs3003-unit4-examples.md @@ -1,3 +1,4 @@ + # Illustrative programs of Tuples, Lists and Dictionaries ## Pre-requisites @@ -514,12 +515,27 @@ A comparison screenshot of the three sorts in action in "verbose" mode is presen ## Python Pseudo Code Compare -- insertionsort : get a key and **insert** it into _sorted_ sublist -- selectionsort : **select** minimum value and swap into _sorted_ sublist -- mergesort : divide and **merge** (_conquer_) of _sorted_ sublists +**UPDATE: May 30, 2022** +_Added bubblesort (for AD3251)_ +![bubble](https://i.imgur.com/AW0GrdY.png) + + - bubblesort: compare adjacent elements and swap, as you iterate the list + - insertionsort : get a key and **insert** it into *sorted* sublist + - selectionsort : **select** minimum value and swap into *sorted* sublist + - mergesort : divide and **merge** (_conquer_) of *sorted* sublists + - quicksort: choose a pivot and partition (_divide_) into big and small sublists and then combine them ![sortCode](http://bit.ly/sortCompared2) +**UPDATE: May 30, 2022** +_Added quicksort (for AD3251)_ +![qsort](https://i.imgur.com/dGztZZe.png) + +With the ```partition``` function: + +![qsort2](https://i.imgur.com/1LVSfeW.png) + + ## Helper functions Three helper functions (`insort`, `min_index` and `merge`) were written and used in the respective sorting implementation. @@ -605,13 +621,3 @@ Which one is which? ## Sort 3 ![gif3](../img/SelectionEg01.gif) - - diff --git a/notes/cs3003-unit4-examples.md.html b/notes/cs3003-unit4-examples.md.html index 467e5509..42aa0005 100644 --- a/notes/cs3003-unit4-examples.md.html +++ b/notes/cs3003-unit4-examples.md.html @@ -133,12 +133,12 @@

    Pre-requisites

    Algorithm

    • -

      In insertsort, given a key, a copy of a pre-determined element in the list, we insert it at the appropriate location after comparing it with the unsorted elements of the list.

      -
        mark first element as sorted
      -  for each unsorted element X
      -  	'extract' the element X as 'key'
      -  	insert key at the relevant index so list remains sorted
      -  return sorted list 
      +

      In insertsort, given a key, a copy of a pre-determined element in the list, we insert it at the appropriate location after comparing it with the unsorted elements of the list.

      +
      mark first element as sorted
      +for each unsorted element X
      +	'extract' the element X as 'key'
      +	insert key at the relevant index so list remains sorted
      +return sorted list
       
    @@ -148,7 +148,7 @@

    Algorithm

    extract the element X for j = lastSortedIndex (position -1) down to 0 if current element j > X - decrement j by 1 + decrement j by 1 else break loop and insert X here return sorted list
    @@ -157,17 +157,17 @@

    Source code

    n = len(alist) # STEP 0 - iterate through the list for idx in range(1, n): - # STEP 1 - element to insert + # STEP 1 - element to insert # j, value = idx, alist.pop(idx) j, value = idx, alist[idx] - # STEP 2 - decide where to insert + # STEP 2 - decide where to insert sorted_already = alist[:idx] while j > 0 and value < sorted_already[j-1]: j -= 1 # STEP 3 - insert it in the relevant index # alist.insert(j, value) - if j != idx: + if j != idx: alist[j+1:idx+1] = alist[j:idx] alist[j] = value print('intermediary:', alist) @@ -175,7 +175,7 @@

    Source code

    The following code can be used to test the above code:

    # Test case using random shuffle
    -from random import shuffle 
    +from random import shuffle
     alist = list(range(10))
     shuffle(alist)
     
    @@ -243,11 +243,11 @@ 

    Version 1

    n = len(alist) # STEP 0 - iterate through the list for i in range(n-1): - min_i = i - # STEP 1 - update mini_i with index + min_i = i + # STEP 1 - update mini_i with index # of min value in unsorted alist[i+1:] - for j in range(i+1, n): - if alist[j] < alist[min_i]: + for j in range(i+1, n): + if alist[j] < alist[min_i]: min_i = j # STEP 2 - swap it with element at index 'i' if min_i != i: @@ -256,14 +256,14 @@

    Version 1

    Version 2

    def selectsort(alist):
    -    n = len(alist) 
    +    n = len(alist)
         # STEP 0 - iterate through the list
         for i in range(n-1):
             # STEP 1 - find the index of the minimum
             unsorted = alist[i:]
             smallest = min(unsorted)
             min_i = alist.index(smallest, i)
    -        # STEP 2 - swap if required 
    +        # STEP 2 - swap if required
             if min_i != i:
                 alist[i],alist[min_i] = alist[min_i], alist[i]
                 print("intermediary", alist)
    @@ -272,7 +272,7 @@ 

    Version 2

    Version 3

      -
    • uses slicing, tuples and list comprehension to make the code very efficient and eminently readable.
    • +
    • uses slicing, tuples and list comprehension to make the code very efficient and eminently readable.
    def selectsort(alist):
         n = len(alist)
    @@ -298,7 +298,7 @@ 

    Pre-requisites

    @@ -516,32 +517,32 @@

    Version 2

    A histogram contains bins (lower bound, upper bound), and statistical values are dropped into these bins. Eventually, the histogram is visualized based on the bin counts. This type of histogram is what is used in more statistical analysis.

    ################################
     # Program No 5
    -# using tuple as key in a dictionary 
    -# to build bins of values for 
    -# visualization 
    +# using tuple as key in a dictionary
    +# to build bins of values for
    +# visualization
     #
    -# Refer https://datavizcatalogue.com/methods/histogram.html 
    +# Refer https://datavizcatalogue.com/methods/histogram.html
     #
     #################################
     # Build a histogram
     
     import random
    -# build a random list 
    +# build a random list
     # returns a list containing numbers 1 <= n <= maxval
     # the list will contain n elements where
    -#   mincount < n < maxcount 
    -def random_list(mincount, maxcount, maxval, minval=1): 
    +#   mincount < n < maxcount
    +def random_list(mincount, maxcount, maxval, minval=1):
       size = random.randint(mincount, maxcount)
       alist = []
       for _ in range(size):
    -    alist.append(random.randrange(minval, maxval+1))		
    +    alist.append(random.randrange(minval, maxval+1))
       return alist
     
     maxval, minval = 100, 10
     arlist = random_list(40, 200, maxval, minval)
     #print("A random list", arlist)
     
    -# returns a list containing tuples with 
    +# returns a list containing tuples with
     # value and frequency, aka a histogram
     from collections import defaultdict
     def generate_histogram(arlist):
    @@ -552,27 +553,27 @@ 

    Version 2

    #minval = min(arlist) #maxval = max(arlist) points = [p for p in range(minval, maxval+1, int(binwidth))] - + bins = [(start, end-1) if end != maxval else (start, end) \ for (start, end) in zip(points, points[1:]) ] #bins.append(points[-1]) - + for number in arlist: - for start, end in bins: - if start <= number <= end: + for start, end in bins: + if start <= number <= end: counters[(start, end)] += 1 - return counters + return counters histo = generate_histogram(arlist) print("A histogram with", histo.items()) print("Visualizing the histogram") -for bin in histo.items(): +for bin in histo.items(): print (f'{str(bin[0]):>10}', '@'*bin[1]) -# Ordered histogram +# Ordered histogram o_histogram = sorted( [(v, k) for k, v in histo.items()], reverse=True ) @@ -582,44 +583,53 @@

    Version 2

    print (f'{str(bin[1]):>10}', '@'*bin[0])

    Complexity Analysis

    -

    This needs to be expanded - or even required?
    -- Rajasekaran to discuss

    +

    This needs to be expanded - or even required? - Rajasekaran to discuss

    http://bit.ly/complexThis

    Epilogue

    A speech at the end of a play that serves as a comment on or a conclusion to what has happened.

    -

    InsertionSort, SelectionSort and MergeSort algorithms were covered in detail, primarily using a Show-And-Tell approach which is most intuitive. Also, the approach is very effective in engaging students of diverse learning capabilities.

    -

    A comparison screenshot of the three sorts in action in “verbose” mode is presented below. The screenshot helps differentiate the three sorting algorithms when they process the same unsorted list as a test case. The curious student will want to trace how the unsorted list becomes a sorted one in each of the three cases.

    +

    InsertionSort, SelectionSort and MergeSort algorithms were covered in detail, primarily using a Show-And-Tell approach which is most intuitive. Also, the approach is very effective in engaging students of diverse learning capabilities.

    +

    A comparison screenshot of the three sorts in action in “verbose” mode is presented below. The screenshot helps differentiate the three sorting algorithms when they process the same unsorted list as a test case. The curious student will want to trace how the unsorted list becomes a sorted one in each of the three cases.

    Verbose Compare

    verbose

    Python Pseudo Code Compare

    +

    UPDATE: May 30, 2022
    +Added bubblesort (for AD3251)
    +bubble

      +
    • bubblesort: compare adjacent elements and swap, as you iterate the list
    • insertionsort : get a key and insert it into sorted sublist
    • selectionsort : select minimum value and swap into sorted sublist
    • mergesort : divide and merge (conquer) of sorted sublists
    • +
    • quicksort: choose a pivot and partition (divide) into big and small sublists and then combine them

    sortCode

    +

    UPDATE: May 30, 2022
    +Added quicksort (for AD3251)
    +qsort

    +

    With the partition function:

    +

    qsort2

    Helper functions

    Three helper functions (insort, min_index and merge) were written and used in the respective sorting implementation.

    These helper functions are very effective in capturing the core of each of the algorithm. Also, they help in presenting the algorithm in an incremental fashion, reducing the cognitive load on the student.

    -
    def  insort(alist, key, j):  
    +
    def  insort(alist, key, j):
         '''insort inserts 'key' into the sorted alist[:j]
    -    so that it remains sorted 
    -    'j' is the current index of 'key' in alist 
    -    '''  
    -    while j > 0 and alist[j-1] > key: 
    -        alist[j] = alist[j-1] 
    -        j -= 1 
    +    so that it remains sorted
    +    'j' is the current index of 'key' in alist
    +    '''
    +    while j > 0 and alist[j-1] > key:
    +        alist[j] = alist[j-1]
    +        j -= 1
         alist[j] = key
     

    http://j.mp/insortCC

    def min_index(alist, i):
         '''function returns the index of the
    -    minimum value in the sublist alist[i:] 
    +    minimum value in the sublist alist[i:]
         '''
    -    n = len(alist) 
    -    min_i = i 
    -    for j in range(i+1, n): 
    -        if alist[j] < alist[min_i]: 
    +    n = len(alist)
    +    min_i = i
    +    for j in range(i+1, n):
    +        if alist[j] < alist[min_i]:
                 min_i = j
         return min_i
     
    @@ -628,7 +638,7 @@

    Helper functions

  • If i is not provided, how will you default it to an appropriate value?
  • http://j.mp/indexMinCC

    -
    def  merge(A, B): 
    +
    def  merge(A, B):
         '''
         merge generates a new sorted list containing
         all elements contained in both sorted lists
    @@ -636,15 +646,15 @@ 

    Helper functions

    C = [] while A and B: smaller = (A if A[0] < B[0] else B).pop(0) - C.append(smaller) - # pick up the residual elements in A or B + C.append(smaller) + # pick up the residual elements in A or B return C + A + B

    http://j.mp/mergeListCC and http://j.mp/unionListCC

    def divideTwo(alist):
         mid = len(alist)//2
         return alist[:mid], alist[mid:]
    -    
    +
     

    http://j.mp/divideTwo - divide a list into two halves

    @@ -652,7 +662,7 @@
  • http://j.mp/butFirstCC and http://j.mp/butLastCC - iterate over a list
  • http://j.mp/rightShiftCC - right shift exactly by one position
  • http://j.mp/swapListCC - swap elements in a list
  • -
  • http://j.mp/enumListCC - manually code out the enumerate function
  • +
  • http://j.mp/enumListCC - manually code out the enumerate function
  • GIF galore

    Which one is which?

    diff --git a/py3/background.js b/py3/background.js index ed41edfc..7e2051f2 100644 --- a/py3/background.js +++ b/py3/background.js @@ -291,6 +291,7 @@ // Event handler for when user input is received. chrome.omnibox.onInputChanged.addListener(function(text, suggest_callback) { setDefaultSuggestion(text); + // console.log("changed:", text); if (!text) { return; } @@ -303,11 +304,13 @@ } var qlower = stripped_text.toLowerCase(); - if ("print".startsWith(qlower)) { - suggestions.push({ + /*if ("print".startsWith(qlower)) { + console.log("***print?"); + suggestions.push({ "content":"http://docs.python.org/release/3.0.1/library/functions.html#print", "description":"print - http://docs.python.org/release/3.0.1/library/functions.html#print"}); - } + + }*/ for (var key in predefined_) { if (key.startsWith(qlower)) { @@ -380,7 +383,8 @@ suggest_callback(suggestions); return; } - + + //console.log(builtin_functions_); if (builtin_functions_) { for (var key in builtin_functions_) { if (key.startsWith(qlower)) { @@ -466,6 +470,7 @@ suggestions.push({"content":stripped_text + " [Development and Coding Search]", "description":["Search for \"", stripped_text, "\" using Develoment and Coding Search - http://www.google.com/cse?cx=005154715738920500810:fmizctlroiw&q=", encodeURIComponent(stripped_text), ""].join('')}); } + // console.log("changed: suggestions", suggestions); suggest_callback(suggestions); }); @@ -508,10 +513,11 @@ return; } + /*console.log("qlower ", qlower); if (qlower == "print") { nav("http://docs.python.org/release/3.0.1/library/functions.html#print"); return; - } + }*/ if (predefined_[qlower]) { nav("http://docs.python.org/3/" + predefined_[qlower]);