Difference between revisions of "EGR 103/Concept List/S23"

From PrattWiki
Jump to navigation Jump to search
(Created page with "== Lecture 1 - 1/11 - Course Introduction == * Main class page: [http://classes.pratt.duke.edu/EGR103S23/ EGR 103L] ** Includes links to Sakai, Pundit, and Ed pages * Sakai pa...")
 
 
(7 intermediate revisions by the same user not shown)
Line 2: Line 2:
 
* Main class page: [http://classes.pratt.duke.edu/EGR103S23/ EGR 103L]
 
* Main class page: [http://classes.pratt.duke.edu/EGR103S23/ EGR 103L]
 
** Includes links to Sakai, Pundit, and Ed pages
 
** Includes links to Sakai, Pundit, and Ed pages
* Sakai page: [https://sakai.duke.edu/portal/site/egr103s23 Sakai 103L page]; grades, surveys and tests, some assignment submissions; first day slideshow in Resources section
+
* Sakai page: [https://sakai.duke.edu/portal/site/egr103s23 Sakai 103L page]; grades, surveys and tests, some assignment submissions; first day slideshow in Resources section goes over everything else.
 
+
== Lecture 2  - 1/13 - Programs and Programming ==
<!--
 
 
 
== Lecture 2  - 8/27 - Programs and Programming ==
 
 
* Almost all languages have input, output, math, conditional execution (decisions), and repetition (loops)
 
* Almost all languages have input, output, math, conditional execution (decisions), and repetition (loops)
* Seven steps of programming [https://adhilton.pratt.duke.edu/sites/adhilton.pratt.duke.edu/files/u37/iticse-7steps.pdf The Seven Steps Poster].  Also, for Monday's class:  
+
* Seven steps of programming [https://adhilton.pratt.duke.edu/sites/adhilton.pratt.duke.edu/files/u37/iticse-7steps.pdf The Seven Steps Poster].  Also, for next Friday's class:  
 
** Watch video on [https://www.coursera.org/lecture/duke-programming-web/developing-an-algorithm-nopgq Developing an Algorithm]
 
** Watch video on [https://www.coursera.org/lecture/duke-programming-web/developing-an-algorithm-nopgq Developing an Algorithm]
 
** Watch video on [https://www.coursera.org/lecture/duke-programming-web/a-seven-step-approach-to-solving-programming-problems-AEy5M A Seven Step Approach to Solving Programming Problems]
 
** Watch video on [https://www.coursera.org/lecture/duke-programming-web/a-seven-step-approach-to-solving-programming-problems-AEy5M A Seven Step Approach to Solving Programming Problems]
 
* Problem: Consider how to decide if a number is a prime number
 
* Problem: Consider how to decide if a number is a prime number
** Some "shortcuts" for specific factors but need to have a generalized approach
+
** Some "shortcuts" for specific factors (2, 3, and 5, for example) but need to have a generalized approach
** See if number is evenly divisible by any integer between 2 and the square root of the number - but how do we ask the computer to do that?
+
** See if number is evenly divisible by any integer between 2 and the square root of the number - but how do we ask the ''computer'' to do that?
* Quick tour of Python
+
* Very quick tour of Python with Spyder
 
** Console (with history tab), variable explorer (with other tabs), and editing window
 
** Console (with history tab), variable explorer (with other tabs), and editing window
** Main numerical types: whole numbers (int) and numbers with decimals (float)
+
 
** Can use % (called "mod") to get "remainder"
+
== Lecture 3 - 1/13 - "Number" Types ==
*** If both items are integers, result is an integer; if either is a float, result is a float
+
* Google Colab notebook available in the [https://drive.google.com/drive/folders/1_RM9uyvXuktDj_QuU3Gwc2tUUKB80rbL?usp=share_link EGR 103 Google Drive folder]
** Relational operators: < <= == >= > !=
 
*** Result is is either <code>True</code> or <code>False</code>
 
 
* Comments in code:
 
* Comments in code:
 
** If there is a <code>#</code>, Python ignores everything remaining in that line after the #
 
** If there is a <code>#</code>, Python ignores everything remaining in that line after the #
 
** If there are <code>"""</code> or <code>'''</code>, Python ignores everything until the closing <code>"""</code> or <code>'''</code>
 
** If there are <code>"""</code> or <code>'''</code>, Python ignores everything until the closing <code>"""</code> or <code>'''</code>
 
** If you use <code># %%</code> in Spyder, the editing window will set up a '''cell''' and light up the cell your cursor is in.  Cells have no impact on how the code runs, just how the code appears in the window  
 
** If you use <code># %%</code> in Spyder, the editing window will set up a '''cell''' and light up the cell your cursor is in.  Cells have no impact on how the code runs, just how the code appears in the window  
 
== Lecture 3 - 9/5 - "Number" Types ==
 
 
* Python is a "typed" language
 
* Python is a "typed" language
 
** Focus of the day: int, float, and array
 
** Focus of the day: int, float, and array
*** int: integers; Python 3 can store these perfectly
+
*** int: integers; Python 3 can store these perfectly up to ginormous sizes
 
*** float: floating point numbers - "numbers with decimal points" - Python sometimes has problems storing floating point items exactly
 
*** float: floating point numbers - "numbers with decimal points" - Python sometimes has problems storing floating point items exactly
** Focus a little later: string, list, tuple
+
* Basic operations for ints and floats
** Focus later: dictionary, set
 
** Focus way later: map, filter, zip
 
* Basic operations and types
 
 
** + - * // (rounded division) and % (remainder / modulo) produce int if both sides are an int, float if either or both are floats
 
** + - * // (rounded division) and % (remainder / modulo) produce int if both sides are an int, float if either or both are floats
** / (regular division) and // (rounded division) produces float with ints or floats
+
** / (regular division) produces float with ints or floats
 
** ** to do powers
 
** ** to do powers
** <code>VAR = input("prompt: ")</code> will ask the user for a value and stores whatever they type as a string (broken in some versions of Spyder!)
+
** Relational operators can compare "Number" Types and work the way you expect with <code>True</code> or <code>False</code> as an answer
 +
*** < <= == >= > !=
 +
** Logical operators can combine (<code>and</code>, <code>or</code>) booleans or reverse (<code> not</code>)
 +
* You can convert strings containing characters that "look" like numbers to ints or floats:
 
** <code>NUM = int(VAR)</code>
 
** <code>NUM = int(VAR)</code>
 
*** If VAR is an int or a float, it will return an int rounded towards 0
 
*** If VAR is an int or a float, it will return an int rounded towards 0
Line 45: Line 38:
 
*** If VAR is an int or a float, it will return a float with the same value
 
*** If VAR is an int or a float, it will return a float with the same value
 
*** If VAR is a string, it will return a float if the string looks like a float, including scientific notation such as <code>float("1.23e4")</code>
 
*** If VAR is a string, it will return a float if the string looks like a float, including scientific notation such as <code>float("1.23e4")</code>
 +
** This is important because <code>VAR = input("prompt: ")</code> will ask the user for a value and stores whatever they type as a '''string'''
 
* Arrays
 
* Arrays
** Python doesn't know everything to start with; may need to import things
+
** Python doesn't know everything to start with; may need to import things - must import numpy for arrays
 
*** <code>import MODULE</code> means using <code>MODULE.function()</code> to run
 
*** <code>import MODULE</code> means using <code>MODULE.function()</code> to run
*** <code>import MODULE as NAME</code> means using <code>NAME.function()</code> to run
+
*** <code>import MODULE as NAME</code> means using <code>NAME.function()</code> to run - this is the most common one for us
 +
*** <code> from MODULE import FUNCTION1, FUNCTION2, ...</code> means using FUNCTION1(), FUNCTION2() as function calls - be careful not to override things
 +
*** <code> from MODULE import *</code> means importing every function and constant from a module into their own name - very dangerous!
 +
** <code>import numpy as np</code> will be a very common part of code for EGR 103
 
** Organizational unit for storing rectangular arrays of numbers
 
** Organizational unit for storing rectangular arrays of numbers
 
** Generally create with np.array(LIST) where depth of nested LIST is dimensionality of array
 
** Generally create with np.array(LIST) where depth of nested LIST is dimensionality of array
 
*** np.array([1, 2, 3]) is a 1-dimensional array with 3 elements
 
*** np.array([1, 2, 3]) is a 1-dimensional array with 3 elements
 
*** np.array([[1, 2, 3], [4, 5, 6]]) is a 2-dimension array with 2 rows and 3 columns
 
*** np.array([[1, 2, 3], [4, 5, 6]]) is a 2-dimension array with 2 rows and 3 columns
* Math with "Number" types works the way you expect
+
** Math with arrays works the way you expect
** ** * / // % + -
+
*** ** * / // % + -
** With arrays, * and / work element by element; *matrix* multiplication is a different character (specifically, @)
+
**** With arrays, * and / work element by element; *matrix* multiplication is a different character (specifically, @)
* Relational operators can compare "Number" Types and work the way you expect with True or False as an answer
+
** Relational operators can compare two arrays that are the same size or an array and a single number
** < <= == >= > !=
+
*** < <= == >= > !=
** With arrays, either same size or one is a single value; result will be an array of True and False the same size as the array
+
*** With arrays, either same size or one is a single value; the result will be an array of True and False the same size as the array
* Slices allow us to extract information from a collection or change information in mutable collections
+
** Slices allow us to extract information from a collection or change information in mutable collections
* a[0] is the element in a at the start
+
*** a[0] is the element in a at the start
* a[3] is the element in a three away from the start
+
*** a[3] is the element in a three away from the start
* a[-1] is the last element of a
+
*** a[-1] is the last element of a
* a[-2] is the second-to-last element of a
+
*** a[-2] is the second-to-last element of a
* a[:] is all the elements in a because what is really happening is:
+
*** a[:] is all the elements in a because what is really happening is:
** a[start:until] where start is the first index and until is just *past* the last index;  
+
**** a[start:until] where start is the first index and until is just *past* the last index;  
** a[3:7] will return a[3] through a[6] in a 4-element array
+
**** a[3:7] will return a[3] through a[6] in a 4-element array
** a[start:until:increment] will skip indices by increment instead of 1
+
**** a[start:until:increment] will skip indices by increment instead of 1
** To go backwards, a[start:until:-increment] will start at an index and then go backwards until getting at or just past until.
+
**** To go backwards, a[start:until:-increment] will start at an index and then go backwards until getting at or just past until.
* For 2-D arrays, you can index items with either separate row and column indices or indices separated by commas:
+
** For 2-D arrays, you can index items with either separate row and column indices or indices separated by commas:
** a[2][3] is the same as a[2, 3]
+
*** a[2][3] is the same as a[2, 3]
** Only works for arrays!
+
*** Only works for arrays!
  
== Lecture 4 - 9/9 - Other Types ==
+
== Lecture 4 - 1/23 - List, Tuple String ==
 +
* Google Colab notebook available in the [https://drive.google.com/drive/folders/1_RM9uyvXuktDj_QuU3Gwc2tUUKB80rbL?usp=share_link EGR 103 Google Drive folder]
 +
* Python script available in the [
 
* Lists are set off with [ ] and entries can be any valid type (including other lists!); entries can be of different types from other entries;  list items can be changed and mutable items within lists can be changed.  Lists can be "grown" by using += with the list or l.append().
 
* Lists are set off with [ ] and entries can be any valid type (including other lists!); entries can be of different types from other entries;  list items can be changed and mutable items within lists can be changed.  Lists can be "grown" by using += with the list or l.append().
 
* Tuples are indicated by commas without square brackets (and are usually shown with parentheses - which are required if trying to make a tuple an entry in a tuple or a list); tuple items cannot be changed but mutable items within tuples can be
 
* Tuples are indicated by commas without square brackets (and are usually shown with parentheses - which are required if trying to make a tuple an entry in a tuple or a list); tuple items cannot be changed but mutable items within tuples can be
Line 98: Line 97:
 
** [https://www.tutorialspoint.com/python/python_lists.htm Lists] at tutorialspoint
 
** [https://www.tutorialspoint.com/python/python_lists.htm Lists] at tutorialspoint
 
** [https://www.tutorialspoint.com/python/python_tuples.htm Tuples] at tutorialspoint
 
** [https://www.tutorialspoint.com/python/python_tuples.htm Tuples] at tutorialspoint
 +
 +
== Lecture 5 - 1/27 - Formatted Printing; Functions==
 +
* Google Colab notebook available in the [https://drive.google.com/drive/folders/1_RM9uyvXuktDj_QuU3Gwc2tUUKB80rbL?usp=share_link EGR 103 Google Drive folder]
 
* Creating formatted strings using {} and .format() ([https://www.python.org/dev/peps/pep-3101/#format-strings format strings], [https://www.python.org/dev/peps/pep-3101/#standard-format-specifiers standard format specifiers]) -- focus was on using s for string and e or f for numerical types, minimumwidth.precision, and possibly a + in front to force printing + for positive numbers.
 
* Creating formatted strings using {} and .format() ([https://www.python.org/dev/peps/pep-3101/#format-strings format strings], [https://www.python.org/dev/peps/pep-3101/#standard-format-specifiers standard format specifiers]) -- focus was on using s for string and e or f for numerical types, minimumwidth.precision, and possibly a + in front to force printing + for positive numbers.
 
** Using {} by themselves will substitute items in order from the <code>format()</code> function into the string that gets created
 
** Using {} by themselves will substitute items in order from the <code>format()</code> function into the string that gets created
 
** Putting a number in the {} will tell <code>format</code> which thing to get
 
** Putting a number in the {} will tell <code>format</code> which thing to get
 
** Format specification comes after a : in the {}; if you do not specify a location index, you still have to put a colon in the {}
 
** Format specification comes after a : in the {}; if you do not specify a location index, you still have to put a colon in the {}
** {:s} means string and {:Xs} where X is an integer means reserve at least that much space for a left-formatted string
+
*** {:s} means string and {:Xs} where X is an integer means reserve at least that much space for a left-formatted string; {:>s} or {:>Xs} where X is a number will right-justify the string
** {:f} means floating point (default 6 digits after decimal point) and {:X.Yf} reserves at least X spaces (including + or - and the . if it is there) with Y digits after the decimal point for t '''right'''-justified number
+
*** {:f} means floating point (default 6 digits after decimal point) and {:X.Yf} reserves at least X spaces (including + or - and the . if it is there) with Y digits after the decimal point for t '''right'''-justified number
** {:e} means floating point (default 6 digits after decimal point) and {:X.Ye} reserves at least X spaces (including + or - and the . if it is there and the letter e and the + or - after the e and the two or three digit number after that) with Y digits after the decimal point for t '''right'''-justified number
+
*** {:e} means floating point (default 6 digits after decimal point) and {:X.Ye} reserves at least X spaces (including + or - and the . if it is there and the letter e and the + or - after the e and the two or three digit number after that) with Y digits after the decimal point for t '''right'''-justified number
* Aside - [https://docs.python.org/3/library/string.html#format-specification-mini-language Format Specification Mini-Language] has all the possibilities; we will cover some but not all of these in later classes
+
** Aside - [https://docs.python.org/3/library/string.html#format-specification-mini-language Format Specification Mini-Language] has all the possibilities; we will cover some but not all of these in later classes
* You can enter numbers in scientific notation with a number followed by the letter 3 and then a number or negative number for the power of 10; for example, <code>x = 6.02e23</code> or <code>e = -1.6e-19</code>
+
** You can enter numbers in scientific notation with a number followed by the letter 3 and then a number or negative number for the power of 10; for example, <code>x = 6.02e23</code> or <code>e = -1.6e-19</code>
 
** float can convert scientific notation as well:
 
** float can convert scientific notation as well:
 
  float("1e-5")
 
  float("1e-5")
 
+
* Lambda functions can have multiple arguments but can perform only one calculation and will return the result of that one calculation: <syntaxhighlight lang=python>fun_name = lambda in_1, in_2, in_3, in_4: CALCULATION</syntaxhighlight>
== Lecture 5 - 9/12 - Functions==
+
** For example:<syntaxhighlight lang=python>hyp = lambda a, b: np.sqrt(a**2 + b**2)</syntaxhighlight>
* Defined functions can be multiple lines of code and have multiple outputs.
+
* Formally defined functions can be multiple lines of code and have multiple outputs.
* The function can see everything in main, but main cannot see things created in the function.
+
** The function can see everything in main, but main cannot see things created in the function.
** Best bet is to pretend the function cannot see things in main - pass everything in that you need to see!
+
*** Best bet is to pretend the function cannot see things in main - pass everything in that you need to see!
*<syntaxhighlight lang=python>
+
**<syntaxhighlight lang=python>
 
  def FNAME(local1, local2, ...):
 
  def FNAME(local1, local2, ...):
 
     CODE
 
     CODE
Line 124: Line 126:
 
**** Function will create a tuple containing these items in order
 
**** Function will create a tuple containing these items in order
 
*** Additional keyword arguments ("**kwargs") (last)
 
*** Additional keyword arguments ("**kwargs") (last)
**** Function will create a dictionary of keyword and value pairs
+
**** Function will create a '''dictionary''' of keyword and value pairs -more about dictionaries later
 
** Function ends when indentation stops or when the function hits a return statement
 
** Function ends when indentation stops or when the function hits a return statement
 
** Return returns single item as an item of that type; if there are multiple items returned, they are stored and returned in a tuple
 
** Return returns single item as an item of that type; if there are multiple items returned, they are stored and returned in a tuple
 
** If there is a left side to the function call, it either needs to be a single variable name or a tuple with as many entries as the number of items returned
 
** If there is a left side to the function call, it either needs to be a single variable name or a tuple with as many entries as the number of items returned
* Dictionaries
 
** Object where the index (called the key) can be any immutable (integer, float, string, or tuple); the value can be anything.
 
  
== Lecture 6 - 9/16 - Loops and Decisions ==
+
== Lecture 6 - 1/30 - Loops and Decisions ==
* The Price is Right!
+
* Google Colab notebook available in the [https://drive.google.com/drive/folders/1_RM9uyvXuktDj_QuU3Gwc2tUUKB80rbL?usp=share_link EGR 103 Google Drive folder]
 
* Logic
 
* Logic
 
** <= < == >= > != work with many types; just be careful about interpreting
 
** <= < == >= > != work with many types; just be careful about interpreting
 
** <code>not</code> can reverse while <code>and</code> and <code>or</code> can combine logical expressions; most expressions can be written in two ways (while/if TRUE or while/if not FALSE)
 
** <code>not</code> can reverse while <code>and</code> and <code>or</code> can combine logical expressions; most expressions can be written in two ways (while/if TRUE or while/if not FALSE)
 +
** in can ask if a character / substring is in a string or if an element is in a list or tuple
 
* Basics of decisions using if...elif...else
 
* Basics of decisions using if...elif...else
 
** Must have logic after if
 
** Must have logic after if
Line 154: Line 155:
 
**** range only creates integers
 
**** range only creates integers
  
== Lecture 7 - 9/19 - Loops and Accounting ==
+
== Lecture 7 - 2/3 - Loops and Accounting ==
 +
* The Price is Right!
 
* Looked at looping through letters in a phrase
 
* Looked at looping through letters in a phrase
 
* Logic: ITEM in THING will be true if ITEM is a subunit of THING
 
* Logic: ITEM in THING will be true if ITEM is a subunit of THING
Line 167: Line 169:
 
** For loop with another for loop
 
** For loop with another for loop
  
== Lecture 8 - 9/23 - Dictionaries ==
+
== Lecture 8 - 2/6 - Dictionaries ==
 
* Dictionaries are collections of key : value pairs set off with { }; keys can be any immutable type (int, float, string, tuple) and must be unique; values can be any type and do not need to be unique
 
* Dictionaries are collections of key : value pairs set off with { }; keys can be any immutable type (int, float, string, tuple) and must be unique; values can be any type and do not need to be unique
 
** [https://www.tutorialspoint.com/python/python_dictionary.htm Dictionary] at tutorialspoint
 
** [https://www.tutorialspoint.com/python/python_dictionary.htm Dictionary] at tutorialspoint
Line 176: Line 178:
 
** Loading lines of text from a file
 
** Loading lines of text from a file
 
** Splitting strings with split
 
** Splitting strings with split
 +
<!--
 
* Don't copy code from a PDF!
 
* Don't copy code from a PDF!
 
** waffle versus wa&#xFB00;le versus wa&#xFB04;e
 
** waffle versus wa&#xFB00;le versus wa&#xFB04;e
 
*** <code>waffle versus wa&#xFB00;le versus wa&#xFB04;e</code>
 
*** <code>waffle versus wa&#xFB00;le versus wa&#xFB04;e</code>
 
** In the first version, the f-f-l are three separate characters, in the second version it is ff-l and in the third, it is ffl; if you try to copy/paste these into Spyder, the words are 6, 5, or 4 characters, respectively!
 
** In the first version, the f-f-l are three separate characters, in the second version it is ff-l and in the third, it is ffl; if you try to copy/paste these into Spyder, the words are 6, 5, or 4 characters, respectively!
 
+
-->
 +
<!--
 
== Lecture 9 - 9/26 - Random Numbers and Logical Masks ==
 
== Lecture 9 - 9/26 - Random Numbers and Logical Masks ==
 
* np.random.randint(low, high, size)
 
* np.random.randint(low, high, size)

Latest revision as of 03:00, 9 February 2023

Lecture 1 - 1/11 - Course Introduction

  • Main class page: EGR 103L
    • Includes links to Sakai, Pundit, and Ed pages
  • Sakai page: Sakai 103L page; grades, surveys and tests, some assignment submissions; first day slideshow in Resources section goes over everything else.

Lecture 2 - 1/13 - Programs and Programming

  • Almost all languages have input, output, math, conditional execution (decisions), and repetition (loops)
  • Seven steps of programming The Seven Steps Poster. Also, for next Friday's class:
  • Problem: Consider how to decide if a number is a prime number
    • Some "shortcuts" for specific factors (2, 3, and 5, for example) but need to have a generalized approach
    • See if number is evenly divisible by any integer between 2 and the square root of the number - but how do we ask the computer to do that?
  • Very quick tour of Python with Spyder
    • Console (with history tab), variable explorer (with other tabs), and editing window

Lecture 3 - 1/13 - "Number" Types

  • Google Colab notebook available in the EGR 103 Google Drive folder
  • Comments in code:
    • If there is a #, Python ignores everything remaining in that line after the #
    • If there are """ or , Python ignores everything until the closing """ or
    • If you use # %% in Spyder, the editing window will set up a cell and light up the cell your cursor is in. Cells have no impact on how the code runs, just how the code appears in the window
  • Python is a "typed" language
    • Focus of the day: int, float, and array
      • int: integers; Python 3 can store these perfectly up to ginormous sizes
      • float: floating point numbers - "numbers with decimal points" - Python sometimes has problems storing floating point items exactly
  • Basic operations for ints and floats
    • + - * // (rounded division) and % (remainder / modulo) produce int if both sides are an int, float if either or both are floats
    • / (regular division) produces float with ints or floats
    • ** to do powers
    • Relational operators can compare "Number" Types and work the way you expect with True or False as an answer
      • < <= == >= > !=
    • Logical operators can combine (and, or) booleans or reverse ( not)
  • You can convert strings containing characters that "look" like numbers to ints or floats:
    • NUM = int(VAR)
      • If VAR is an int or a float, it will return an int rounded towards 0
      • If VAR is a string, it will return an int only if the string looks exactly like an integer
    • NUM = float(VAR)
      • If VAR is an int or a float, it will return a float with the same value
      • If VAR is a string, it will return a float if the string looks like a float, including scientific notation such as float("1.23e4")
    • This is important because VAR = input("prompt: ") will ask the user for a value and stores whatever they type as a string
  • Arrays
    • Python doesn't know everything to start with; may need to import things - must import numpy for arrays
      • import MODULE means using MODULE.function() to run
      • import MODULE as NAME means using NAME.function() to run - this is the most common one for us
      • from MODULE import FUNCTION1, FUNCTION2, ... means using FUNCTION1(), FUNCTION2() as function calls - be careful not to override things
      • from MODULE import * means importing every function and constant from a module into their own name - very dangerous!
    • import numpy as np will be a very common part of code for EGR 103
    • Organizational unit for storing rectangular arrays of numbers
    • Generally create with np.array(LIST) where depth of nested LIST is dimensionality of array
      • np.array([1, 2, 3]) is a 1-dimensional array with 3 elements
      • np.array([[1, 2, 3], [4, 5, 6]]) is a 2-dimension array with 2 rows and 3 columns
    • Math with arrays works the way you expect
      • ** * / // % + -
        • With arrays, * and / work element by element; *matrix* multiplication is a different character (specifically, @)
    • Relational operators can compare two arrays that are the same size or an array and a single number
      • < <= == >= > !=
      • With arrays, either same size or one is a single value; the result will be an array of True and False the same size as the array
    • Slices allow us to extract information from a collection or change information in mutable collections
      • a[0] is the element in a at the start
      • a[3] is the element in a three away from the start
      • a[-1] is the last element of a
      • a[-2] is the second-to-last element of a
      • a[:] is all the elements in a because what is really happening is:
        • a[start:until] where start is the first index and until is just *past* the last index;
        • a[3:7] will return a[3] through a[6] in a 4-element array
        • a[start:until:increment] will skip indices by increment instead of 1
        • To go backwards, a[start:until:-increment] will start at an index and then go backwards until getting at or just past until.
    • For 2-D arrays, you can index items with either separate row and column indices or indices separated by commas:
      • a[2][3] is the same as a[2, 3]
      • Only works for arrays!

Lecture 4 - 1/23 - List, Tuple String

  • Google Colab notebook available in the EGR 103 Google Drive folder
  • Python script available in the [
  • Lists are set off with [ ] and entries can be any valid type (including other lists!); entries can be of different types from other entries; list items can be changed and mutable items within lists can be changed. Lists can be "grown" by using += with the list or l.append().
  • Tuples are indicated by commas without square brackets (and are usually shown with parentheses - which are required if trying to make a tuple an entry in a tuple or a list); tuple items cannot be changed but mutable items within tuples can be
  • Strings are set off with " " or ' ' and contain characters; string items cannot be changed
  • For lists, tuples, and strings:
    • Using + concatenates the two collections
    • Using * with them makes creates a collection with the original repeated that many times
    • Using += will create a new item with something appended to the old item; the "something" needs to be the same type (list, tuple, or string); this may seem to break the "can't be changed" rule but really a += b is a = a + b which creates a new a.
  • Characters in strings have "numerical" values based on the ASCII table (https://www.asciitable.com/)
    • Numbers are earlier than lower case letters; lower case letters are earlier than upper case letters
    • Strings are sorted character by character; if one string is shorter than another, it is considered less
      • " Hello" < "Hi" is True since the "e" comes before the "i"
      • "Zebra" < "apple" is True since the upper case "Z" is before the lower case "a"
      • "go" < "gone" is True since the first two characters match and then the word is done
  • To get the numerical value of a single character, use ord("A") or replace the A with the character you want
  • To get the character a number represents, use chr(NUM)
  • To apply either ord or chr to multiple items, use a map; to see the results, make a list out of the map
  • Trinket

  • To read more:
    • Note! Many of the tutorials below use Python 2 so instead of print(thing) it shows print thing
    • Lists at tutorialspoint
    • Tuples at tutorialspoint

Lecture 5 - 1/27 - Formatted Printing; Functions

  • Google Colab notebook available in the EGR 103 Google Drive folder
  • Creating formatted strings using {} and .format() (format strings, standard format specifiers) -- focus was on using s for string and e or f for numerical types, minimumwidth.precision, and possibly a + in front to force printing + for positive numbers.
    • Using {} by themselves will substitute items in order from the format() function into the string that gets created
    • Putting a number in the {} will tell format which thing to get
    • Format specification comes after a : in the {}; if you do not specify a location index, you still have to put a colon in the {}
      • {:s} means string and {:Xs} where X is an integer means reserve at least that much space for a left-formatted string; {:>s} or {:>Xs} where X is a number will right-justify the string
      • {:f} means floating point (default 6 digits after decimal point) and {:X.Yf} reserves at least X spaces (including + or - and the . if it is there) with Y digits after the decimal point for t right-justified number
      • {:e} means floating point (default 6 digits after decimal point) and {:X.Ye} reserves at least X spaces (including + or - and the . if it is there and the letter e and the + or - after the e and the two or three digit number after that) with Y digits after the decimal point for t right-justified number
    • Aside - Format Specification Mini-Language has all the possibilities; we will cover some but not all of these in later classes
    • You can enter numbers in scientific notation with a number followed by the letter 3 and then a number or negative number for the power of 10; for example, x = 6.02e23 or e = -1.6e-19
    • float can convert scientific notation as well:
float("1e-5")
  • Lambda functions can have multiple arguments but can perform only one calculation and will return the result of that one calculation:
    fun_name = lambda in_1, in_2, in_3, in_4: CALCULATION
    
    • For example:
      hyp = lambda a, b: np.sqrt(a**2 + b**2)
      
  • Formally defined functions can be multiple lines of code and have multiple outputs.
    • The function can see everything in main, but main cannot see things created in the function.
      • Best bet is to pretend the function cannot see things in main - pass everything in that you need to see!
    •  def FNAME(local1, local2, ...):
           CODE
           return THING1, THING2, ...
      
    • Four different types of input parameters - we only really talked about the first three kinds:
      • Required (listed first)
      • Named with defaults (second)
      • Additional positional arguments ("*args") (third)
        • Function will create a tuple containing these items in order
      • Additional keyword arguments ("**kwargs") (last)
        • Function will create a dictionary of keyword and value pairs -more about dictionaries later
    • Function ends when indentation stops or when the function hits a return statement
    • Return returns single item as an item of that type; if there are multiple items returned, they are stored and returned in a tuple
    • If there is a left side to the function call, it either needs to be a single variable name or a tuple with as many entries as the number of items returned

Lecture 6 - 1/30 - Loops and Decisions

  • Google Colab notebook available in the EGR 103 Google Drive folder
  • Logic
    • <= < == >= > != work with many types; just be careful about interpreting
    • not can reverse while and and or can combine logical expressions; most expressions can be written in two ways (while/if TRUE or while/if not FALSE)
    • in can ask if a character / substring is in a string or if an element is in a list or tuple
  • Basics of decisions using if...elif...else
    • Must have logic after if
    • Can have as many elif with logic after
    • Can have an else without logic at the end
    • Flow is solely dependent on indentation!
    • Branches can contain other trees for follow-up questions
  • Basics of loops using while
    • Must have logic; gets evaluated at start and not again until branch ends
    • Useful when you do not know how many times a loop will run (input validation example)
    • break in a loop can break out early
    • continue in a loop goes back to the top early
  • Basics of loops using for
    • for VAR in ITERABLE
      • VAR will take on each item in ITERABLE one at a time; ITERABLE can be a string, list, tuple, array, or range
        • range(N) creates something similar to [0, 1, 2, 3, 4, ..., N-1]
        • range(M, N) creates something similar to [M, M+1, M+2, ..., N-1]
        • range only creates integers

Lecture 7 - 2/3 - Loops and Accounting

  • The Price is Right!
  • Looked at looping through letters in a phrase
  • Logic: ITEM in THING will be true if ITEM is a subunit of THING
    • "a" in "subway" would be True
    • "way" in "subway" would be True
    • "as" in "subway" would be False
  • Many ways to keep track of items
    • Counter variable
    • List with different indices to track different items
  • Many ways to evaluate items
    • For loop with an if tree
    • For loop with another for loop

Lecture 8 - 2/6 - Dictionaries

  • Dictionaries are collections of key : value pairs set off with { }; keys can be any immutable type (int, float, string, tuple) and must be unique; values can be any type and do not need to be unique
  • Storing values in a dictionary
    • Different loops
    • zip
  • Translation demo with Morse code and NATO phonetic alphabet
    • Loading lines of text from a file
    • Splitting strings with split