PyCon 2012 Beginner Python Solutions

sample.py

import types
import unittest

class SampleTest(unittest.TestCase):
    def test_example(self):
        """
        An example of how to do the tests
        """
        # Variables
        #
        # Create a variable ``name`` that is assigned to the string
        # "Matt".
        # ================================
        name = "Matt"
        self.assert_(isinstance(name, types.StringType))
        self.assertEquals(name, 'Matt')

if __name__ == '__main__':
    unittest.main()

variables.py

import unittest

class TestVariables(unittest.TestCase):
    def test_variables(self):
        """
        This is a test method you will need to fill in the content
        where it says and then run it (ie ``python variables.py``).
        If it doesn't complain, then you pass!
        """
        # create a the variable ``a`` and assign it to a float (5.0)
        # **************************************************
        a=5.0
        self.assert_(isinstance(a, float))

        # re-assign ``a`` to 6
        # **************************************************
        a = 6
        self.assertEqual(a, 6)
        self.assert_(isinstance(a, int))

        # create a variable ``b`` assigned to "hello"
        # **************************************************
        b = "hello"
        self.assertEqual(b, "hello")
        self.assertTrue(isinstance(b, str))
        
if __name__ == '__main__':
    unittest.main()

strings.py

import unittest

class TestStrings(unittest.TestCase):
    def test_strings(self):
        """
        A basic introduction to strings
        """
        # Create the variable ``a`` and assign 'hello world'
        #**************************************************
        a='hello world'
        self.assertEqual(a, """hello world""")
        self.assert_(isinstance(a, str))

        # Create a string, ``b`` that equals ``a`` multiplied by 2
        #**************************************************
        b = a * 2
        self.assertEqual(b, 'hello worldhello world')

        # Triple quoted strings (with ''' or """) allow embedded of
        # both single and double quotes.
        # Create a triple quoted string
        # ``c`` that has the following content:
        # Frank said, "That's not a way to talk to an economist!"
        #**************************************************
        c = '''Frank said, "That's not a way to talk to an economist!"'''
        self.assertEqual(c, 'Frank said, "That\'s not a way to talk to an economist!"')

        # Assign the method names of a string to a variable ``d``
        # use ``dir()`` to list them
        #**************************************************
        d = dir(a)
        self.assertEqual(d, ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'])

        # Create a variable e that has holds the index of the
        # substring "o w" in the string a.  (Use a string method to
        # figure it out)
        #**************************************************
        e=a.index("o w")
        self.assertEqual(e, 4)
       
if __name__ == '__main__':
    unittest.main()

lists.py

import unittest

class TestLists(unittest.TestCase):
    def test_lists(self):
        """
        A basic introduction to lists
        """
        # Create the variable ``a`` and assign to an empty list
        # **************************************************
        a= []
        self.assertEquals(a, [])

        # Append 'fred' and 'arnold' to ``a``
        # **************************************************
        a.append('fred')
        a.append('arnold')
        self.assertEquals(a, ['fred', 'arnold'])

        # Sort ``a``
        # **************************************************
        a.sort()
        self.assertEquals(a, ['arnold', 'fred'])

        # ``extend`` the list ``a`` with ['barney', 'george']
        # **************************************************
        a.extend(['barney', 'george'])
        self.assertEquals(a, ['arnold', 'fred', 'barney', 'george'])

        # create a variable ``idx`` with the index of 'barney' in ``a`` using list methods.
        # **************************************************
        idx=a.index('barney')
        self.assertEquals(idx, 2)
       
if __name__ == '__main__':
    unittest.main()

dictionaries.py

import unittest

class TestDicts(unittest.TestCase):
    def test_dicts(self):
        """
        A basic introduction to dictionaries
        """
        # Create the variable ``room2names`` and assign to an empty dict
        #**************************************************
        room2names={}
        self.assertEquals(room2names, {})

        # map the string 'room1' to an empty list
        #**************************************************
        room2names["room1"] = []
        self.assertEquals(room2names['room1'], [])
        self.assert_('room1' in room2names)

        # map the string 'room2' to ['fred', 'hermione']
        #**************************************************
        room2names["room2"]= ['fred', 'hermione']
        self.assertEquals(room2names['room2'], ['fred', 'hermione'])

        # add 'harry' to the list in 'room1'
        room2names["room1"].append('harry')
        self.assertEquals(room2names['room1'], ['harry'])

        # use ``setdefault`` to assign the contents of 'room3'
        # to an empty list and store the result in variable ``empty``
        empty=room2names.setdefault('room3',[])
        self.assertEquals(room2names['room3'], [])
        self.assertEquals(empty, [])

        # use ``in`` to see if 'room4' is there.
        # assign the results to variable ``d``
        d = "room4" in room2names
        self.assertEquals(d, False)

        # use ``del`` to remove 'room1'
        del room2names['room1']
        self.assert_('room1' not in room2names)

if __name__ == '__main__':
    unittest.main()

functions.py

import types
import unittest

class TestFunctions(unittest.TestCase):
    def test_functions(self):
        """
        A basic introduction to functions
        """
        # Define a function called ``add_2`` that returns 2 more than
        # what is passed into it.  Normally function are global to a
        # module, but they can also be defined in the scope of another
        # function.  You can either put it below, or outside of the
        # TestFunctions class.
        # ================================
        def add_2(num): return num+2
        self.assert_(isinstance(add_2, types.FunctionType))
        self.assertEquals(add_2(4), 6)

        # Write a function ``add_3`` that has the following docstring:
        # "Adds 3 to the input"
        # ================================
        def add_3(): "Adds 3 to the input"
        self.assertEquals(add_3.__doc__, 'Adds 3 to the input')

        # Default Parameters.
        # Write a function ``mul_n`` that takes one or two parameters (the second parameter named ``x``).
        # If it has 2 parameters it multiplies them.  If it takes one
        # parameter, it multiplies it by 5
        # ================================
        def mul_n(y,x=5): return y*x
        self.assertEquals(mul_n(5,1), 5)
        self.assertEquals(mul_n(5), 25)
        self.assertEquals(mul_n.func_defaults, (5,))

if __name__ == '__main__':
    unittest.main()

loops.py

import unittest

class TestLoops(unittest.TestCase):
    def test_loops(self):
        # Using ``range``
        # Write variable ``a`` that holds 0 to 5 (use the ``range`` function)
        # ================================
        a=range(0,6)
        self.assertEquals(a, [0,1,2,3,4,5])

        # ``range`` 2
        # Create variable ``b`` that holds from 3 to 11
        # ================================
        b=range(3,12)
        self.assertEquals(b, [3,4,5,6,7,8,9,10,11])

        # Write a function ``even`` that takes a list of
        # number and returns a list of even numbers
        # ================================
        def even(num):
            evenlist=[]
            for k in num:
                if k%2==0:
                    evenlist.append(k)
            return  evenlist
        self.assertEquals(even(a), [0, 2, 4])
        self.assertEquals(even(b), [4, 6, 8, 10])

        # Write a function ``even_index`` that takes a list
        # of numbers and returns those that are in an even
        # index position
        # ================================
        def even_index(num):
            newlist=[]
            for index, value in enumerate(num):
                if index%2==0:
                    newlist.append(value)
            return newlist
        self.assertEquals(even_index(a), [0, 2, 4])
        self.assertEquals(even_index(b), [3, 5, 7, 9, 11])

if __name__ == '__main__':
    unittest.main()

Classes.py

import unittest

class TestClass(unittest.TestCase):
    def test_classes(self):
        # Create a class called ``Echoer``
        # Accept a name in the constructor
        # ================================
        class Echoer(object):
            def __init__(self,name):
                self.name = name
            def say(self, strval):
                return '''%s said, "%s\"''' % (self.name,strval)
        e = Echoer('matt')
        self.assert_(isinstance(e, Echoer))

        # Add a method ``say`` to Echoer that
        # accepts a string and returns:
        # ${name} said, "${string}"
        # ================================
      
        self.assertEquals(e.say('hi'), 'matt said, "hi"')

        # Subclass - create a subclass ``Screamer``
        # of ``Echoer`` that has the same constructor
        # but ``say`` returns:
        # ${name} screamed, "${string.upper()}"
        # ================================
        class Screamer(Echoer):
            def say(self, strval):
                return '''%s screamed, "%s\"''' % (self.name,strval.upper())
        s = Screamer("Frank")
        self.assertEquals(s.say('later'), 'Frank screamed, "LATER"')


if __name__ == '__main__':
    unittest.main()

Python send email Gmail

Below is sample code for sending email through Gmail using Python

import smtplib;
fromaddr = 'email@gmail.com'
toaddrs = 'email@gmail.com'
msg = 'My first email message from Python'
username = 'email@gmail.com'
password = '###'
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()

Twitter Python API Tutorial

Playing around with the Twitter Python API.
Download:

wget http://code.google.com/p/python-twitter/downloads/detail?name=python-twitter-0.8.2.tar.gz

Extract:

tar -xvf python-twitter-0.8.2.tar.gz

Install Twitter (navigate inside the Twitter extracted folder)

sudo python setup.py install

Make sure Python Setuptool is installed

apt-get install python-setuptools

Install dependent files

httplib2-0.7.2$ sudo python setup.py install
simplejson-2.3.2$ sudo python setup.py install
simplegeo-python-oauth2-a83f4a2$ python setup.py build
simplegeo-python-oauth2-a83f4a2$ sudo python setup.py install

Register your Twitter application: https://dev.twitter.com/
Make sure you application Access Level is: Read, write, and direct messages.

Now we need to get access code for our application. Run get_access_token.py file with your consumer_key and consumer_secret inside that you got from creating your application.
Run:

sudo python get_access_token.py

It will show a link to to access with Passcode?. Click on the link to open and enter the Passcode value displayed in the webpage. It will then provide you with a access_token_key and access_token_secret which you can use in the code below:

List Twitter friends sample code:

import twitter
mytwitteraccount = twitter.Api(consumer_key='###', consumer_secret='###', access_token_key='###', access_token_secret='###')
friends=mytwitteraccount.GetFriends()
print[u.name for u in friends]

Make twitter post:

import twitter
mytwitteraccount = twitter.Api(consumer_key='###', consumer_secret='###', access_token_key='###', access_token_secret='###')
status=mytwitteraccount.PostUpdates('My first API call using Python')

Python writing reading large datasets script

Below is a script to read and write to and from large datasets saved as csv files.

Writing datasets to an csv file.

import csv
#writing data into csv file
writer = csv.writer(open('dataset.csv', 'wb', buffering=0))
writer.writerows([
('GOOG', 'Google Inc.', 123.44, 0.32, 0.09),
('YHOO', 'Yahoo! Inc.', 2.33, 99.23, 0.123),
('IBM', 'IBM Inc.', 223.44, 212.32, 6.42)
])

Reading from large datasets csv files

import csv
dataset = csv.reader(open('dataset.csv', 'rb'))
status_labels = {-1: 'down', 0: 'unchanged', 1: 'up'}
for ticker, name, price, change, pct in dataset:
	status = status_labels[cmp(float(change), 0.0)]
print '%s is %s (%s%%)' % (name, status, pct)

This script is good for importing large datasets for you Hadoop jobs.