Difference between revisions of "EGR 103/Concept List Fall 2019"

From PrattWiki
Jump to navigation Jump to search
(Lecture 4 - Other Types and Functions)
Line 43: Line 43:
 
** 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 - Other Types and Functions ==
 
== Lecture 4 - Other Types and Functions ==
 
* Lists are set off with [ ] and entries can be any valid type (including other lists!); entries can be of different types from other entries
 
* Lists are set off with [ ] and entries can be any valid type (including other lists!); entries can be of different types from other entries
Line 64: Line 65:
 
** Return returns single item as an item of that type; if there are multiple items returned, they are stored in a tuple
 
** Return returns single item as an item of that type; if there are multiple items returned, they are stored 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
<!--
 
== Lecture 2 - Programs and Programming ==
 
* To play with Python:
 
** Install it on your machine or a public machine: [https://www.anaconda.com/download/ Download]
 
* Quick tour of Python
 
** Editing window, variable explorer, and console
 
** Variable explorer is your friend
 
* From Dewey - programming language typically have ability to work with input, output, math, conditional execution, and repetition
 
* Hilton and Bracy Seven Steps
 
* Class work developing algorithm for program to determine if a number is prime
 
* Inputs in Python using input() command - always grab strings
 
* Convert strings containing integer characters to integers using int()
 
* Some commands are only available by importing from modules; <code>import numpy as np</code> will bring in all the functions of the numpy module.  Access these commands by typing np.VALUE or np.FUNCTION (for example, np.pi or np.cos(2))
 
  
== Lecture 3 - Variable Types ==
+
== Lecture 5 - Format, Logic, Decisions, and Loops ==
* Python has several different variable types, each with their own purpose and operators.
+
* 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 e or f for type, minimumwidth.precision, and possibly a + in front to force printing + for positive numbers.
* Main ones this lecture: int, float, string, tuple, list.
+
* Also - [https://docs.python.org/2/library/string.html#format-specification-mini-language Format Specification Mini-Language]
 +
* Basics of decisions using if...elif...else
 +
* Basics of loops using for and while
 +
* Building a program to count the number of numbers, vowels, consonants, and other characters in a phrase
 +
<div class="mw-collapsible mw-collapsed">
 +
<source lang=python>
 +
# letter_counter.py from class:
 +
</source>
 +
<div class="mw-collapsible-content">
 +
<source lang=python>
 +
def counter(phrase):
 +
    counts = [0, 0, 0, 0]
 +
    nums = "0123456789"
 +
    vowels = "aeiou"
 +
    cons = "bcdfghjklmnpqrstvwxyz"
  
== Lecture 4 - Dictionaries and Functions ==
+
    for k in phrase.lower():
* Brief discussion of dictionaries, how to build, and how to access.
+
        #print(k)
* Two main types of function - lambda functions and defined functions
+
        if k in nums:
* Lambda functions are one line of code; can have multiple inputs but only one expression.
+
            # print('{:s} is a number!'.format(k))
** c = lambda a,b: np.sqrt(a**2 + b**2)
+
            counts[0] += 1
* Defined functions can be multiple lines of code and have multiple outputs.
+
        elif k in vowels:
** Four different types of argument:
+
            counts[1] += 1
*** Required (listed first)
+
        elif k in cons:
*** Named with defaults (second)
+
            counts[2] += 1
*** Additional positional arguments ("*args") (third)
+
        else:
**** Function will create a tuple containing these items in order
+
            counts[3] += 1
*** Additional keyword arguments ("**kwargs") (last)
+
             
**** Function will create a dictionary of keyword and value pairs
+
    return counts
 +
       
 +
if __name__ == '__main__':
 +
    c = counter("Hello! Go 2023! East Campus Rocks!")
 +
    print(c)
 +
</source>
 +
</div>
 +
</div>
 +
<!--
  
 
== Lecture 5 - Format, Logic, Decisions, and Loops ==
 
== Lecture 5 - Format, Logic, Decisions, and Loops ==

Revision as of 18:43, 9 September 2019

This page will be used to keep track of the commands and major concepts for each lecture in EGR 103.

Lecture 1 - Introduction

  • Class web page: EGR 103L; assignments, contact info, readings, etc - see slides on Errata/Notes page
  • Sakai page: Sakai 103L page; grades, surveys and tests, some assignment submissions
  • CampusWire page: CampusWire 103L page; message board for questions - you need to be in the class and have the access code to subscribe.

Lecture 2 - Programs and Programming

Lecture 3 - "Number" Types

  • Python is a "typed" language - variables have types
  • We will use eight types:
    • Focus of the day: int, float, and array
    • Focus a little later: string, list, tuple
    • Focus later: dictionary, set
  • int: integers; Python can store these perfectly
  • float: floating point numbers - "numbers with decimal points" - Python sometimes has problems
  • array
    • Requires numpy, usually with import numpy as np
    • Organizational unit for storing rectangular arrays of numbers
  • Math with "Number" types works the way you expect
    • ** * / // % + -
  • Relational operators can compare "Number" Types and work the way you expect with True or False as an answer
    • < <= == >= > !=
    • 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
  • Slices allow us to extract information from an array or put information into an array
  • a[0] is the element in a at the start
  • a[3] is the element in a three away from the start
  • 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 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 - Other Types and Functions

  • 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
  • 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)
  • 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
  • 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
    • Dictionary at tutorialspoint
  • Defined functions can be multiple lines of code and have multiple outputs.
    • Four different types of input parameters:
      • 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
    • 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 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 5 - Format, Logic, Decisions, and Loops

  • Creating formatted strings using {} and .format() (format strings, standard format specifiers) -- focus was on using e or f for type, minimumwidth.precision, and possibly a + in front to force printing + for positive numbers.
  • Also - Format Specification Mini-Language
  • Basics of decisions using if...elif...else
  • Basics of loops using for and while
  • Building a program to count the number of numbers, vowels, consonants, and other characters in a phrase
# letter_counter.py from class:
def counter(phrase):
    counts = [0, 0, 0, 0]
    nums = "0123456789"
    vowels = "aeiou"
    cons = "bcdfghjklmnpqrstvwxyz"

    for k in phrase.lower():
        #print(k)
        if k in nums:
            # print('{:s} is a number!'.format(k))
            counts[0] += 1
        elif k in vowels:
            counts[1] += 1
        elif k in cons:
            counts[2] += 1
        else:
            counts[3] += 1
               
    return counts
        
if __name__ == '__main__':
    c = counter("Hello! Go 2023! East Campus Rocks!")
    print(c)