Bitly Test - Andrew Conti

1. Text Blocking

In [1]:
def text_blocking(text_array):
    output = []
    text = ''
    for char in range(0, len(text_array[0])): 
        for text_element in range(0, len(text_array)):
            text += text_array[text_element][char]
        output.append(text)
        text = ""  
    return output
            
In [2]:
text_array = ["AAA",
              "BBB",
              "CCC"]
text_blocking(text_array)
Out[2]:
['ABC', 'ABC', 'ABC']
In [3]:
text_array = ["AAAAAAAAAAAAA"]
text_blocking(text_array)
Out[3]:
['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A']
In [4]:
text_array = ["A",
              "A",
              "A",
              "A",
              "A"]
text_blocking(text_array)
Out[4]:
['AAAAA']

2. Race Average

In [5]:
import datetime


class RaceAverage(object):
    ''' Calculates the average times of competitors in a sailboat race.'''
    def __init__(self, start_time):
        self.start_time = self.parse_time(start_time)

    def parse_time(self, time):
        ''' Parses input to datetime objects. '''
        time, day = time.split(', DAY ')
        date = datetime.datetime.strptime(time, "%I:%M %p")
        date += datetime.timedelta(days=(int(day) - 1))
        return date

    def completion_time(self, date):
        ''' Calculates race completion time in minutes'''
        race_duration = date - self.start_time
        return race_duration.total_seconds() / 60

    def avgMinutes(self, times):
        '''
        Calculates the average number of minutes taken by
        the competitors to complete the race. Times are
        rounded up from 0.5.
        '''
        race_completion_times = []
        for time in times:
            finish_time = self.parse_time(time)
            race_completion_times.append(self.completion_time(finish_time))
        average_time = int(round(sum(race_completion_times) / len(race_completion_times)))
        return average_time
In [6]:
race_average = RaceAverage('08:00 AM, DAY 1')
times = ["12:00 PM, DAY 1",
         "12:01 PM, DAY 1"]
race_average.avgMinutes(times)
Out[6]:
241
In [7]:
race_average = RaceAverage('08:00 AM, DAY 1')
times = ["02:00 PM, DAY 19",
         "02:00 PM, DAY 20",
         "01:58 PM, DAY 20"]
race_average.avgMinutes(times)
Out[7]:
27239

3. Hot Phrases

In [8]:
import json
import urllib
import urllib2


class Service(object):
    def __init__(self, host, endpoints, params):
        self.host = host
        self.endpoints = endpoints
        self.params = params

    def generate_url(self, endpoint):
        self.url = self.host + endpoint

    def create_request(self, **kwargs):
        self.request = urllib2.Request(self.url + "?" + urllib.urlencode(self.params))

    def get_data_from_api(self, endpoint):
        self.generate_url(endpoint)
        self.create_request()
        self.response = urllib2.urlopen(self.request).read()

    def pretty_print_response(self, data):
        print json.dumps(self.response, sort_keys=True, indent=4, separators=(',', ': '))
In [9]:
class HotPhrases(Service):
    
    def parse_hot_phrases(self): 
        data = json.loads(self.response)['data']['phrases']
        phrases = [x["phrase"] for x in data]
        return phrases
    
    def get_hot_phrases(self, endpoint, limit):
        self.get_data_from_api(endpoint)
        phrases = self.parse_hot_phrases()
        for phrase in phrases[:limit]:
            print phrase
            
In [10]:
service_parameters = {
    "host": 'https://api-ssl.bitly.com',
    "endpoints": ['/v3/realtime/hot_phrases'],
    "params": {
        "access_token": "a2c09b3944b5e02f50ad49da64e0abe7280f8d95"
    }
}
hot_phrases = HotPhrases(**service_parameters)
hot_phrases.get_hot_phrases(hot_phrases.endpoints[0], 5)
nfl draft
conchita wurst
openly gay player
openly gay
louis rams
In [11]:
class HighValue(Service):
    def parse_high_value_links(self):
        self.high_value_links = json.loads(self.response)['data']['values']

    def get_high_value_links(self, endpoint):
        self.get_data_from_api(endpoint)
        self.parse_high_value_links()

    def get_link_clicks(self, endpoint, link):
        ''' Gets number of clicks for a single link '''
        self.params['link'] = link
        self.get_data_from_api(endpoint)
        return json.loads(self.response)['data']['link_clicks']

    def get_high_value_links_clicks(self, endpoint):
        ''' Gets number of clicks for a list of links '''
        self.high_value_links_clicks = [self.get_link_clicks(endpoint, i) for i in self.high_value_links]

    def show_high_value_links(self, link_endpoint, click_endpoint):
        self.get_high_value_links(link_endpoint)
        self.get_high_value_links_clicks(click_endpoint)
        high_value_link_list = zip(self.high_value_links, self.high_value_links_clicks)
        for link in high_value_link_list:
            print "%s - %s" % link
In [12]:
service_parameters = {
    "host": 'https://api-ssl.bitly.com',
    "endpoints": ['/v3/realtime/hot_phrases',
                  '/v3/highvalue',
                  '/v3/link/clicks'],
    "params": {
        "access_token": "a2c09b3944b5e02f50ad49da64e0abe7280f8d95",
        "limit": 10
    }
}
high_value = HighValue(**service_parameters)
In [13]:
high_value.show_high_value_links(high_value.endpoints[1], high_value.endpoints[2])
http://bit.ly/PbKEGW - 4039
http://bit.ly/1iA2xME - 141619
http://bit.ly/1jpwHli - 170
http://bit.ly/1fPLHJo - 10996
http://bit.ly/Rq6wjz - 981
http://bit.ly/1jItTzc - 230
http://bit.ly/1fBuiEg - 2122
http://bit.ly/QhFP0q - 192642
http://bit.ly/1kVu5rR - 225
http://bit.ly/1qfP94u - 58901
In [13]: