Python Functions
format( )
"Sammy has {} balloons.".format(value) takes a value (str, int, double) and substitutes it in for the {} in a string ** "{:3}".format(number) was used in asn2 to produce even columns
Binary Search
- How it works: - Sets a low(first value in the list), mid (center value in the list), and high(last value in list). - Tests to see if the target value is the mid value - if yes, that value is returned - if no, the low, mid and high values are reset - if the the target value is greater than the mid value, the low is set to the original mid, high stays the same, and mid is set to halfway between - if the the target value is less than the mid value, the high is set to the original mid, low stays the same, and mid is set to halfway between - repeat until value is found or low> - faster than linear search for longer lists - cost = a(log(base 2) n+1) **at worst
Linear Search
- How it works: consecutively checks each value in the list until the target value is found or the end of the list is reached (meaning that the target value isn't in the list) - faster than binary search for short lists - cost = an+b
What data structures can you slice?
- lists and tuples - use the slice( ) method to slice objects
Increasing order of functions (used for simplifying a cost function)
1, log(n), nlogn, n, n^2, n^3,...., 2^n, 3^n,....., n!
Bubble Sort
1. Compares first and values, puts them in order. 2. Compares second and third values, puts them in order...... 3. Compares the last and one from the last values, puts them in order. ****At this point, the last value in the list is certainly the highest value in the list - meaning it no longer has to be considered in future iterations.**** 4. The whole process is repeated from the beginning of the list again, leaving out the last value in the list. 5. All of this is repeated until there are no more values to test (every value except the first one has become the end item)
What terms are used to test equality?
== (and) !=
What is a tuple?
A data structure similar to a list, except that it is immutable
What are finite state machines?
A model that can be implemented into software that maps out all of the possible outcomes of some code.
What is list comprehension?
An (often) more concise way to create a list.
clear( )
Clears all of the elements out of a dictionary or list
How do you simplify a cost function?
Ex: f(n) = ((n^2)/100 + 2^5 n+ (3n)/9) * (22^100 +3nlogn) 1.) remove the constant multipliers f(n) = (n^2 + n + n) * (1+nlogn) 2.) if summing two functions, discard lower order functions f(n) = (n^2)*(nlogn) 3.) simplify and add big O = O(n^3 *logn) ***This method doesn't work with very large constants
The following code is an example of which type of search? if x in a: ....
Linear Search
What is the cost of a binary search?
O(log(base2)n)
What is the cost of a for loop?
O(n)
What is the cost of a linear search?
O(n)
What is the cost of a bubble sort?
O(n^2)
What is the cost of a nested for loop?
O(n^2) (usually)
What are split and join in relation to each other?
They undo one another.
What an example of a list comprehension with 2 changing values?
[(x,y) for x in range(5) for y in range(2,8), if x%2==0]
What is the syntax for slicing?
[start_index : end_index+1: increment] - start .index is the first element, end_index is the last, increment tells how many elements to skip before printing the next element - if increment is left out, it is set to go over ever element in the range - if the start is left out, it starts from 0 - if the end is left out, it goes to the end of the list or tuple - if all 3 are left out, it's the whole list or tuple
abs( )
abs(num) - Takes an int or float parameter and returns the absolute value of that parameter
How do you construct a 2D list?
arr_name = [ ] for row in range(num_rows+1): arr_name.append([ ]) for col in range(num_columns): arr_name[-1].append(' ')
How do you construct a list?
arr_name = [item1, item2...]
What is the syntax for a function header?
def function_name(parameter1, parameter2...): - it can take 0 parameters
How do you construct a dictionary?
dict_name = dict( ) - creates an empty dictionary dict_name = {key1: entry1, key2 = entry2....} - creates and initializes a dictionary
How do you add an element to a dictionary?
dict_name [key] = val
enumerate( )
enumerate(iterable, start_index) - iterates through an iterable object (typically list) at the starting index specified (if none is specified it starts at 0) by creating a counter and returns an enumerate object (a list of tuples each containing (index, item))
What is the syntax of reading from a data file?
handle = open(filename, 'r')
What is the syntax of writing to a data file?
handle = open(filename, 'w')
What terms are used to test identity?
is not (and) not
How can you count the number of arguments passed into the command line?
len(sys.argv)
len( )
len(val) - returns the length of the data passed in (for a list or dictionary it would return the number of items, for a string the number of characters etc.)
What is the syntax of reading the next line in a text file?
line = handle.readline( )
What is the syntax of reading to EOF?
line = handle.readlines( ) - returns an array of the lines
append( )
lis_name.append(item)
insert( )
lis_name.insert(index, element) - this shifts all the elements past the insertion point one index to the right
pop( )
lis_name.pop(index) - removes the element at the specified index (if no index is specified, the last element is returned and removed) - returns the element - if the given index isn't in the list, the last element is returned and removed
remove( )
lis_name.remove(value) - removes the element with the specified value - this shifts all the elements past the removed point one index to the left - if there isn't an element with that value in the list, a valueError is thrown - returns nothing
sort( )
lis_name.sort() - puts a list in sorted order - returns nothing
sorted( )
lis_name.sorted() - puts a list in sorted order - returns the list
What is the cost of a while loop?
log(base n)
How do you declare a tuple?
name = (item1, item2, item3.....)
How do you access a specific term (or terms) in a tuple?
name[index] name[starting_index : ending_index-1]
What is the syntax for a list comprehension?
new_list = [ expression for item in list if conditional ] ex: squares_of_evens = [x**2 for x in range(10) if x%2==0]
print( )
print(item1, item2) - prints most types of data - to join different pieces of data put a comma between them
How can you use the print statement without it creating a new line?
print(item1, item2......, end = " ") - end = " " appends a space in place of the new line
range( )
range(end_index+1) - With 1 parameter, it returns a range from 0 - parameter-1. range(start_index, end_index+1) - With 2 parameters it returns a range from first parameter - second parameter-1. range(start_index, end_index+1, step) - With 3 parameters it returns a range from first parameter - second parameter-1, with each of the values incremented by the third parameter step.
round( )
round(num) - takes a double and returns that number rounded into an int round(num, digits_from_point) - takes a double and returns that number rounded to the specified number of digits from the decimal point
join( )
str.join (sequence) - takes a str separator and a list or sequence of items - creates a string made of the sequence joined by the str
split( )
str.split (separator, max_split) - takes a string and splits it by its separator (if none is specified, white space is assumed) - max_split is how many strings we want it split into (if none is specified, then there is no max_split) - returns a list of strings
strip( )
str.strip(char) - removes the specified characters from the beginning and end of the string (if no characters are specified, white space is default) - rstrip(char) removes the char's on the right side of the list - lstrip(char) removes the char's on the left side of the list
Python code to read a specific word from the command line.
sys.argv[ i ] ** is the index of the words put into the terminal that you want to be read **i can be a range
What is the syntax for reading something from the command line?
sys.argv[argument#]
input( )
tells the program to read an input from the command line
If you read all of the lines from a text file how, can you remove the new lines?
yes, and you likely should! Use line.rstrip('/n/r')
yield keyword
yield is used like return, but remembers context because it is used in generator functions. It saves the current variables and location for the next time it's ran. yield is ONLY used in a for-loop - only works with iteration. It works by processing a single value in the loop, then when it hits the yield that value is returned. After that, it returns to the generator function's loop, processes the next value, when yield is hit the value is returned.... This allows the computer to save a lot of memory, because instead of returning a whole list at the end of processing a set of data, each piece of data can be returned one at a time, and tossed once it has been used.