In [1]:
import requests # a better package than urllib2
In [2]:
def my_mean(input_list):
list_sum = 0
list_count = 0
for el in input_list:
intValue = int(el)
list_sum += intValue
list_count += 1
return list_sum / list_count
In [3]:
def my_median(input_list):
list_length = len(input_list)
sorted_list = sorted(input_list)
if list_length % 2 == 1: # odd list: we return the central number
return sorted_list[int(list_length/2)]
else: # even list: we sum the two central numbers
mean_idx = int(list_length/2)
return (sorted_list[mean_idx] + sorted_list[mean_idx-1]) / 2
In [4]:
api_key = "ffaf60d7d82258e112dd4fb2b5e4e2d6:3:72421680"
In [5]:
url = "http://api.nytimes.com/svc/search/v2/articlesearch.json?q=gay+marriage&api-key=%s" % api_key # wrong variable case
In [6]:
r = requests.get(url)
In [7]:
wc_list = []
for article in r.json()['response']['docs']:
wc_list.append(article['word_count'])
In [8]:
wc_list = [int(i) for i in wc_list if i != None] # missing conversion to int type
wc_list
Out[8]:
In [9]:
my_mean(wc_list)
Out[9]:
In [10]:
import numpy as np
In [11]:
np.mean(wc_list)
Out[11]:
In [12]:
my_median(wc_list)
Out[12]:
In [13]:
np.median(wc_list)
Out[13]:
In [ ]: