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 Prelim 2 Study Guide

by: Eunice

CS 1110 Prelim 2 Study Guide CS 1110-002

Marketplace > Cornell University > ComputerScienence > CS 1110-002 > CS 1110 Prelim 2 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

Summarized Lecture Notes from 3/08-4/19 ThinkPython Notes
Intro to Computing using Python
Lee, Van Loan
Study Guide
Python, CS
50 ?




Popular in Intro to Computing using Python

Popular in ComputerScienence

This 10 page Study Guide was uploaded by Eunice on Wednesday April 20, 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 106 views. For similar materials see Intro to Computing using Python in ComputerScienence at Cornell University.

Similar to CS 1110-002 at Cornell

Popular in ComputerScienence


Reviews for CS 1110 Prelim 2 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: 04/20/16
CS 1110 Van Loan and Lee Spring 2016 Prelim 2 Summarized Lecture and ThinkPython Notes LECTURE NOTES:  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 THINK PYTHON NOTES:  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


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

Bentley McCaw University of Florida

"I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"

Allison Fischer University of Alabama

"I signed up to be an Elite Notetaker with 2 of my sorority sisters this semester. We just posted our notes weekly and were each making over $600 per month. I 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."


"Their 'Elite Notetakers' are making over $1,200/month in sales by creating high quality content that helps their classmates in a time of need."

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.