Difference between revisions of "EGR 103/Fall 2018/Test 1"
Jump to navigation
Jump to search
Line 69: | Line 69: | ||
* If going backwards, you must include a negative c; thing[4:2] will return an empty version the same type as thing | * If going backwards, you must include a negative c; thing[4:2] will return an empty version the same type as thing | ||
− | == | + | == logic == |
* Logical operators (not, and, or) | * 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 different between <code>"Ha" in "Happy"</code> (which is True) and <code>"Ha" in ["Happy"]</code>, which is false | ||
+ | ** Note: if you are checking if a list is in another list, the whole list has to be there! So, <code>1 in [1, 2, 3]</code> is true, <code>[1] in [1, 2, 3]</code> is false, and <code>[1] in [[1], 2, 3]</code> is true. | ||
== math == | == math == | ||
Line 89: | Line 93: | ||
* np.loadtxt('filename') | * np.loadtxt('filename') | ||
− | == | + | == logical masks == |
* (Logic) * (Formula) | * (Logic) * (Formula) | ||
* Unit step function: | * Unit step function: |
Latest revision as of 20:02, 11 October 2018
Contents
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
- float(blah) returns the float value of blah if blah is a string with a valid float in it
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
- 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
- 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.
- 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) -- 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'
slices
- work on 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
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 different 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! 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()
- 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')
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
- fill, align, #, , - N/A
- 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
- plt.figure()
- plt.clf()
- plt.plot(y)
- plt.plot(x, y)
- plt.plot(x, y, format)
- plt.plot(x, y, 'bo-', markersize=3, markerfacecolor='r', markeredgecolor = 'b', label='hello!')
- plt.legend()
- plt.xlabel(), plt.ylabel(), plt.title(), plt.grid()
- plt.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 line and marker (and for marker, markeredgecolor and markerface color) are different, use kwargs
- If using kwargs, each item to be plotted needs its own plt.plot() command
functions
- definition and default cases
- returns (returns a tuple - can either grab all or each individually)
program flow
- if trees
- while loops
- for loops
- break and continue in loops
- nested versions of all of the above
Not on test
- LaTeX
- UNIX
- Turtles
- PyDAQmx
- Chapra 4.2
- isinstance(), raise
- binary