In [215]:
import requests # a better package than urllib2
from math import ceil, floor
In [216]:
def my_mean(input_list):
list_sum = 0
list_count = 0
for el in input_list:
list_sum += el
list_count += 1
return list_sum / list_count
In [217]:
def my_median(input_list):
list_length = len(input_list)
if list_length%2 == 0: # if list length even
return (input_list[ceil(list_length/2)] + input_list[floor(list_length/2)])/2
elif list_length%2 != 0: # if list length odd
return input_list[ceil(list_length/2)] # rounds up to nearest integer to find middle position
In [218]:
api_key = "ffaf60d7d82258e112dd4fb2b5e4e2d6:3:72421680"
In [219]:
url = "http://api.nytimes.com/svc/search/v2/articlesearch.json?q=gay+marriage&api-key=%s" % api_key
In [220]:
r = requests.get(url)
In [221]:
wc_list = []
for article in r.json()['response']['docs']:
if article['word_count'] != None:
wc_list.append(int(article['word_count']))
In [222]:
my_mean(wc_list)
Out[222]:
In [223]:
import numpy as np
In [224]:
np.mean(wc_list)
Out[224]:
In [225]:
my_median(wc_list)
Out[225]:
In [226]:
np.median(wc_list)
Out[226]: