New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here

CS 1110, Final Exam Study Guide

by: Eunice

CS 1110, Final Exam Study Guide CS 1110-002

Marketplace > Cornell University > ComputerScienence > CS 1110-002 > CS 1110 Final Exam Study Guide

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Compiled and organized class and thinkpython notes
Intro to Computing using Python
Lee, Van Loan
Study Guide
CS, Python
50 ?




Popular in Intro to Computing using Python

Popular in ComputerScienence

This 25 page Study Guide was uploaded by Eunice on Saturday May 14, 2016. The Study Guide belongs to CS 1110-002 at Cornell University taught by Lee, Van Loan in Spring 2016. Since its upload, it has received 179 views. For similar materials see Intro to Computing using Python in ComputerScienence at Cornell University.

Similar to CS 1110-002 at Cornell


Reviews for CS 1110, Final Exam Study Guide


Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 05/14/16
CS 1110 Spring 2016 Van Loan and Lee Final Exam Study Guide (Class and Textbook Notes) CLASS NOTES  ASSIGNMENT STATES AND TYPES o Variables, Expression, Assignments  r and A are variables  define variable: a named memory location, like a box, holds a value  define = : assignment statement  variables are used in an expression o expression: evaluated and then stored under assigned variable o ex. 3.14*r**2  order is important  variable must be assigned a value before it is used and evaluated in an expressed  Assigning is different from “equal to”  Difference between math and python  Overwriting works  <variable name> = <expression>  Evaluate right item and store it in left item  Rules of naming variables  Name must be digits, uppercase letters, low care letters and _ (underscore)  Must begin with a letter or _  Expressions: use parentheses if there is ambiguity o Types  Python views numbers as a type  int: integer, integer arithmetic is exact  float: float arithmetic is usually inexact  literals  Int: ex. 12  Float: ex. 12.0  Str: ex. abc  Ints and floats o Integers v. decimals and python arithmetic  Integer division: A/B = Q and R (a remainder)  >>> r = x%y  r is printed as a remainder  Decimal division: A/B = Q (a decimal)  Clock arithmetic  Float can represent an integer even though it is not an integer type  Operations  Int: + - * / unary- ** %  Float: + - * / unary- **  Str: + o Strings  Strings: quoted characters  a single character is a string  define subscripting: characters in a string can be referenced through their indices (USE BRACKETS)  “t is a slice of s”  [x:y] will return characters with indexes x to and including y-1  Concatenation: string analog of addition (unlimited)  Data is provided often in strings and can be converted into floats/ints  WRITING A CODE o Comments begin with a “#”, guidelines o Docstrings: three quotation marks “”” o formatting options (not on exams)  %f  print ‘x=%A.Bf’ %x  where A and B are numbers and x is a float  it will print x with A number of spaces until x’s decimal point  and B number of digits after the decimal point will be displayed  %e  same as %f except converts to scientific notation  %d  print ‘x=%Ad’ %x  where A is a number and x is a integer  prints x with A number of spaces before x (including x’s digits)  %s  A = ‘string1’  print ‘%s ‘string2’ % A  concatenates ‘string1’ and ‘string 2’ o Import functions from modules  CONDITIONAL EXECUTION o If-Else o The punctuation and indentation are essential  If something isn’t indented, it’s a new statement/task that will be executed o You do not need variables, you can have expressions  If boolean expression:  Statements to execute if the expression is True  Else:  Statements to execute if the expression is False o When comparing two expressions to see if they have exactly the same value, use ==  = is an assignment  == is a comparison o < (less than), > (greater than), <= (less than or equal to), >= (greater than or equal to), == (is equal to), != (not equal to)  No spaces  Alphabetical/string comparison:  Comes first in alphabet: <  capital letter is < a lower case letter  0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghij klmnopqrstuvwxyz o If-Elif-Else construction  Elif: “else if”  An input is evaluated by each condition, until it reaches a comparison that verifies as True  Once a condition is evaluated as True, it stops and executes the statement o If boolean expression: o Statements to execute if this expression is True o Elif another Boolean expression: o Statements to execute if this expression is True o Else: o Statements to execute if all above expressions are False  len function: N = len(string)  LOGICAL OPERATORS x y x AND y true true true true false false false true false false false false x y x OR y true true true true false true false true true false false false  and: both statements must be true for the overall statement to be true o or: at least one of the statements must be true for the overall statement to be true o not:  not true = false  not false = true  FUNCTION o m = fct(x,y)  fct: name given to a function  x, y: both are arguments  arguments may be expressions o python functions: max, min, abs, round o when you use a function that doesn’t return a value, it’s void and when the function is assigned to a value, printing that value will print “none” o mechanics of how functions work  calling a function is different from defining a function  examining fruitful functions (those that return a value)  call frame o when a function is called in a program, the process steps through the function body  local variables are variables used within a defined function’s environment  MODULES o common: math, string, random, numpy, scipy, timeit, urllib2, PIL (image processing), datetime o dot notation  [module].[function]()  advantage being that if you are using multiple modules that each have functions with the same name, then dot notation clarifies o “from [module] import [function]”: dot notation no longer required/won’t work  “from math import *”: imports all o functions: math.floor, math.ceil, math.round  BUILDING FUNCTIONS o >>> def function(argument): [header] o >>> body statement o >>> more body statements o >>> return a variable o authors of a function must make available the how-to-use information through docstrings and comments o rule 1 and 2  module starts with authorship comments and an explanation  #module name  #author(s) names (and netid)  #last modified date  “””a doctstring: a module to ____””” o rule 3.  each function starts with a docstring “specification”  short summary that states what the function returns (post condition)  longer prose can be include which gives more useful info  precondition: conditions that the argument must satisfy if the function is to work o procedures  procedures are functions that do not return values, they “do something” o functions can call other functions  METHODS o 3 string methods  count: how many times does string t occur in string s  returns an int value  find: first occurrence of string t in string s  if a -1 is returned then nothing was found  otherwise, returns an int value  Boolean device: in o s1 in s2 o true: there is an instance o false: there is not  replace: in string s replace all string s1 with string s2  note: ‘’ is a null string  returns a copy of the string s with the appropriate replacements o note, a copy not a changed original  if s1 is not a substring of s then the returned string is just s  if there are overlapping substrings then the first found is replaced o xxx, replace xx with o = ox  NOTE: strings are immutable o their values cannot be changed o must slice and concatenate in order to apply replace function  check slides for example  evaluations  s.isalnum: all numbers or alphabet  s.isalpha: all alphabetical  s.isdigit:all numbers o dot notation instead of usual function-call syntax  n = count (y,x) [old]  n = x.count(y) [dot]  formally:  nameofstring.nameofmethod(argument1, argument2, …)  don’t use “or”; use commas to separate arguments  ITERATIONS o repeating a script using loops  for: for a certain object in another object, do a certain execution  “for x in y:”  LOOP BODY o iterating through a string vs is a range  letters/characters/string: “for c in s”: do thing in loop body  number/quantities: “for k in range(n)”: do thing in loop body o counting: a type of summation  “for k in range(there, here):  print k”  “for k in range(there, here, -1):  print k”  this counts backwards o the while-loop  open-ended iteration:  do a certain execution until a certain characteristic/event appears  “[code that comes before the loop]  while [a Boolean expression]: o [the loop body]  [code that comes after the loop]”  RANDOM SIMULATIONS o random in cs: means no discernable pattern o random Module  random.randint(a,b)  gives back a random integer between a and b, including a and b  renaming a function o “from random import randint as randi”  random.uniform(a,b)  random floats  random.normalvariate(mu,sigma) o short cut  x += 1  same as  x = x + 1 o repeatability of experiments  random.seed  reset the algorithmic process and fix the random generation process’s start point o having the same start point means that the same random sequence will be applied and the simulation can be repeated  note: if the variable that is assigned to another variable is updated, the other variable doesn’t update with it  WHILE LOOP o open ended iteration o redefining the sqrt  for loop will execute for the number of times you input  while loop will execute until it is at a specified error margin o up/down sequence example  given a number n  if even, replace by its half  if odd, replace by 3n+1  will you always end up at 1 o with open-ended, it is possible that the loop won’t end  infinite loop  insert a condition to end the loop after a certain number of steps given that it hasn’t ended on its own  LOGICAL MANEUVERS o loop body returns o logical maneuvers make codes more user friendly  corrects and points out errors  importerror o importing something that doesn’t exist  nameerror o a variable hasn’t been defined  typeerror o ex. dividing a string by an integer  zerodivisionerror o can’t divide by zero  assertions  ability to generate exceptions  “assert [Boolean expression],[string]” o if Boolean is not true then string is printed and an exception is made  type checking o use assert and the function isinstance o ex. isinstance(x,int)  if x houses an int then It’s true  check for strings and floats too  try-except construction  try: o code that may generate a particular exception  except [name of exception]: o code to execute if specified exception is found  break  a way to terminate a loop  LISTS o lists of numbers  previously seen in the triplet of numbers that is the rgb encoding of a color (length 3 list)  Terminology: “x=[1,2,3,4,5]”: x holds all those values  2 is an item, entry, element, value in the list x  n=len(x)=5  a=x[2] o a subscript is used to access an entry  can be sliced like a string (lists are similar to strings but with distinct differences) o string: sequence of characters o list: sequence of numbers (or lists of strings or lists of object (this will be learned later))  differences: list vs. strings  strings are immutable (unchangeable)  lists are mutable (changeable) o can replace a single value or a slice o List Methods  like count, find, replace (string methods)  dot notation  append, extend, insert, sort  x.append(#) o add the # value to the end of the list  t=[#,##]  x.extend(t) o append t o when applying the list method “extend”, you need to put a list in the argument/parameter otherwise an error is returned  i=some index number  a=#  x.insert(i,a) o insert value of a at index i  x.sort() o sort in a manner (like little to big) o default argument is False o to reverse: “x.sort(reverse=True)” o you can alphabetize a list of strings using sort o Void vs. Fruitful Methods  Void  void methods return the value of None (they don’t return anything)  list methods are void  ex. o “y=x.method() o print y o None”  Fruitful  pop o i = index number o m = x.pop(i) o removes the value from that string (which shortens the length)  count o m=x.count(#) o returns the number of # in the list  two available functions (built-in): len and sum o don’t use dot notation o sum is like concatenating/extending  if you multiply a list, it’s like extending it three times  Other considerations o sum() does not concatenate the strings in a list of strings o consider  “s= [‘cat’, ‘dog’, ‘mouse’]  c=s[2][1:3]”  same as  “s= [‘cat’, ‘dog’, ‘mouse’]  t=s[2]  c=t[1:3]”  they both assign ‘ou’ to c o Nested loops  a loop whose body contains another loop  lists of strings o slicing works to isolate strings in a list  [] is an empty list  be careful with syntax, [ indicates a list  text file o lists store tons of data in files o to open a file  name of file is passed as a string  file must be in the same directory as the code that reads it  open(‘nameoffile.txt’,’r’) as F  F is the name  r means read o s as a name of a string  s.rstrip()  removes a line  split method o s.split() o when applied, it will create a list out of string s and the list can be assigned to a variable o the blank in the argument is the delimiter and tells the method where to split the string  readme file o says how data is arranged so that user will know how to use a .csv file  steps to use a file for computation o download a file o name the file and put it in a directory with the code o do the computation  comparing lists o == to compare if two lists have same length and data o can’t use <= or >= etc  aliasing o two variables refer to the same object (the same list)  an object is aliased when it has more than one name  DICTIONARIES o an item has a key and a value  values are assigned to keys o set up  use a colon to separate a key from its value  separate items with a comma  enclose the whole thing with {} o dictname.keys()  list of keys o dictname.values()  list of the values o delete a dictionary item  del dictname[‘keyname’] o checking if a dict has a particular key  Boolean  ‘keyname’ in dictname o extracting a value  keys are like subscripts  variablename = dictname[‘keyname’] o adding an item to a dictionary  dictname[‘nameofkeynotindict’]=value  items in a dictionary are randomly ordered  if the named key already exists then the value of that key is changed o list vs. dictionary  dict: keys mapped to values  list: integers (indices) mapped to values o copying dictionaries  copy = dict(originaldict) o use loops to go through dictionaries o keys must be strings or numbers, values can be anything  all values in a dictionary do not have to have the same type  OBJECTS AND CLASSES o classes: packages data into units  defining the point class  build the point given info (using the constructor method) o builds a point object  to define a point, you need to define a new type  define the attributes of the class  __init__ (double underscore function) o initializing, method to write a constructor o “def __init__(self,x,y):” o always start with self  the first argument when writing a constructor o under the __init__, assign incoming values to self’s attributes o constructor builds an object and creates the box  always has the same name as the class  invoking the constructor=building the object and the reference to it  dot notation: substitution mechanism  get values of attributes  to the left of the dot: a point object o affiliated with self o the argument (whatever is in the parenthesis) is affiliated with other o object  holds and organizes data  attributes are variables that live in the object  use dot notation to access and manipulate attributes  pretty printing (define a __str__ method in the class)  note: whenever you have a method that is defined in a class in the same module, the first argument is always self  method thinking  apply the method to a pair of certain objects  List of Objects o list of objects vs. integers  a single integer stored  a reference to some object (ex. a point) is stored  u = L[1].x  list L, box 1, x value from object: assigned to u o importing modules that contain classes (defined within the module) means that you can use the class o assignment statement is like an address o can’t change all of (for example) x attributes at once, use a for loop instead  references are different from assignments o with objects, two objects set = to each other is a reference, meaning that the two things will refer to the same object and changing the object will change both things o use the function ‘copy’ for creating separate assignment  sorting o sorting by different characteristics  write a ‘getter’ function that extracts the ‘key’ attribute  getKEY() returns object.keyattribute  complicated classes o class: packaging of data and methods that work on that data o Redefining computations (+ or -) o example: SimpleDate class  create methods to calculate in leap years and lengths of months  redefine + to add days instead of attempting concatenation by creating an __add__ method  similarly, for – and subtraction, __sub__  for ==, __eq__  for *, similarly __mul__ o Boolean valued function:  isinstance(object, class)  is the object an instance of the class  remember than if the object looks like a (for example) a fraction, it’s actually an integer, or maybe a float  copying objects: o B = copy(A)  copying an object doesn’t reproduce a copy of its references o B = deepcopy(A)  complete copy including its references  RECURSION o functions that call themselves o patterns that are defined by the terms of itself o consider levels  at each level, execute a certain procedure respective to the level  (with triangles and fractals, consider each inner triangle a new level) o factorial example  if an execution can be reapplied with n-1 (n being the major variable at hand), recursion could be applied  a base case: the condition or point at which the recursion stops  SEARCHING A LIST (example being searching a list of integers) o Linear Search: data is unordered  method: iterate and go down a line  no match case: return -1  while implementation vs. for implementation  while: while there’s no match  for: check for each whether it’s a match  if there are multiple cases, without further specification, it will just return the first match case o Binary search: assume/specify that the list to be searched is sorted from little to big  when the length of the list increased by a certain constant, the time it takes to search the list does not equally scale  method: check half, discard the half that does not include the match  ex. if you have a name to find in an alphabetized list, check half and if the name falls within the letters of that half  math: log 2n)  code: find midpoint (Mid), discard either preceding or following half (halving the size of the search space) o L: left endpoint; R: right endpoint; Mid: (L+R)/2  at the end of the loop, compare the end points (which are the two remaining values to check for matches) o a recursion o Benchmarking (check how long a code takes)  the longer the list, the binary method is fastest  the linear method, for loop is second; linear method, while loop is the slowest  while loop test condition is complicated  SORTING METHODS o selection sort  sort through a sequence of swaps  ex. select a value from the left and swap with lower values on the right (list of integers)  use a helper function  remember, sort functions are void functions  depends on n^2 (n being length) o merging two sorted lists into a single sorted list  make smaller and smaller decks, merge them and sort the decks  depends on n*log(n) (n being length)  ex. compare each item in the two lists and append the smaller and move on  mergesort():  divide and conquer technique (previous example, binary search)  split lists (again and again) to sort and then merge o recursion! (a recursive code calls itself)  OBJECT-ORIENTED PROGRAMMING (OOP) o see ThinkPython chapter 18 o examples used involve playing cards  decks vs. hands  can do certain things with both but also some methods won’t be shared o def __str__(self)  a special method that “pretty prints” o Inheritance  in defining a class instead of having “class Child(object)”  if you have “class Child(Parent)” the new class (Child) inherits, or is able to use all the methods from the other class (Parent)  any method from Parent that is redefined in Child is overridden by the new definition  in using Child class, you can use methods defined in the Parent class and apply it (it has been inherited)  PROBABILITY o of a full house in a hand  5 card hand: two of one rank, three of another  DATA VISUALIZATION o how to define a useful class for manipulating (for ex.) sunrise/sunset data o how to graphically display facts about that data using numpy and pyplot  pyplot allows you to easily graph  numpy arrays  within numpy, there’s an array type o you can add, subtract, multiply, divide arrays  requires same length  1-dimensional array basics o example of 3 element 1d array: o from numpy import * o x = array([1,2,3])  built in linspace function o can’t be used on a python list, can be used in an numpy array  2d arrays in python o first index, second index  in a list of lists, the first indicates the list item and the second indicates the item in the list item  in a 2d array, it’s like row and column o A = array ((3,3))  python sets aside a 3 by 3 array space  TWO DIMENSIONAL ARRAYS o arrays are objects o rows and columns (via module numpy) o application: a firm with m factories with n factory production  factory (row) k has value (column) j  j could be the amount of product (inventory) or cost  question: how much does it cost for each factory to produce some amount  loop through the array (through row, and through column) to compare costs and production per factory  PAGERANK o there are islands and people on each all transition to another island at once (conceptually) o think about the probability  half will stay on each island, and the other half will split among the other islands o the distribution after a transition  the numbers will reach a steady state (or a stationary array) after a significant number of iterations THINKPYTHON NOTES o 1.1: high level vs. low level language o 1.2  Program: sequence of instructions for the performance of a computation  Input: get data from keyboard, file or other device  Output: display data or send data to file or device  Math: perform basic math operations  Conditional execution: check for certain conditions and execute appropriate code  Repetition: perform some action repeatedly, usually with some variation o 1.3  Bugs: programming errors  Syntax: structure of program and rules of structure, an error will prevent the program from running because it can’t be parsed  Semantic error: program will run successfully but action will be incorrect  Runtime errors: will appear after program has started to run o Called exceptions: these errors are rare  Debugging: finding errors o 1.4  Syntax rules  Tokens: basic elements of language (ex. words, numbers, chemical elements)  Structure o Parsing: process of understanding structure of sentence  Natural vs. formal  Ambiguity: formal language statement has exactly one meaning regardless of context  Redundancy: formal languages are more concise, less redundant because there’s no ambiguity to clarify  Literalness: natural languages use idioms and metaphors o 1.5: Print statement o 1.7  Portability: a property of a program that can run on more than one kind of computer  Algorithm: process for solving a category of problems o 2.1  Value: what a program works with  Types o String (str): a string of letters enclosed in single quotation marks o Integer (int) o Floating-point (float): numbers with a decimal point o 2.2  Variable: a name that refers to a value  Assignment statement: creates new variable and gives them values o 2.3  A variable can include numbers, letters and _ but must begin with a letter  If there is a space in a variable name, python assumes two operands and no operator  PYTHON 2 KEYWORDS  and as assert break class continue def del elif else except exec finally from global if import in is lambda not or pass print raise return try while with yield o 2.4  Operators: special symbols that represent computations  + - * / **  Floor division: both of operands are integers, result is an integer (rounds down)  Operands: value the operator is applied to o 2.5  Expression: combination of values, variables, and operators  Statement: unit of code that the python interpreter can execute (ex. print and assignment) o 2.6: Script vs interactive mode o 2.7: rule of precedence: (math) PEMDAS o 2.8: Concatenation: joining strings by linking end-to-end o 2.9: Comments: notes added to programs to explain in natural language the function of the program (start with “#”) o 2.11: State diagram: graphical representation of a variable set and the values referred to o 8.1  String: sequence of characters  Each character is assigned a number starting with 0  Index: expression in brackets that uses character number o Index must be an integer o 8.2: len: built-in function that returns the number of characters in a string (length) o 8.4  Slice: segment of string  Empty string: result of using a slice [n:m] where n=m or n>m  5.1 st  Modulus operator: works on integers, yields remainder from 1 operand divided by a 2nd o Symbol: %  extract the right-most digit(s) from a number o x%10 (last digit) o x%100 (last two digits)  5.2  Boolean expression: expression either true or false (==) o True and False are type bool; not strings  == is a relational operator o Others: x! # x is not equal to y =y x> # x is greater than y y x< # x is less than y y x> # x is greater than or =y equal to y x< # x is less than or equal =y to y  5.3  Three logical operators: and, or, not  Technically, operands of logical operators should be Boolean expressions  5.4  Conditional statements: check conditions o Boolean expression after if: the condition  If true, then indented statement is executed; if not, nothing happens o Function definition structure: a header followed by an indented body (compound statements) o If you need to have a body with no statements as a place keeper: use pass statement  5.5: if-else  A form of the if statement: alternative execution o Two possibilities and condition determines which one is executed o Since the condition is either true or false, only one of the alternatives will be executed  Alternatives: branches  5.6: elif  More than two branches needed: use a chained conditional o Elif: “else if”  5.7: Nested conditionals  5.11  Raw_input: input from keyboard o Program stops and waits for user to type something; once the user presses return/enter, the program resumes o Raw_input will return what the user typed as a string  3.1  Function: named sequence of statements that performs a computation  Functional call: …calling said function  argument of the function: expression in the parentheses  a function “takes” an argument and “returns” a result (the return value)  3.2: functions int(), float(), str()  3.3: modules o contains predefined functions and variations o to access these use dot notation  module.function()  3.5  function definition: specifies the name of a new fct and the sequence to execute when fct is called o def functionname(): 1 o [detail the sequence] 2  1. header 2. body  empty parentheses: no argument  end function by entering an empty line  the value of functionname() is a function object, type is function  3.7  flow of execution: order in which statements are executed o begins at the first statement, one at a time, from top to bottom o follow where the function is called (Detour) which executes the body of the function and then the program continues on  3.8: parameters: inside the function () arguments are assigned variables  3.9: locality: variable inside function and parameters works only in the function  3.10  stack diagram: shows value of each variable and the function each variable belongs to  function is represented by a frame o a box, function name next to it, parameters and variables inside it  the list of functions in an error is the traceback: what file, what line and what functions in which the error exists  3.11  fruitful functions: fct that yields results (math functions)  void functions: fcts that perform an action but don’t return a value (ex. printtwice()) o 6.1  fruitful function  “return” statements includes an expression o return from the defined function and use the expression given as a return value  in conditional: o the code that appears after a return, flow of execution never reaches it: dead code o if all the conditionals fail to apply then “None” is printed o 6.3: composition: calling one function from within another o 8.3  traversal: select a character, do something, continue  while loop (7.3)  while a certain condition holds true, repeat script  can be used to create a find/search function (8.6)  for loop  for a certain condition, do an action  can be used to create a counter (8.7) o 8.8  method: takes arguments and returns values but with different syntax  function(argument) vs. argument.method(parameter)  method call: invocation  optional arguments  method(argument[, optionalargument[, optionalargument2]]) o 8.9  “in”: Boolean operator  takes two strings and returns True if the first is a substring of the second o 4.2: repetition o 13.2: random module: pseudorandom o 6.4: Boolean in function o 7.1: multiple assignments  assigning a new value to a variable o 7.2: changing the value of a variable  initialize  update with  +1: increment  -1: decrement o 7.5: sqrt o 7.6: algorithms o 7.4: break: stopping a loop when this happens, as opposed to keep going until that happens  7 o .1: multiple assignments (assigning new values to variables) o .2: updating assignments  +1: increment  -1: decrement o .3: while loop  loops while a condition holds true or false (Boolean) o 7.5: sqrt o 7.6: algorithms o 7.4: break  ‘stop a loop when at the occurrence of a given characteristic’  as opposed to ‘keep going until the occurrence of a given characteristic’  10 o .1  list: sequence of values  values can be any type (called elements, items)  a list within another: nested  empty nest: [] o .2  lists are mutable (unlike strings)  indices:  any integer expression can be used  if you try to read/write an element that doesn’t exist: IndexError  if index is negative, it counts backward from end of list o .3  traverse a list using a for loop  “for x in []:”  “for i in range(len(list)):” o .4  + concatenates by adding lists end to end  * concatenates by adding the given number of times o .5  slice operator acts the same way as it does for strings o .6  append: adds a new element to end of list  extend: takes a list as an argument and appends all of its elements  argument is unmodified  sort: arranges elements from low to high  all methods are void and return None o .7  += short way to update a variable  augmented assignment statement  the variable to which this is assigned (if in a loop) is called an accumulator  sum(x) will combine the sequence of elements of x into a single value  sum() is a reduce operator  if in a loop, each element is placed through a function, the loop is a map  functions that removes some elements but not others are a filter o .8  t.pop(index): removes and returns element in index  if no index is provides, it deletes and returns the last element  del t[index]: deletes without returning a value  t.remove(‘element’): removes element without usage of index  no return value o .9  t=list(s): breaks string s into a list t of characters  t=s.split(): splits string s (sentence) into list t of words  delimiter: specifies which characters to use as word boundaries when splitting  delimiter = ‘assign a character’  t=s.split(delimiter)  join: joins list t of elements into a string with divisions set by delimiter  delimiter = ‘ ‘  delimiter.join(t) o .10  strings can be identical  lists are equivalent, not identical  they are not the same object  object has a value  so two different objects can have the same value o .11  reference: association of a variable with an object  an object is aliased: an object has more than one reference and more than one name  as in if two names refer to the same list  if objects are mutable and aliased, changing the object via one name will have changed it with the other name  11 o dictionary: a more general list  indices can be any time  a mapping between a set of indices (called keys) and a set of values  key-value pair, an item  dict() creates a dictionary with no items  {} empty dictionary  dictname[‘string’]=[‘str2’] mapped the two strings together o {‘string’:’str2’}  order of items in a dictionary is unpredictable  elements aren’t indexed with integer indices, use keys  if the key isn’t in the dictionary, you get a KeyError  len: returns the number of key-value pairs  in operator returns True or False  whether something appears as a key in the dictionary (not a value)  to use in on values: values method o x = dictname.values() o ‘string’ in x o True #or False o .1  implementation: computation performance  histogram: set of counters (or frequencies)  get method  dictname.get(‘key’, default value)  returns the corresponding value if key is in dict; otherwise returns default value o .2: for loops can be used on a dictionary o .3  lookup; dictionary d and key k  x=d[k] o .4  singleton: a list that contains a single element  hash: a function that takes a value of any kind and returns an integer  hashable keys: immutable  hash values: integers that store and look up key-value pairs in a dictionary  13.3: example of using histogram  5 o .8  recursion: a function calls itself, function is recursive o .9: stack diagrams for recursions o .10  infinite recursion: process never reaches a base case (the program never terminates)  6 o .5: recursion example for math o .6  “leap of faith”: assuming a function works  this is required when calling your own function o .7: another example  9 o .3  problem recognition: if problem has already been solved, apply the previously-developed solution o .4  use recursion as an alternative to tricky loops  15 o .1  class: a user-defined type  objects are built in types  class definition  “class Name(object):”  Name is a class object o a factory for creating objects  to create a Name, call it like a function o the return value is a reference to a Name-type object o instantiation: creating a new object o object: an instance of the class o .2  use dot notation to assign values to an instance  attributes: elements of an object o .3  an embedded object: an object that is an attribute of another object o .4: functions can return instances o .5  the state of an object can be changed by making an assignment to one of its attributes (objects are mutable) o .6  avoid confusions caused by aliasing: copy an object  copy module: contains function copy (duplicates any object)  copied objects are not the same object (They are separate)  copied objects are equivalent but have different object identities  shallow copy: copies object and its references but not embedded objects  deep copy: copies object, the objects it refers to, the objects they refer to, etc  17 o .1  object-oriented programming language: has features that support object-oriented programming  method: a function that is associated with a particular class o .2  printing an object  class.nameofmethod(parameter)  in which the method is print  parameter.method()  the parameter is the subject, the object the method is invoked on o .3  a pure function is not a modifier o .4: example o .5  init method (initialization)  invoked when an object is instantiated  “__init__” o .6  “__str__”  returns a string representation of an object o .7  operator overloading: changing the behavior of an operator so that it works with user-defined types o .8  type-based dispatch  if the parameter at hand is a certain type object, then it invokes a specified function o .9  polymorphic functions: can work with several types of functions  18 o .1  encode: define a mapping between two entities o .2  class attributes  instance attributes: variables that are associated with a particular instance o .3: compare using > < = o .4: example o .5: applying list method o .6  veneer: method that uses another function without doing much real work o .7  inheritance: ability to define a new class that is a modified version of an existing class  parent: existing class from which new class inherits methods  child: new class o .8  class diagrams: a graphical representation of relationships  relationship types o HAS-A: objects in one class might contain references to objects in the other class o IS-A: one class might inherit from another o one class might depend on the another in the sense that changes in one class would require changes in the other  multiplicity: indicated by a * near an arrow, indicates how many classes are in another class


Buy Material

Are you sure you want to buy this material for

50 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Jim McGreen Ohio University

"Knowing I can count on the Elite Notetaker in my class allows me to focus on what the professor is saying instead of just scribbling notes the whole time and falling behind."

Anthony Lee UC Santa Barbara

"I bought an awesome study guide, which helped me get an A in my Math 34B class this quarter!"

Jim McGreen Ohio University

"Knowing I can count on the Elite Notetaker in my class allows me to focus on what the professor is saying instead of just scribbling notes the whole time and falling behind."

Parker Thompson 500 Startups

"It's a great way for students to improve their educational experience and it seemed like a product that everybody wants, so all the people participating are winning."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.