Who could be Myopic? Use Logistic Regression to know.

Here I use Logistic regression to classify myopic and non-myopic students.

Data source: myopia dataset

Importing Libraries

In [1]:
import numpy as np
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
from patsy import dmatrices
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import train_test_split
from sklearn import metrics
from sklearn.cross_validation import cross_val_score

Loading Dataset

In [2]:
myopia = pd.read_excel("myopia.xls")
In [3]:
myopia['MYOPIC'].value_counts()
Out[3]:
0    537
1     81
dtype: int64
This dataset is an imbalanced dataset. Only 15%(approx.) data represents cases for myopic students.
In [4]:
#creating dataframe with intercept column using dmatrices from patsy
y,x = dmatrices('MYOPIC ~ AGE + GENDER + READHR + COMPHR + STUDYHR + TVHR + SPORTHR + DIOPTERHR + MOMMY + DADMY', myopia, return_type="dataframe")
In [5]:
# creating a logistic regression model, and fitting with x and y
logit = LogisticRegression()
logit = logit.fit(x, y)

# checking accuracy
logit.score(x, y)
Out[5]:
0.8689320388349514

Model Training

In [6]:
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=0)

#creating logistic regression, fitting training data set : x_train, y_train
logit2 = LogisticRegression()
logit2.fit(x_train, y_train)
Out[6]:
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
          intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=1,
          penalty='l2', random_state=None, solver='liblinear', tol=0.0001,
          verbose=0, warm_start=False)
In [7]:
# predicting using test data set
predicted = logit2.predict(x_test)

# getting probabilities
probs = logit2.predict_proba(x_test)
predicted
Out[7]:
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  0.])

Checking Accuracy

In [8]:
# generate evaluation metrics
print metrics.accuracy_score(y_test, predicted)
print metrics.confusion_matrix(y_test,predicted)
print metrics.precision_score(y_test, predicted) # what proportion of students identified as myopic were actually myopic.
print metrics.recall_score(y_test, predicted) # what proportion of students that were myopic , were identified as myopic. 
 Out[8]:
0.854838709677
[[159   1]
 [ 26   0]]
0.0
0.0

The accuracy score is about 86%. According to the confusion matrix, the model predicts 159/160 cases for non-myopic students correctly which is the reason for high accuracy. However, the model is unable to predict any case of myopic students correctly. Clearly, this is a case of class imbalance as proportion of non-myopic cases is much higher than myopic cases. Class imbalance leads to ‘accuracy paradox‘ i.e. models with a given level of accuracy may have better predictive power than models with higher level of accuracy. Ratio of correct predictions to total number of cases may seem to be an important metric for predictive models, but in cases of class imbalance it may be useless.

Class imbalance is also the reason for low precision score and low recall score. Hence, while measuring the performance of a model we must look at different types of performance measures.

Cross Validation

In [9]:
#converting y into one dimensional array
y = np.ravel(y)
In [10]:
# evaluating using 10-fold cross-validation
scores = cross_val_score(LogisticRegression(), x, y, scoring='accuracy', cv=10)
print scores
print scores.mean()
 Out[10]:
[ 0.85714286  0.87096774  0.87096774  0.87096774  0.87096774  0.87096774
  0.87096774  0.86885246  0.86885246  0.86885246]
0.86895066858

Cross validation score shows 86.9% accuracy. The cross validation score is high as it is aggregated accuracy score with different combinations of training and test datasets.

In further blog posts we will use other modelling techniques to solve this problem of classification.

 

 

Advertisements

Review Tuples !

my_list = [2,3]
my_tuple = (4,5)
other_tuple = 6,7
my_list[1] = 10
my_list
[2, 10]
my_tuple[1] = 11 #see that tuple cannot be modified
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-ce8c7e54784a> in <module>()
----> 1 my_tuple[1] = 11

TypeError: 'tuple' object does not support item assignment
def sum_product(x, y):
    return (x + y),(x * y)
sp = sum_product(11,12)
sp
(23, 132)
s, p = sum_product(11,12)
s
23
p
132
x,y = 1,2 # multiple assignment is possible both in lists and tuples
x,y = 3,4

Studying Data Science from Scratch by Joel Grus.

Creating a Dictionary in Python

Dictionary is similar to a list. It contains key:value pairs. Here, we will learn about creating and modifying dictionaries.
Creating Dictionary
dictionary_name = {key:value, key:value,…..}

We create a dictionary with colors of jams as keys and fruit names as values.

jam = {'red':'strawberry', 'yellow': 'mango', 'orange':'orange'}
print jam['orange']
print jam['red']

orange
strawberry

Insertion – Here, we add a new key/value pair to the existing dictionary.

jam['blue'] = 'blueberry'

{‘blue’: ‘blueberry’, ‘red’: ‘strawberry’, ‘yellow’: ‘mango’, ‘orange’: ‘orange’}

Deletion – Here, we delete a key/value pair

del jam['orange']
jam

{‘blue’: ‘blueberry’, ‘red’: ‘strawberry’, ‘yellow’: ‘mango’}

Replacing values – We replace value for key ‘red’ from strawberry to cherry.

jam ['red'] = 'cherry'
jam

{‘blue’: ‘blueberry’, ‘red’: ‘cherry’, ‘yellow’: ‘mango’}

Nesting : We nest a new dictionary within an existing dictionary.

 jam['red'] = {'light' : 'cherry', 'dark' : 'strawberry' }

{‘blue’: ‘blueberry’, ‘red’: {‘dark’: ‘strawberry’, ‘light’: ‘cherry’}, ‘yellow’: ‘mango’}
We set a list as a value for key ‘blue’.

jam['blue'] = ['blueberry','plum']
jam

{‘blue’: [‘blueberry’, ‘plum’], ‘red’: {‘dark’: ‘strawberry’, ‘light’: ‘cherry’}, ‘yellow’: ‘mango’}

Append to a list

jam['blue'].append('jamun')  
print jam['blue']

[‘blueberry’, ‘plum’, ‘jamun’]

Indexing the nested dictionary

print jam['red']['dark']

strawberry

jam

{‘blue’: [‘blueberry’, ‘plum’, ‘jamun’], ‘red’: {‘dark’: ‘strawberry’, ‘light’: ‘cherry’}, ‘yellow’: ‘mango’}

Using Lists as Stacks and Queues in Python

Before reading about stacks and queues, you may wish to read about – How to create and modify lists in python.

What is a Stack?

A stack is a data structure that could be represented by a pile where insertion and deletion of items takes place only at a single end called top of the stack. The basic way to access data in stack is by Last In First Out(LIFO) method. To understand the structure of stack, imagine a pile of books (call it stack). One can use only the top end of the pile to add or remove a book to the stack. Also, index numbers are not assigned to elements in a stack, hence, the elements in the middle of a stack cannot be accessed directly.

Using List as a Stack

We create a list called stack.

stack = ["geography","statistics","biology","linear algebra"]
stack

[‘geography’, ‘statistics’, ‘biology’, ‘linear algebra’]

Insertion to a Stack
Now we use append() to add new elements to the stack. Here the last element being added is “economics”.

stack.append("physics")
stack.append("history")
stack.append("economics")
stack

[‘geography’,’statistics’, ‘biology’, ‘linear algebra’, ‘physics’, ‘history’, ‘economics’]

Deletion from a Stack
Now we remove the element last added by using pop() without an index number. Remember elements in a stack do not have index numbers.

stack.pop()

‘economics’

stack.pop()

‘history’

We see that our stack follows the principle of LIFO (as mentioned above). Lets check our stack after removing the last two elements.

stack

[‘geography’, ‘statistics’, ‘biology’, ‘linear algebra’, ‘physics’]

What is a Queue?

A queue is a data structure that could be represented by a queue(sequence of people) at a ticket counter. It has a front and a back. At a ticket counter queue, new persons join at the back and the first person buys the tickets first and leaves first. Similarly, the data structure queue follows the principle of First In First Out(FIFO). Addition of elements is called “Enqueue” and Removal of elements is called “Dequeue”. Enqueue takes place at the back, while Dequeue takes place at the front.

 

Using List as a Queue
To use list as a queue, we use collections.deque. It was designed to have faster appends and pops from both ends of a list.
from collections import deque

Now, we create a queue by using deque()on a list.

queue = deque(["rohan", "sameer", "adil", "saksham"])
queue

deque([‘rohan’, ‘sameer’, ‘adil’, ‘saksham’])

Insertion to a Queue
We use append() to add an element at the end of the queue.

queue.append("priya")
queue.append("aashi")
queue

deque([‘rohan’, ‘sameer’, ‘adil’, ‘saksham’, ‘priya’, ‘aashi’])

Deletion from a Queue
We use popleft() to remove the element at the beginning of the queue.

queue.popleft()

‘rohan’

queue.popleft()

‘sameer’

We see that our queue follows the principle of FIFO (as mentioned above). Lets check our queue after removing the first two elements.

queue

deque([‘adil’, ‘saksham’, ‘priya’, ‘aashi’])

Creating and Modifying Lists in Python

List stores pieces of information in a sequence within a variable.

Creating – We create a list and store it under a variable called my_list. In python, to create a list, we need to mention the items within square brackets “[]”. Here we create a list of string items, hence each item is written within double quotes.

my_list = ["frog", "dino", "lion", "rabbit"]
my_list

[‘frog’, ‘dino’, ‘lion’, ‘rabbit’]

Appending – We use append to add an item at the end of the list. Here, we append “tiger” to the list.

my_list.append("tiger")
my_list

[‘frog’, ‘dino’, ‘lion’, ‘rabbit’, ‘tiger’]

Creating – Now we create another list called new_list.

new_list = ["red","blue","orange"]

Extending – We use extend to add one list to another list. Here we extend new_list by my_list.

new_list.extend(my_list) 
new_list

[‘red’, ‘blue’, ‘orange’, ‘frog’, ‘dino’, ‘lion’, ‘rabbit’, ‘tiger’]

Insertion – We use insert to add a new item at a specified position in a list. Here, we insert a new item “snake” at position 2 of my_list. Index number in python lists starts from 0. Here, “frog” is at 0 index number, “dino” at 1 index number and so on.

my_list.insert(2,"snake")
my_list

[‘frog’, ‘dino’, ‘snake’, ‘lion’, ‘rabbit’, ‘tiger’]

Removing by item name – Remove looks for the first mention of the specified item name in the list and deletes it. Here, remove looks for first mention of “dino” in my_list and removes it.

my_list.remove("dino")
my_list

[‘frog’, ‘snake’, ‘lion’, ‘rabbit’, ‘tiger’]

Removing by index number – Pop removes the item at the specified index number. Here, item mentioned at the index number 3 i.e. “rabbit” is removed.

my_list.pop(3)
my_list

[‘frog’, ‘snake’, ‘lion’, ‘tiger’]

Finding index number – Index finds the index number of the first mention of specified item. Here, we find index number for item “lion” in my_list.

my_list.index("lion")

2

Counting item mentions – Count gives the number of mentions of the specified item in the list. Here, we get the count of item “snake” in my_list.

my_list.count("snake")

1

Sorting(Ascending) – Sort helps to sort list in ascending or descending order. By default it sorts the list in ascending order. Here, we sort my_list in ascending order.

my_list.sort()
my_list

[‘frog’, ‘lion’, ‘snake’, ‘tiger’]

Sorting(Descending) – To sort the list in descending order, we set reverse option as TRUE. Here, we sort my_list in descending order.

my_list.sort(reverse=True)
my_list

[‘tiger’, ‘snake’, ‘lion’, ‘frog’]

Reversing – We use reverse to reverse the items of a list such that the item at position 0 takes position len(list), item at position 1 takes position len(list-1) and so on. Here, we reverse new_list

new_list.reverse()
new_list

[‘tiger’, ‘rabbit’, ‘lion’, ‘dino’, ‘frog’, ‘orange’, ‘blue’, ‘red’]

Next, you may like to read about How to use lists as Stacks and Queues.

File Input/Output – Python

This is the last part of the Python exercises on codecademy. It trains one on how to read information from a file on your computer, and/or write that information to another file. This process is called file I/O (the “I/O” stands for “input/output”).

I. Introduction to file I/O

i. See It to Believe It 1/9

>Simply save and submit!

ii. The open() Function 2/9

my_file = open(“output.txt”, “r+”)

iii. Writing 3/9

my_list = [i**2 for i in range(1,11)]

my_file = open(“output.txt”, “r+”)

# Add your code below!
for each in my_list:
return my_file.write(each) \n

my_file.close()

iv. Reading 4/9

my_file = open(“output.txt”,”r”)
print my_file.read()
my_file.close()

II The Devil’s in the Details

i. Reading Between the Lines 5/9

my_file = open(“text.txt”, “r”)
print my_file.readline()
print my_file.readline()
print my_file.readline()

my_file.close()

ii. PSA: Buffering Data 6/9

# Open the file for reading
read_file = open(“text.txt”, “r”)

# Use a second file handler to open the file for writing
write_file = open(“text.txt”, “w”)
# Write to the file
write_file.write(“Not closing files is VERY BAD.”)

write_file.close()

# Try to read from the file
print read_file.read()
read_file.close()

iii. The ‘with’ and ‘as’ Keywords 7/9

with open(“text.txt”, “w”) as textfile:
textfile.write(“Success!”)

iv. The ‘with’ and ‘as’ Keywords

Save and Submit

v. Try it Yourself

with open(“text.txt”,”w”) as my_file:
my_file.write(“You are and apple”)

vi. Case Closed?

with open(“text.txt”,”w”) as my_file:
my_file.write(“You are and apple”)
if my_file.closed == False:
my_file.close()
print my_file.closed


 

Congratulations!! You’re done.

 

Classes in Python

Classes

I A Review of Classes

i. Class basics 1/11

class Car(object):
   pass

ii. Create an instance of a class 2/11

class Car(object):
  def __init__(self):
    pass
my_car = Car()

iii. Class member variables 3/11

class Car(object):
  condition = "new"
my_car = Car()

iv. Calling class member variables 4/11

class Car(object):
  condition = "new"
my_car = Car()
print my_car.condition

v. Initializing a class 5/11

class Car(object):
    condition = "new"
    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg = mpg        
my_car = Car("DeLorean","silver", 88)
print my_car.condition

vi. Referring to member variables 6/11

class Car(object):
    condition = "new"
    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg = mpg        
my_car = Car("DeLorean","silver", 88)
print my_car.condition
print my_car.model
print my_car.color
print my_car.mpg

II Using Classes

i. Creating class methods

class Car(object):
    condition = "new"
    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg
    def display_car(self):
        return "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))
my_car = Car("DeLorean", "silver", 88)
print my_car.display_car()

ii. Modifying member variables

class Car(object):
    condition = "new"
    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg
    def display_car(self):
        return "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))
    def drive_car(self):
        self.condition = "used"
my_car = Car("DeLorean", "silver", 88)
print my_car.condition
my_car.drive_car()
print my_car.condition

iii. Inheritance

class Car(object):
    condition = "new"
    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg
    
    def display_car(self):
        return "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))
    
    def drive_car(self):
        self.condition = "used"
my_car = Car("DeLorean", "silver", 88)

print my_car.condition
my_car.drive_car()
print my_car.condition

class ElectricCar(Car):
    def __init__(self, model, color, mpg, battery_type):
        self.battery_type = battery_type
        return super(ElectricCar, self).__init__(model, color, mpg)
        
my_car = ElectricCar("Prada", "Blue", 90, "molten salt")

iv. Overriding methods

class Car(object):
    condition = "new"
    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg
    
    def display_car(self):
        return "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))
    
    def drive_car(self):
        self.condition = "used"

my_car = Car("DeLorean", "silver", 88)

print my_car.condition
my_car.drive_car()
print my_car.condition

class ElectricCar(Car):
    def __init__(self, model, color, mpg, battery_type):
        self.battery_type = battery_type
        return super(ElectricCar, self).__init__(model, color, mpg)
    def drive_car(self):
        self.condition = "like new"
        
my_car = ElectricCar("Prada", "Blue", 90, "molten salt")
print my_car.condition
my_car.drive_car()

v. Building useful classes

lass Point3D(object):
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z
    
    def __repr__(self):
        return "(%d, %d, %d)" % (self.x, self.y, self.z)
        
my_point = Point3D(1,2,3)
print my_point

Introduction to Classes

I Class Basics

i. Why Use Classes? 1/18

class Fruit(object):
    """A class that makes various tasty fruits."""
    def __init__(self, name, color, flavor, poisonous):
        self.name = name
        self.color = color
        self.flavor = flavor
        self.poisonous = poisonous

    def description(self):
        print "I'm a %s %s and I taste %s." % (self.color, self.name, self.flavor)

    def is_edible(self):
        if not self.poisonous:
            print "Yep! I'm edible."
        else:
            print "Don't eat me! I am super poisonous."

lemon = Fruit("lemon", "yellow", "sour", False)
lemon.description()
lemon.is_edible()

ii. Class Syntax 2/18

class Animal(object):
    pass

iii. Classier Classes 3/18

class Animal(object):
    def __init__(self):
        pass

iv. Let’s Not Get Too Selfish 4/18

class Animal(object):
    def __init__(self,name):
        self.name = name

v. Instantiating your First Object 5/18

class Animal(object):
    def __init__(self,name):
        self.name = name

zebra = Animal("Jeffrey")
print zebra.name

II Member Variables and Functions

i. More on __int()__  and self 6/18

# Class definition
class Animal(object):
    """Makes cute animals."""
    # For initializing our instance objects
    def __init__(self, name, age, is_hungry):
        self.name = name
        self.age = age
        self.is_hungry = is_hungry

# Note that self is only used in the __init__()
# function definition; we don't need to pass it
# to our instance objects.

zebra = Animal("Jeffrey", 2, True)
giraffe = Animal("Bruce", 1, False)
panda = Animal("Chad", 7, True)

print zebra.name, zebra.age, zebra.is_hungry
print giraffe.name, giraffe.age, giraffe.is_hungry
print panda.name, panda.age, panda.is_hungry

ii. Class Scope 7/18

class Animal(object):
    """Makes cute animals."""
    is_alive = True
    def __init__(self, name, age):
        self.name = name
        self.age = age

zebra = Animal("Jeffrey", 2)
giraffe = Animal("Bruce", 1)
panda = Animal("Chad", 7)

print zebra.name, zebra.age, zebra.is_alive
print giraffe.name, giraffe.age, giraffe.is_alive
print panda.name, panda.age, panda.is_alive

iii. A Methodical Approach 8/18

class Animal(object):
    """Makes cute animals."""
    is_alive = True
    def __init__(self, name, age):
        self.name = name
        self.age = age
    # Add your method here!
    def description(self):
        print self.name
        print self.age
hippo = Animal("alpha", 23)

print hippo.description()

iv. They’re Multiplying 9/18

class Animal(object):
    """Makes cute animals."""
    is_alive = True
    health = "good"
    def __init__(self, name, age):
        self.name = name
        self.age = age
       
    # Add your method here!
    def description(self):
        print self.name
        print self.age
      
hippo = Animal("alpha", 23)
sloth = Animal("prop", 15)
ocelot = Animal("cooper", 14)

print hippo.health
print sloth.health
print ocelot.health

v. It’s Not All Animals and Fruits 10/18

class ShoppingCart(object):
    """Creates shopping cart objects
    for users of our fine website."""
    items_in_cart = {}
    def __init__(self, customer_name):
        self.customer_name = customer_name

    def add_item(self, product, price):
        """Add product to the cart."""
        if not product in self.items_in_cart:
            self.items_in_cart[product] = price
            print product + " added."
        else:
            print product + " is already in the cart."

    def remove_item(self, product):
        """Remove product from the cart."""
        if product in self.items_in_cart:
            del self.items_in_cart[product]
            print product + " removed."
        else:
            print product + " is not in the cart."

my_cart = ShoppingCart("Saksham")
my_cart.add_item("Apples", 20)

III Inheritance

i. Warning: Here Be Dragons 11/18

class Customer(object):
    """Produces objects that represent customers."""
    def __init__(self, customer_id):
        self.customer_id = customer_id

    def display_cart(self):
        print "I'm a string that stands in for the contents of your shopping cart!"

class ReturningCustomer(Customer):
    """For customers of the repeat variety."""
    def display_order_history(self):
        print "I'm a string that stands in for your order history!"

monty_python = ReturningCustomer("ID: 12345")
monty_python.display_cart()
monty_python.display_order_history()

ii. Inheritance Syntax 12/18

class Shape(object):
    """Makes shapes!"""
    def __init__(self, number_of_sides):
        self.number_of_sides = number_of_sides

# Add your Triangle class below!

class Triangle(Shape):
    def __init__(self,side1,side2,side3):
        self.side1 = side1
        self.side2 = side2
        self.side3 = side3

iii. Override! 13/18

class Employee(object):
    """Models real-life employees!"""
    def __init__(self, employee_name):
        self.employee_name = employee_name

    def calculate_wage(self, hours):
        self.hours = hours
        return hours * 20.00

# Add your code below!
class PartTimeEmployee(Employee):
    def calculate_wage(self, hours):
        self.hours = hours
        return hours * 12.00

iv. This Looks Like a Job For… 14/18

class Employee(object):
    """Models real-life employees!"""
    def __init__(self, employee_name):
        self.employee_name = employee_name

    def calculate_wage(self, hours):
        self.hours = hours
        return hours * 20.00

# Add your code below!
class PartTimeEmployee(Employee):
    def calculate_wage(self, hours):
        self.hours = hours
        return hours * 12.00
    
    def full_time_wage(self, hours):
        return super(PartTimeEmployee, self).calculate_wage(hours)

milton = PartTimeEmployee("Saksham")
print milton.full_time_wage(10)

IV Review

i. Class Basics 15/18

class Triangle(object):
    def __init__(self,angle1, angle2, angle3):
        self.angle1 = angle1
        self.angle2 = angle2
        self.angle3 = angle3

ii. Class it Up 16/18

class Triangle(object):
    number_of_sides = 3
    def __init__(self,angle1, angle2, angle3):
        self.angle1 = angle1
        self.angle2 = angle2
        self.angle3 = angle3
    
    def check_angles(self):
        if self.angle1 + self.angle2 + self.angle3 == 180:
            return True
        else:
            return False

iii. Instantiate an Object 17/18

class Triangle(object):
    number_of_sides = 3
    def __init__(self,angle1, angle2, angle3):
        self.angle1 = angle1
        self.angle2 = angle2
        self.angle3 = angle3
    
    def check_angles(self):
        if self.angle1 + self.angle2 + self.angle3 == 180:
            return True
        else:
            return False

my_triangle = Triangle(40,90,50)
print my_triangle.number_of_sides
print my_triangle.check_angles()

iv.Inheritance 18/18

class Triangle(object):
    number_of_sides = 3
    def __init__(self,angle1, angle2, angle3):
        self.angle1 = angle1
        self.angle2 = angle2
        self.angle3 = angle3
    
    def check_angles(self):
        if self.angle1 + self.angle2 + self.angle3 == 180:
            return True
        else:
            return False

my_triangle = Triangle(40,90,50)
print my_triangle.number_of_sides
print my_triangle.check_angles()

class Equilateral(Triangle):
    angle = 60
    def __init__(self):
        self.angle1 = self.angle
        self.angle2 = self.angle
        self.angle3 = self.angle

Introduction to Bitwise Operators

I Binary Representation

i. Just a Little BIT 1/14

print 5 >> 4  # Right Shift
print 5 << 1  # Left Shift
print 8 & 5   # Bitwise AND
print 9 | 4   # Bitwise OR
print 12 ^ 42 # Bitwise XOR
print ~88     # Bitwise NOT

ii. Lesson 10: The Base 2 Number System 2/14

print 0b1,    #1
print 0b10,   #2
print 0b11,   #3
print 0b100,  #4
print 0b101,  #5
print 0b110,  #6
print 0b111   #7
print "******"
print 0b1 + 0b11
print 0b11 * 0b11

iii. I Can Count to 1100! 3/14

one = 0b1
two = 0b10
three = 0b11
four = 0b100
five = 0b101
six = 0b110
seven = 0b111
eight = 0b1000
nine = 0b1001
ten = 0b1010
eleven = 0b1011
twelve = 0b1100

iv. The bin() Function

print bin(1)
for each in range(2,6):
    print bin(each)

v. int()’s Second Parameter

print int("1",2)
print int("10",2)
print int("111",2)
print int("0b100",2)
print int(bin(5),2)
# Print out the decimal equivalent of the binary 11001001.
print int("11001001",2)

II The Bitwise Operators
i. Slide to the Left! Slide to the Right!

shift_right = 0b1100
shift_left = 0b1

# Your code here!
shift_right = shift_right >>2
shift_left = shift_left <

ii.A BIT of This AND That

print bin(0b1110 & 0b101)

iii.A BIT of This OR That

print bin(0b1110 | 0b101)

iv.This XOR That?

print bin(0b1110^0b101)

v. See? This is NOT That Hard!
> Save and Submit!
III A Bit More Complicated
i. The Man Behind the Bit Mask

def check_bit4(input):
    mask = 0b1000
    if input & mask > 0:
        return "on"
    else:
        return "off"

ii. Turn It On

a = 0b10111011
mask = 0b100
print bin(a|mask)

iii. Just Flip Out

a = 0b11101110
mask = 0b11111111
print bin(a^mask)

iv. Slip and Slide

def flip_bit(number, n):
    mask = 0b1 << n-1
    return bin(number^mask)

Advanced Topics in Python

I Iteration Nation

i. Iterators for Dictionaries 1/18

my_dict = {
    'Name': 'Sunakshi',
    'Height': 160
}
print my_dict.items()

ii. keys() and values() 2/18

my_dict = {
    'Name': 'Sunakshi',
    'Height': 160
}
print my_dict.keys()
print my_dict.values()

iii. The ‘in’ Operator 3/18

my_dict = {
    'Name': 'Sunakshi',
    'Height': 160
}

for key in my_dict:
    print key, my_dict[key]

II List Comprehensions

i. Building Lists 4/18

>Save and Submit!

ii. List Comprehension Syntax 5/18

doubles_by_3 = [x*2 for x in range(1,6) if (x*2) % 3 == 0]

# Complete the following line. Use the line above for help.
even_squares = [x**2 for x in range(1,12) if x % 2 == 0]
print even_squares

iii. Now you Try! 6/18

cubes_by_four = [ x**3 for x in range(1,11) if x**3 % 4 == 0]
print cubes_by_four

III List Slicing

i. List Slicing Syntax 7/18

l = [i ** 2 for i in range(1, 11)]
# Should be [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

print l[2:9:2]

ii. Omitting Indices 8/18

my_list = range(1, 11) # List of numbers 1 - 10

# Add your code below!
print my_list[::2]

iii. Reversing a List 9/18

my_list = range(1, 11)

# Add your code below!
backwards = my_list[::-1]

iv. Stride Length 10/18

to_one_hundred = range(101)
# Add your code below!
backwards_by_tens = to_one_hundred[::-10]
print backwards_by_tens

v. Practice Makes Perfect 11/18

to_21 = range(1,22)
odds = to_21[::2]
print odds
middle_third = to_21[7:14]
print middle_third

IV Lambdas

i. Anonymous Functions 12/18

>Save and Submit!

ii. Lambda Syntax 13/18

languages = ["HTML", "JavaScript", "Python", "Ruby"]
print filter(lambda x: x == 'Python', languages)

iii. Try it! 14/18

squares = [x**2 for x in range(1,11)]
print filter(lambda i: 30 <= i <=70, squares)

V Review

i. Iterating over Dictionaries 15/18

movies = {
	"Monty Python and the Holy Grail": "Great",
	"Monty Python's Life of Brian": "Good",
	"Monty Python's Meaning of Life": "Okay"
}
print movies.items()

ii. Comprehending Comprehensions 16/18

threes_and_fives = [x for x in range(1,16) if x % 3 == 0 or x % 5 == 0]

iii. List Slicing 17/18

garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI"
message = garbled[::-2]

iv. Lambda Expressions 18/18

garbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX"
message = filter(lambda i: i != 'X', garbled)
print message