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

From PrattWiki
Jump to navigation Jump to search
Line 95: Line 95:
 
** See [[Singularity Functions]] for way too much information - more in lab!
 
** See [[Singularity Functions]] for way too much information - more in lab!
 
*** [[Singularity_Functions#Alternate_Names_for]], [[Singularity_Functions#Building_a_Mystery_Signal]], and [[Singularity_Functions#Accumulated_Differences]] might be particularly helpful!
 
*** [[Singularity_Functions#Alternate_Names_for]], [[Singularity_Functions#Building_a_Mystery_Signal]], and [[Singularity_Functions#Accumulated_Differences]] might be particularly helpful!
 +
 +
=== Lecture 8 ===
 +
* Be sure to use the resources available to you, especially the [http://greenteapress.com/thinkpython2/html/index.html Think Python] links in the [http://classes.pratt.duke.edu/EGR103F18/schedules.html Class Schedule]!
 +
* When checking for valid inputs, sometimes the order of asking the question can be important.  If you want a single non-negative integer, you first need to ask if you have an integer before you ask if something is non-negative.  The right way to go is something like:
 +
<source lang=python>
 +
if not isinstance(n, int) or n<1:
 +
</source>
 +
because if n is not an integer, the logic will be true without having to ask the second question.  This is a good thing, because if n is, for example, a list, asking the question n<1 would yield an error. 
 +
* We built up a program whose end goal was to compare and contrast the time it takes different methods of calculating Fibonacci numbers to run.
 +
* The [https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html plt.plot(x, y)] command has some near cousins:
 +
** [https://matplotlib.org/api/_as_gen/matplotlib.pyplot.semilogy.html plt.semilogy(x, y)] will plot with a regular scale for x and a base-10 log scale for y
 +
** [https://matplotlib.org/api/_as_gen/matplotlib.pyplot.semilogx.html plt.semilogx(x, y)] will plot with a base-10 log scale for x and a regular scale for y
 +
** [https://matplotlib.org/api/_as_gen/matplotlib.pyplot.loglog.html plt.loglog(x, y)] will plot with base-10 log scales in both directions
 +
* Fibonacci comparison program
 +
<div class="mw-collapsible mw-collapsed">
 +
<source lang=python>
 +
# Fibonacci program from class
 +
</source>
 +
<div class="mw-collapsible-content">
 +
<source lang=python>
 +
# -*- coding: utf-8 -*-
 +
"""
 +
Created on Fri Sep 21
 +
 +
@author: DukeEgr93
 +
"""
 +
 +
import time
 +
import numpy as np
 +
import matplotlib.pyplot as plt
 +
 +
 +
def fib(n):
 +
    if not isinstance(n, int) or n < 1:
 +
        print('Invalid input!')
 +
        return None
 +
    if n == 1 or n == 2:
 +
        return 1
 +
    else:
 +
        return fib(n - 1) + fib(n - 2)
 +
 +
 +
"""
 +
fib_dewey based on fibonacci at:
 +
http://greenteapress.com/thinkpython2/html/thinkpython2012.html#sec135
 +
"""
 +
known = {1: 1, 2: 1}
 +
 +
 +
def fib_dewey(n):
 +
    if not isinstance(n, int) or n < 1:
 +
        print('Invalid input!')
 +
        return None
 +
    if n in known:
 +
        return known[n]
 +
    res = fib_dewey(n - 1) + fib_dewey(n - 2)
 +
    known[n] = res
 +
    return res
 +
 +
 +
def fibloop(n):
 +
    if not isinstance(n, int) or n < 1:
 +
        print('Invalid input!')
 +
        return None
 +
    head = 1
 +
    tail = 1
 +
    for k in range(3, n + 1):
 +
        head, tail = head + tail, head
 +
    return head
 +
 +
 +
N = 30
 +
uvals = [0] * N
 +
utimes = [0] * N
 +
 +
mvals = [0] * N
 +
mtimes = [0] * N
 +
 +
lvals = [0] * N
 +
ltimes = [0] * N
 +
 +
for k in range(1, N + 1):
 +
    temp_time = time.clock()
 +
    uvals[k - 1] = fib(k)
 +
    utimes[k - 1] = time.clock() - temp_time
 +
 +
    temp_time = time.clock()
 +
    mvals[k - 1] = fib_dewey(k)
 +
    mtimes[k - 1] = time.clock() - temp_time
 +
 +
    temp_time = time.clock()
 +
    lvals[k - 1] = fibloop(k)
 +
    ltimes[k - 1] = time.clock() - temp_time
 +
 +
for k in range(1, N + 1):
 +
    print('{:2d} {:6d} {:0.2e}'.format(k, uvals[k - 1], utimes[k - 1]), end='')
 +
    print(' {:6d} {:0.2e}'.format(mvals[k - 1], mtimes[k - 1]), end='')
 +
    print(' {:6d} {:0.2e}'.format(lvals[k - 1], ltimes[k - 1]))
 +
 +
k = np.arange(1, N + 1)
 +
plt.figure(1)
 +
plt.clf()
 +
plt.plot(k, utimes, k, mtimes, k, ltimes)
 +
plt.legend(['recursive', 'memoized', 'looped'])
 +
 +
plt.figure(2)
 +
plt.clf()
 +
plt.semilogy(k, utimes, k, mtimes, k, ltimes)
 +
plt.legend(['recursive', 'memoized', 'looped'])
 +
</source>
 +
</div>
 +
</div>
  
 
== Labs ==
 
== Labs ==

Revision as of 16:50, 23 September 2018

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

Lectures

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
  • Piazza page: Piazza 103L page; message board for questions

Lecture 2 - Programs and Programming

  • To play with Python:
    • Install it on your machine or a public machine: Download
    • Use a Duke container with Spyder: Containers - note - these do not have access to your Duke files. More on how to connect that later.
  • 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

Lecture 3

  • 7 Steps for finding prime numbers
  • prime program -- includes intro to input(), if tree, for loop, print(), remainder %

Lecture 4

  • Function definitions
    • Positional and key word arguments (kwargs)
    • Default values
    • Returns tuples -- can be received by a single item or a tuple of the right size
  • Aquarium

Lecture 5

  • print() and format specifications: link
    • Main components are width, precision, and type; sometimes initial +
    • e and f can print integers as floats; d cannot print floats
  • relational and logical operators - how they work on item, string, list, tuple
  • if trees
  • while loops
  • for loops
    • NOTE: in the case of
for y in x
If the entries of x are changed, or really if x is changed in a way that its location in memory remained unchanged, y will iterate over the changed entries. If x is changed so that a copy first has to be made (for example, it is set equal to a slice of itself), then y will iterate over the original entries. Note the differences between:
x = [1, 2, 3, 4, 5]
for y in x:
    print(x, y)
    x[4] = [0]
    print(x, y)

and:

x = [1, 2, 3, 4, 5]
for y in x:
    print(x, y)
    x = x[:-1]
    print(x, y)
  • counting characters program
# letter_typing.py from class:
def check_letters(phrase):
    vowels = "aeiou"
    numbers = "0123456789"
    consonants = "bcdfghjklmnpqrstvwxyz"
    # vowels, numbers, consonants, and other in that order
    count = [0, 0, 0, 0]
    
    for letter in phrase:
        if letter.lower() in vowels:
            count[0] += 1
        elif letter.lower() in numbers: # .lower not really needed here
            count[1] += 1
        elif letter.lower() in consonants:
            count[2] += 1
        else:
            count[3] += 1
            
    return count

out = check_letters("Let's go Duke University 2018!")
print(out)
  • Question in class: does Python have ++ or -- operators; it does not. You need x += 1 or x -= 1

Lecture 7

Lecture 8

  • Be sure to use the resources available to you, especially the Think Python links in the Class Schedule!
  • When checking for valid inputs, sometimes the order of asking the question can be important. If you want a single non-negative integer, you first need to ask if you have an integer before you ask if something is non-negative. The right way to go is something like:
if not isinstance(n, int) or n<1:

because if n is not an integer, the logic will be true without having to ask the second question. This is a good thing, because if n is, for example, a list, asking the question n<1 would yield an error.

  • We built up a program whose end goal was to compare and contrast the time it takes different methods of calculating Fibonacci numbers to run.
  • The plt.plot(x, y) command has some near cousins:
  • Fibonacci comparison program
# Fibonacci program from class
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 21

@author: DukeEgr93
"""

import time
import numpy as np
import matplotlib.pyplot as plt


def fib(n):
    if not isinstance(n, int) or n < 1:
        print('Invalid input!')
        return None
    if n == 1 or n == 2:
        return 1
    else:
        return fib(n - 1) + fib(n - 2)


"""
fib_dewey based on fibonacci at:
http://greenteapress.com/thinkpython2/html/thinkpython2012.html#sec135
"""
known = {1: 1, 2: 1}


def fib_dewey(n):
    if not isinstance(n, int) or n < 1:
        print('Invalid input!')
        return None
    if n in known:
        return known[n]
    res = fib_dewey(n - 1) + fib_dewey(n - 2)
    known[n] = res
    return res


def fibloop(n):
    if not isinstance(n, int) or n < 1:
        print('Invalid input!')
        return None
    head = 1
    tail = 1
    for k in range(3, n + 1):
        head, tail = head + tail, head
    return head


N = 30
uvals = [0] * N
utimes = [0] * N

mvals = [0] * N
mtimes = [0] * N

lvals = [0] * N
ltimes = [0] * N

for k in range(1, N + 1):
    temp_time = time.clock()
    uvals[k - 1] = fib(k)
    utimes[k - 1] = time.clock() - temp_time

    temp_time = time.clock()
    mvals[k - 1] = fib_dewey(k)
    mtimes[k - 1] = time.clock() - temp_time

    temp_time = time.clock()
    lvals[k - 1] = fibloop(k)
    ltimes[k - 1] = time.clock() - temp_time

for k in range(1, N + 1):
    print('{:2d} {:6d} {:0.2e}'.format(k, uvals[k - 1], utimes[k - 1]), end='')
    print(' {:6d} {:0.2e}'.format(mvals[k - 1], mtimes[k - 1]), end='')
    print(' {:6d} {:0.2e}'.format(lvals[k - 1], ltimes[k - 1]))

k = np.arange(1, N + 1)
plt.figure(1)
plt.clf()
plt.plot(k, utimes, k, mtimes, k, ltimes)
plt.legend(['recursive', 'memoized', 'looped'])

plt.figure(2)
plt.clf()
plt.semilogy(k, utimes, k, mtimes, k, ltimes)
plt.legend(['recursive', 'memoized', 'looped'])

Labs

  • Lab 1
    • Unix commands: pwd, cd, ls, mkdir, wget, tar, cp, latex, dvipdf, evince, xeyes
    • Other concepts: MobaXterm, XQuartz, ssh
    • Windows permissions were covered, but were only needed during this one lab.
    • Mounting CIFS drives was covered, but will not be needed for lab 1.
    • Three parts of lab:
      • Once only ever: creating EGR 103 folder, setting Windows permissions
      • Once per lab: creating lab1 folder, wget-ting files, tar expansion, duplicate lab skeleton
      • Doing work: changing to lab1 folder; using emacs, latex, dvipsd, and evince correctly
    • Work on lab every day - at least logging in, changing directories, using (emacs, latex, dvipdf, evince)
    • Work a little at a time to help with debugging