Difference between revisions of "EGR 103/Concept List/F23"
Jump to navigation
Jump to search
Line 134: | Line 134: | ||
*** Use <code>enumerate(iterable)</code> to create an iterable made up of tuples where the index is entry 0 and the item is entry 1 | *** Use <code>enumerate(iterable)</code> to create an iterable made up of tuples where the index is entry 0 and the item is entry 1 | ||
− | == Lecture | + | == Lecture 9 - 9/25 - More Strings and Dictionaries == |
* Strings | * Strings | ||
** Iterable, so you can use a for loop to go through individual letters | ** Iterable, so you can use a for loop to go through individual letters |
Revision as of 18:45, 28 September 2023
Contents
- 1 Lecture 1 - 8/28 - Course introduction
- 2 Lecture 2 - 9/1 - Introduction to programming
- 3 Lecture 3 - 9/4 - Introduction to Python
- 4 Lecture 4 - 9/8 - Built-in functions, formatted printing
- 5 Lecture 5 - 9/11 - Intro to lists, tuples, and strings; Intro to graphs
- 6 Lecture 6 - 9/15 - Intro to functions
- 7 Lecture 7 - 9/18 - Functions continued; Decisions
- 8 Lecture 8 - 9/22 - Loops
- 9 Lecture 9 - 9/25 - More Strings and Dictionaries
Lecture 1 - 8/28 - Course introduction
- Main class page: EGR 103L
- Includes links to Canvas, Pundit, and Ed pages
- Sakai page: Canvas103L page; grades, surveys and tests, some assignment submissions; first day slideshow in Resources section goes over everything else.
- For next Friday's class:
- Log in at Coursera at Duke
- Watch video on Developing an Algorithm
- Watch video on A Seven Step Approach to Solving Programming Problems
- See Seven steps of programming The Seven Steps Poster.
Lecture 2 - 9/1 - Introduction to programming
- Seven steps of programming The Seven Steps Poster
- Watch video on Developing an Algorithm
- Watch video on A Seven Step Approach to Solving Programming Problems
- Almost all languages have input, output, math, conditional execution (decisions), and repetition (loops)
- 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?
- We can use output to get the computer to ask for a number and we can use input to allow the computer to receive that number
- We can use math and the mod operator (%) to see if one number is evenly divisible by another, a loop to go through all possible relevant divisors, and a decision structure to choose what to do if we determine that a number is not prime.
- Very quick tour of Python with Spyder
- Console (with history tab), info box (with variable explorer, files, and other tabs), and editing window
- Pushing "play" button or hitting F5 will save the script, change the working directory, and run the script
- Quick introduction to variable types: int, float, str
- Quick introduction to indexing: Python is "0" indexed, meaning if there is a collection of items called x, x[0] will be the "first" item in the collection and x[N-1] where N is the total number of items will be the last item. Also, reverse indexing, where x[-1] is the last item and x[-N] is the first item.
Lecture 3 - 9/4 - Introduction to Python
- No lecture due to Labor Day
- See User:DukeEgr93/ld for a summary of work to do instead!
Lecture 4 - 9/8 - Built-in functions, formatted printing
- Python doesn't know everything to start with; may need to import things
import MODULE
means usingMODULE.function()
to run - brings in everything in the module under the module's nameimport MODULE as NAME
means usingNAME.function()
to run - this is the most common one for usfrom MODULE import FUNCTION1, FUNCTION2, ...
means using FUNCTION1(), FUNCTION2() as function calls - be careful not to override thingsfrom MODULE import *
means importing every function and constant from a module into their own name - very dangerous!
- Arrays
- Must import numpy for arrays
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, @)
- ** * / // % + -
- 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
e
and then a number or negative number for the power of 10; for example,x = 6.02e23
ore = -1.6e-19
- float can convert scientific notation as well:
float("1e-5")
- Using {} by themselves will substitute items in order from the
Lecture 5 - 9/11 - Intro to lists, tuples, and strings; Intro to graphs
- 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 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
isa = a + b
which creates a newa
.
- Trinket
- To read more:
- Plotting
- Need to import matplotlib.pyplot as plt
- Create a figure, cerate a set of axes within the figure, plot using that set of axes
- Plots can have different colors, line styles, and/or point styles
- Labels and title are added with the set command
- See Python:Plotting for more info
Lecture 6 - 9/15 - Intro to functions
- Defined functions can be multiple lines of code and have multiple outputs - we looked at a single output.
def FNAME(local1, local2, ...): CODE return THING
- Four different types of input parameters - we only really talked about the first two kinds:
- Required (listed first)
- Named with defaults (second)
- We will cover the other kinds later
- Additional positional arguments ("*args") (third)
- Additional keyword arguments ("**kwargs") (last)
- Function ends when indentation stops or when the function hits a return statement
- Return returns single item as an item of that type
- The function can see things in the console but the console can't see things in the function
- When calling the function, you can put arguments in the order the function expects them to appear or you can give the local names when you call the function. You can do some of both, but the "in order" arguments have to be first; once you name one argument in a function call you *must* name all the rest.
- Four different types of input parameters - we only really talked about the first two kinds:
- Writing test codes
- You will usually test functions by running a script with the function in it; autograders will generally test code by importing the function from your script.
- Python has a default variable called
__name__
that tells you who is running the show - it will be"__main__"
if you run a script from the console and it will be the same as the name of the file if you are importing from that file. - Given that, including the line
if __name__=="__main__":
before test code means the test code will run if you run the script with F5 or the play button but not run if you import the function from the module.
Lecture 7 - 9/18 - Functions continued; Decisions
- Defined functions can be multiple lines of code and have multiple outputs - now lets talk multiple outputs!
def FNAME(local1, local2, ...): CODE return THING1, THING 2
- 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
- <= < == >= > != work with many types; just be careful about interpreting
not
can reverse whileand
andor
can combine logical expressions- 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
Lecture 8 - 9/22 - Loops
- 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
- VAR will take on each item in ITERABLE one at a time; ITERABLE can be a string, list, tuple, array, or range
- Many ways to keep track of items
- Loop over indices and access specific item in iterable
- Loop over iterable and keep a separate counter variable
- Use
enumerate(iterable)
to create an iterable made up of tuples where the index is entry 0 and the item is entry 1
- for VAR in ITERABLE
Lecture 9 - 9/25 - More Strings and Dictionaries
- Strings
- Iterable, so you can use a for loop to go through individual letters
- for idx, letter in enumerate(the_string): could be handy
- the_string.split("something") will create a list of strings based on splitting the_string at "something" - usually a space with " "
- "glue".join(a_list) will take strings that are elements in the list and put them into a single string separated by the glue
- ord(char) will give the numerical value of that character; chr(num) will give the character at number num
- Dictionaries
- Collections whose indices are immutables (integer, float, string, tuple)
- Built with d={key1:values, key2:value2}
- Extended with d[newkey]=newvalue
- Look up values with d[key] or d.get(key) or d.get(key, other); for the latter two, if key is not in the dictionary, the get version will return None or other if other is an option.
- d.keys() will give the keys, d.value() will give the values, and d.items() will give tuples containing the key and the values - the latter is very useful for making a loop using for idx, val in d.items():