1 / 67

JavaScript Loop Statements and Key-Value Mapping Review

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.

nruiz
Download Presentation

JavaScript Loop Statements and Key-Value Mapping Review

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CSE 115 Introduction to Computer Science I

  2. 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

  3. Today's Plan Review Dictionaries (key-value mappings) Coding in repl.it Exercises

  4. 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!

  5. 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!

  6. REVIEW REVIEW REVIEW REVIEW REVIEW REVIEW REVIEW Keywords Matter! • JavaScript's for…of • is analogous to • Python's for…in

  7. REVIEW REVIEW REVIEW REVIEW REVIEW REVIEW REVIEW JavaScript for… loops • for…ofto get values • for…into get indicies HIGH ACCIDENT ZONE AHEAD

  8. 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

  9. 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.

  10. 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

  11. 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.

  12. 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

  13. 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.

  14. 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

  15. Today's Plan Review Dictionaries (key-value mappings) Coding in repl.it Exercises

  16. Key-Value Mappings Common idea found everywhere "Key" mapped to a "value" to make using information easier

  17. 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

  18. 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

  19. 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?' }

  20. Dictionary Printing variable shows ALL the pairings > print(empty) { } > print(majorChamps) {'nyc': 55, 'boston': 37, 'chicago': 29, 'buffalo': 0 }

  21. Visualizing Dictionary Dictionary is an objectin Python Draw box to represent object 55 37 29 0

  22. Visualizing Dictionary Name holds keys Value holds values 55 37 29 0

  23. Dictionaries Values in object usually accessed via keys Must use brackets ([]) to address specific key-value pair > print(majorChamps['nyc']) 55 37 29 0

  24. Dictionaries Values in object usually accessed via keys Must use brackets ([]) to address specific key-value pair > print(majorChamps['nyc']) 55 37 29 0

  25. 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

  26. Dictionaries Values in object usually accessed via keys Must use brackets ([]) to address specific key-value pair >majorChamps['buffalo'] = 1 55 37 29 0

  27. Dictionaries Values in object usually accessed via keys Must use brackets ([]) to address specific key-value pair >majorChamps['buffalo'] = 1> 55 37 29 1

  28. Dictionaries Values in object usually accessed via keys Assignment using new key expands dictionary >majorChamps['la'] = 23 55 37 29 1

  29. Dictionaries Values in object usually accessed via keys Assignment using new key expands dictionary >majorChamps['la'] = 23 55 37 29 1

  30. Dictionaries Values in object usually accessed via keys Assignment statement using new key expands dictionary >majorChamps['la'] = 23 55 37 29 1 23

  31. Dictionaries Values in object usually accessed via keys Assignment statement using new key expands dictionary >majorChamps['la'] = 23> 55 37 29 1 23

  32. 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' }

  33. 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' }

  34. 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

  35. 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

  36. 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

  37. 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' }

  38. Today's Plan Review Dictionaries (key-value mappings) Coding in repl.it Exercises

  39. 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

  40. 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

  41. 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

  42. 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

  43. 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

  44. 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

  45. Dictionary Use Key needed to start, but what if it not found? >majorChamps['rochester'] 0 37 1 23

  46. 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

  47. 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

  48. 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

  49. 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

  50. 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

More Related