EGR 103/Fall 2020/Test 1

From PrattWiki
Revision as of 17:09, 2 October 2020 by DukeEgr93 (talk | contribs) (Created page with "== ints and floats == * Operators (** * / % // + -) -- work as expected as long as you expect x**y to be x to the yth power! * += and -= to add or subtract a value from a vari...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

ints and floats

  • Operators (** * / % // + -) -- work as expected as long as you expect x**y to be x to the yth power!
  • += and -= to add or subtract a value from a variable
  • Relational operators (< <= == >= > !=)
  • round(blah, [ndigits=0]) -- rounds to the 10**(-ndigits) place; round(123.456, -1) is 120.0 for instance.
  • int(blah) returns the integer value of blah if blah is a string with a valid integer in it; error otherwise
  • float(blah) returns the float value of blah if blah is a string with a valid float in it; error otherwise

arrays

  • rectangular sequences of numbers (ints or floats)
  • create using np.array(COLLECTION) where COLLECTION could be a list, list of lists, tuple, tuple of tuples, etc - must be rectangular
  • + between arrays will add corresponding elements; + between an array and a number will add that number to each element
    • -, *, /, **, //, and % work in similar fashion
  • np.TRIG() (where TRIG is cos, sin, etc) works on an array -- note that m.TRIG() will not work on an array
  • no compact way to append an array
    • x = np.append(x, NEW) works but is a little clunky
  • slicing
  • Use ARRAY.max() ARRAY.min() and ARRAY.mean() to get max, min, and average
    • collection.copy() to create duplicate list somewhere else in memory

lists

  • Sequence made up of any types of items, including other lists
  • + will concatenate lists ([1, 2] + [3] yields [1, 2, 3])
    • Have to be lists -- [1, 2] + 3 yields an error!
  • += will append an item to a list - that item must be a list!
  • * will repeat lists -- [1, 2] * 3 yields [1, 2, 1, 2, 1, 2]
  • Useful commands (assume the variable collection is a list):
    • list(map()) or list(string) or list(range()) can convert those types into lists of things - useful for viewing and manipulating
    • stuff.join(collection) -- takes the elements in the list and joins them into a single string, using the characters in the variable stuff to join them. Commonly, stuff will simply be so the items in the list are all put directly next to each other.
    • sum(collection), max(collection), min(collection) -- returns the appropriate value if all items are the same type (i.e. all numbers or all strings or all lists) -- sum only works on numbers
    • len(collection) -- returns the number of items in the list; note len([[1, 2], (3, 4, 5)]) is 2 because there are two items in the list - a list and a tuple.
    • collection.count(thing) -- returns the number of times the thing appears in the list
    • slicing
    • collection.copy() to create duplicate list somewhere else in memory
    • map(command, collection) will return a map with the command applied to each entry in the collection; use list(map(command, collection)) to actually see what happened
  • (simple) Comprehensions [EXPRESSION for VARIABLE in ITERABLE if LOGIC]

tuples

  • Immutable - cannot change values
  • Sequence made up of any types of items, including other tuples
  • Single-element tuples created by putting , after item: x = (3,)
  • + will concatenate tuples ((1, 2) + (3,) yields (1, 2, 3))
    • Have to be tuples -- (1, 2) + 3 or (1, 2) + (3) both yield an errors!
  • += will append an item to a tuple and replace the old tuple with the new one - that item must be a tuple!
  • * will repeat tuples -- (1, 2) * 3 yields (1, 2, 1, 2, 1, 2)
  • Useful commands (assume the variable collection is a tuple):
    • sum(collection), max(collection), min(collection) -- returns the appropriate value if all items are the same type (i.e. all numbers or all strings or all lists) -- sum only works on numbers
    • len(collection) -- returns the number of items in the tuple; note len(([1, 2], (3, 4, 5))) is 2 because there are two items in the tuple - a list and a tuple.
    • collection.count(thing) -- returns the number of times the thing appears in the list
    • slicing
    • collection.copy() to create duplicate list somewhere else in memory
    • map(command, collection) will return a map with the command applied to each entry in the collection; use list(map(command, collection)) to actually see what happened

strings

  • Immutable - cannot change characters
  • + will concatenate strings ('Go' + ' ' + 'Duke' yields 'Go Duke')
  • * will repeat strings ('Go' * 4 yields 'GoGoGoGo')
  • str(blah) creates a string from the entries in blah (generally an int or float)
  • ord(letter) can work on a single-character to return the ASCII value of that single letter; chr(number) will give the string related to the ASCII value of number. Since this only works on one character, need to map it to get all of them.
  • len(blah) returns the number of characters in the string blah.
  • max(STRING) returns a single character from STRING based on ord value; max(STRING1, STRING2, ...) returns the STRING latest in the alphabet. min works in a similar way.
  • Useful commands (assume the variable phrase is some string):
    • phrase = input("prompt: ") -- input always gets a string, use int() or float() to convert to something else if needed
    • phrase.lower(), phrase.upper(), phrase.capitalize() -- returns a string with words having appropriate cases
    • phrase.count(string) -- returns the number of times the string occurs in the phrase or 0 if it does not appear
    • phrase.find(string) -- returns the index where the string first appears in the phrase or -1 if it does not appear
    • phrase.split(string) -- looks for the string in the phrase and breaks the phrase up into a list of strings
    • phrase.strip(string) -- not on the test but spiffy -- looks for characters in the string at the start or end of a phrase and removes all of them
In [1]: phrase = 'aaababbleaaaaa'

In [2]: phrase.strip('a')
Out[2]: 'babble'

In [3]: phrase.strip('ab')
Out[3]: 'le'

slicing

  • work on arrays, strings, lists, and tuples
  • thing[a:b:c] will slice the elements in thing starting with the ath item and going to just before the bth item, skipping c items at a time.
  • For a thing with N elements,
    • Default for a is 0 if c is positive or N if c is negative
    • Default for b is N if c is positive or "up to and including the 0th entry" if c is negative
  • If going backwards, you must include a negative c; thing[4:2] will return an empty version the same type as thing
  • For lists of lists (or tuples of tuples) or arrays, can cascade indices like q[2][4]
  • FOR ARRAYS ONLY can use x[row(s), col(s)]

logic

  • Logical operators (not, and, or)
  • "in" operator
    • check if integer is in a list or tuple
    • check if a letter or string is in a list of strings or in a string -- note difference between "Ha" in "Happy" (which is True) and "Ha" in ["Happy"], which is false
    • Note: if you are checking if a list is in another list, the whole list has to be there as a list! So, 1 in [1, 2, 3] is true, [1] in [1, 2, 3] is false, and [1] in [[1], 2, 3] is true.

math

  • requires import math or import math as m
  • Constants: m.pi and m.e
  • Trig -- only works on a single value (m.sin(), m.cos(), m.asin(), etc); degrees are in radians
  • Rounding -- m.ceil(), m.floor(); may be preferred to np.ceil() and np.floor() since numpy version returns floats
  • Others:
    • m.log(x, [b==m.e]) returns base b logarithm of x
    • m.exp(x) returns m.e**x

numpy

  • requires import numpy or import numpy as np
  • np.linspace()
  • np.where()
  • np.random.randint(), np.random.uniform(), np.random.normal(), np.random.seed()
  • np.polyfit(x, y, ord) and np.polyval(coefs, new_x)
  • np.loadtxt('filename')
  • np.min(), np.mean(), np.max()

pandas

  • requires import pandas or import pandas as pd
  • For this test, primarily used for loading data - see Pandas#File_Types
  • Values are loaded in a dataframe; use DATAFRAME.iloc[ROW,COL] to slice values

logical masks

  • (Logic) * (Formula)
  • Unit step function:
def u_step(x):
    (x>=0) * (1)

printing

  • Be able to use print using replacement fields and the format command
  • Given a replacement field of the form "{" [field_name] ["!" conversion] [":" format_spec] "}", be able to use:
    • field name: if blank, take next field on stack; if a number, take that entry in the stack
    • conversion - N/A
    • format spec - given the general format spec of [[fill]align][sign][#][0][width][,][.precision][type], be able to use:
      • sign: if this is +, put - and + in front of numbers; otherwise, ignore +
      • 0: print 0s to left of number if it is not taking up all the space
      • width: reserve at least this much space to print the number; if the number needs more space, it will take it. If it needs left, default alignment is to the right for a number and to the left for a string
      • precision: number of digits after the decimal point
      • type: s for strings, f for regular floating point, e for scientific notation, d for decimal integer
  • default is for print to append '\n' to go to next line; use print(thing, end="") to stop that from happening


plotting

  • requires import matplotlib.pyplot as plt
  • Start with
fig,ax = plt.subplots(num=1, clear=True)
or
fig = plt.figure(num=1, clear=True)
ax = fig.add_subplot(1, 1, 1)
  • ax.plot(y)
  • ax.plot(x, y)
  • ax.plot(x, y, format)
  • ax.plot(x, y, 'bo-', markersize=3, markerfacecolor='r', markeredgecolor = 'b', label='hello!')
    • Or: ax.plot(x, y, 'bo-', ms=3, mfc='r', mec = 'b', label='hello!')
  • ax.legend()
  • ax.set(xlabel='text', ylabel='text', title='text')
    • Alternately: ax.set_xlabel('text'), ax.set_ylabel('text'), ax.set_title('text')
  • ax.grid(True)
  • fig.savefig(NAME)
  • Need to know for the format:
    • colors: b g r c m y k w
    • line styles: - -- -. :
    • marker styles: . o s + D
    • Can only put one color in format
    • If using kwargs (i.e. markersize, mfc, mec, label), each item to be plotted needs its own ax.plot() command

functions

  • definition and default cases
  • required inputs / positional arguments
  • returns (returns a tuple - can either grab all or each individually)

program flow

  • if trees
    • May include multiple elif branches
    • May include else branch at the end
  • while loops
  • for loops
    • for k in LIST: iterates over each item in the list
    • for k in TUPLE: iterates over each item in the tuple
    • for k in STRING: iterates over each character in the string
    • for k in range(stop): iterates over integers from 0 to stop-1
    • for k in range(start, stop): iterates over integers from start to stop-1
    • for k in range(start, stop, step): iterates over integers from start by step to the value before hitting or going over stop
  • for idx,val in enumerate(ITERABLE): provides an index in idx and the value in that index in val
  • nested versions of all of the above
  • break and continue in loops

dictionaries

  • Be able to start a dictionary from scratch with {}
  • Be able to add new key/value pairs to dictionaries
  • Be able to change values in dictionaries
  • Be able to check if a key exists without breaking Python if it doesn't
  • Be able to have a dictionary return a default value if a key doesn't exist
  • Be able to iterate over the keys, the values, or both at once
  • d.keys() returns a collection of the keys (arguments)
  • d.values() returns a collection of the values (function values)
  • d.items() returns a collection of tuples with (key, value)

binary

  • Given an integer in base 10 be able to convert it to base 2
  • Given a whole number in base 2 be able to convert it to base 10
    • There will be no fractional parts on the test

linear algebra

  • Know the conditions two matrices must satisfy to be multipled together using matrix multiplication.
  • Show the process for multiplying two matrices together by hand.
  • Given a set of linear algebra equations, be able to rearrange and write them in matrix form.
  • Be able to calculate by hand the determinant of matrices up to 3x3 and the inverses of matrices up to 2x2.

Not on test

  • Chapra 4.2 from memory
  • LaTeX
  • UNIX
  • NiDAQmx
  • isinstance(), raise
  • Norms and condition numbers