670 likes | 681 Views
This lab activity reviews loop statements in JavaScript and key-value mapping using dictionaries. Learn how to write for...of and for...in loops and work with key-value pairs.
E N D
CSE 115 Introduction to Computer Science I
UBInfinite Requirements • For Lab ActivityThis WeekALL of M2 JavaScript • from Expressions to Module 2 - JS For Lab ActivityNext weekModule 2 – Lists &Module 2 - Arrays • must be completed
Today's Plan Review Dictionaries (key-value mappings) Coding in repl.it Exercises
REVIEW REVIEW REVIEW REVIEW REVIEW REVIEW REVIEW Loop Statement Subgoal • loop1) Determine the collection whose values you want to process • loop2) Write the loop headera) Write the for keyword • b) Write the name of the loop variable • c) Write the in keyword • d) Write the name of the collection • loop3) Write the ':' delimiter • loop4) Write the loop body, indented consistently • a) The loop variable is assigned a value BEFORE the body is executed: do not assign a value to the loop variable!
REVIEW REVIEW REVIEW REVIEW REVIEW REVIEW REVIEW Loop Statement Subgoal • loop1) Determine the collection whose values you want to process • loop2) Write the loop headera) Write the for keywordb) Write an open parenthesis • c) Write the let keyword & name of the loop variable • d) Write the of keyword • e) Write the name of the collectionf) Write a close parenthesis • loop3) Write the { and } delimiters • loop4) Write the loop body inside the delimiters • a) The loop variable is assigned a value BEFORE the body is executed: do not assign a value to the loop variable!
REVIEW REVIEW REVIEW REVIEW REVIEW REVIEW REVIEW Keywords Matter! • JavaScript's for…of • is analogous to • Python's for…in
REVIEW REVIEW REVIEW REVIEW REVIEW REVIEW REVIEW JavaScript for… loops • for…ofto get values • for…into get indicies HIGH ACCIDENT ZONE AHEAD
REVIEW REVIEW REVIEW REVIEW REVIEW REVIEW REVIEW range • range([start, ]stop[, step])0 default value of start; 1 default value of step • Examples range(5)consists of values 0, 1,2,3, and 4 range(3, 7)consists of values 3, 4,5,and 6 range(3, 7, 2)consists of values 3and 5 range(3, 8, 2)consists of values 3, 5,and 7
keep_long_strings • Define function whose input is • an array of strings • a list of strings • Returns a new array/list containing only those strings from the argument whose length is greater than 4. • Maintain the (relative) order of items.
REVIEW REVIEW REVIEW REVIEW REVIEW REVIEW REVIEW keep_long_strings # Return a new list containing the# strings longer than 4 charactersdef keep_long_strings(lst): answer = [ ] for st in lst : if len(st) > 4 :answer.append(st) return answer // Return a new array containing the// strings longer than 4 characters function keep_long_strings(lst) { let answer = [ ]; for (let st of lst) { if (st.length > 4) {answer.push(st); } } return answer;} Accumulator code patterncommon solution found everywhere
REVIEW REVIEW REVIEW REVIEW REVIEW REVIEW REVIEW remove_vowels • Define a function whose input is • a String • a str • Returns a new String/str like the argument, but with all the vowels removed. • Maintain the (relative) order of characters.
REVIEW REVIEW REVIEW REVIEW REVIEW REVIEW REVIEW remove_vowels Line continuation character (must be last character on line) def isVowel(ch) : c = ch.lower() return c=='a' or c=='e' or\ c=='i' or c=='o' or\ c=='u' def remove_vowels( s ) : answer = "" for e in s : if not isVowel(e) : answer = answer + e return answer function isVowel(ch) { let c = ch.toLowerCase(); return c=='a' || c=='e' || c=='i' || c=='o' || c=='u'; } function remove_vowels(s) { let answer = ""; for (let e of s) { if (!isVowel(e)) { answer = answer + e; } } return answer;} Add functions to simplifyproblem solving process
REVIEW REVIEW REVIEW REVIEW REVIEW REVIEW REVIEW every_other • Define function whose input is • an array • a list • Returns a new array/list containing only those entries from the argument at odd indicies. • Maintain the (relative) order of items.
REVIEW REVIEW REVIEW REVIEW REVIEW REVIEW REVIEW every_other # Return a new list containing the# entries at odd indicesdef every_other(lst) : answer = [ ] for i in range(len(lst)) : if (i % 2) == 1 :answer.append(lst[i]) return answer // Return a new array containing the// entries at odd indices function every_other(rA){ let answer = [ ]; for (let iinrA) { if ((i%2) == 1) {answer.push(rA[i]); } } return answer;} Focus on solving problems;language is HOW we do this
Today's Plan Review Dictionaries (key-value mappings) Coding in repl.it Exercises
Key-Value Mappings Common idea found everywhere "Key" mapped to a "value" to make using information easier
Simple vs Compound expressions statements values compound 13.79 * 12 compound if { … } else { … } compound [ 42, 17, -318 ] simple 13.79 simple x = e simple 13.79
Simple vs Compound expressions statements values compound 13.79 * 12 compound if { … } else { … } compound [ 42, 17, -318 ]{'nyc':55,'bos':37} simple 13.79 simple x = e simple 13.79
Dictionary • Type of value holding key-value pairs Usually assigned to variable (just like any other value) To create a value, write pairings inside braces ({ }) empty = { } • majorChamps = {'nyc': 55, "boston": 37, \ "chicago": 29, 'buffalo': 0}legalButWeird = {'dc': 3,'twin cities': "2", \4: 'consistency?' }
Dictionary Printing variable shows ALL the pairings > print(empty) { } > print(majorChamps) {'nyc': 55, 'boston': 37, 'chicago': 29, 'buffalo': 0 }
Visualizing Dictionary Dictionary is an objectin Python Draw box to represent object 55 37 29 0
Visualizing Dictionary Name holds keys Value holds values 55 37 29 0
Dictionaries Values in object usually accessed via keys Must use brackets ([]) to address specific key-value pair > print(majorChamps['nyc']) 55 37 29 0
Dictionaries Values in object usually accessed via keys Must use brackets ([]) to address specific key-value pair > print(majorChamps['nyc']) 55 37 29 0
Dictionaries Values in object usually accessed via keys Must use brackets ([]) to address specific key-value pair > print(majorChamps['nyc'])55 55 37 29 0
Dictionaries Values in object usually accessed via keys Must use brackets ([]) to address specific key-value pair >majorChamps['buffalo'] = 1 55 37 29 0
Dictionaries Values in object usually accessed via keys Must use brackets ([]) to address specific key-value pair >majorChamps['buffalo'] = 1> 55 37 29 1
Dictionaries Values in object usually accessed via keys Assignment using new key expands dictionary >majorChamps['la'] = 23 55 37 29 1
Dictionaries Values in object usually accessed via keys Assignment using new key expands dictionary >majorChamps['la'] = 23 55 37 29 1
Dictionaries Values in object usually accessed via keys Assignment statement using new key expands dictionary >majorChamps['la'] = 23 55 37 29 1 23
Dictionaries Values in object usually accessed via keys Assignment statement using new key expands dictionary >majorChamps['la'] = 23> 55 37 29 1 23
Pick Correct Declaration Convince Your Neighbor Your Answer Is Correct • Which correctly declares dictionary having 3key-value pairs: • dictA = [ 'one':1, 'dos':2, \ 'four': 5] • dictB = { 'length' : 3} • dictC = { 'uno':0, 'two':0, \ 'cse4ever':'zero' } • dictD = { 'uno':1, 'uno':2, \ 'hertz':'uno' }
Pick Correct Declaration • Which correctly declares dictionary having 3key-value pairs: • dictA = [ 'one':1, 'dos':2, \ 'four': 5] • dictB = { 'length' : 3} • dictC = { 'uno':0, 'two':0, \ 'cse4ever':'zero' } • dictD = { 'uno':1, 'uno':2, \ 'hertz':'uno' }
Pick Correct Declaration • Which correctly declares dictionary having 3key-value pairs: • dictA = [ 'one':1, 'dos':2, \ 'four': 5] • dictB = { 'length' : 3} • dictC = { 'uno':0, 'two':0, \ 'cse4ever':'zero' } • dictD = { 'uno':1, 'uno':2, \ 'hertz':'uno' } Must use { }for Dictionary declaration
Pick Correct Declaration • Which correctly declares dictionary having 3key-value pairs: • dictA = [ 'one':1, 'dos':2, \ 'four': 5] • dictB = { 'length' : 3} • dictC = { 'uno':0, 'two':0, \ 'cse4ever':'zero' } • dictD = { 'uno':1, 'uno':2, \ 'hertz':'uno' } Only 1 pair defined;key is 'length'and its value is 3
Pick Correct Declaration • Which correctly declares dictionary having 3key-value pairs: • dictA = [ 'one':1, 'dos':2, \ 'four': 5] • dictB = { 'length' : 3} • dictC = { 'uno':0, 'two':0, \ 'cse4ever':'zero' } • dictD = { 'uno':1, 'uno':2, \ 'hertz':'uno' } Eachkeymapped to at most 1value
Pick Correct Declaration • Which correctly declares dictionary having 3key-value pairs: • dictA = [ 'one':1, 'dos':2, \ 'four': 5] • dictB = { 'length' : 3} • dictC = { 'uno':0, 'two':0, \ 'cse4ever':'zero' } • dictD = { 'uno':1, 'uno':2, \ 'hertz':'uno' }
Today's Plan Review Dictionaries (key-value mappings) Coding in repl.it Exercises
Dictionaries Values in object usually accessed via keys Removing an entry is harder; any value is a valid value >majorChamps['nyc'] = 0 55 37 29 1 23
Dictionaries Values in object usually accessed via keys Removing an entry is harder; any value is a valid value >majorChamps['nyc'] = 0 0 37 29 1 23
Dictionaries Values in object usually accessed via keys Removing an entry is harder; any value is a valid value >majorChamps['nyc'] = 0> 0 37 29 1 23
Dictionary Function:pop() Values in object usually accessed via keys Must delete key-value pair; easiest using pop(key) >majorChamps.pop('chicago') 0 37 29 1 23
Dictionary Function:pop() Values in object usually accessed via keys Must delete key-value pair; easiest using pop(key) >majorChamps.pop('chicago')29 0 37 29 1 23
Dictionary Function:pop() Values in object usually accessed via keys Must delete key-value pair; easiest using pop(key) >majorChamps.pop('chicago')29 0 37 1 23
Dictionary Use Key needed to start, but what if it not found? >majorChamps['rochester'] 0 37 1 23
Dictionary Use Key needed to start, but what if it not found? >majorChamps['rochester'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'rochester' 0 37 1 23
Dictionary Operators:in & not in Evaluates toTrueif validkeypassed in call Boolean result often used as guard in selection statement >'rochester' in majorChamps False 0 37 1 23
Dictionary Operators:in & not in Evaluates toTrueif validkeypassed in call Boolean result often used as guard in selection statement >'buffalo' in majorChamps True 0 37 1 23
Dictionary Operators:in & not in Evaluates toTrueif validkeypassed in call Boolean result often used as guard in selection statement >37 not in majorChamps True 0 37 1 23
Dictionary Methods: get() Callget()if uncertain whether key added If key in Dictionary, function returns the mapped value >majorChamps.get('nyc', False) 0 37 1 23