The writer of this code wants to count the mean and median article length for recent articles on gay marriage in the New York Times. This code has several issues, including errors. When they checked their custom functions against the numpy functions, they noticed some discrepancies. Fix the code so it executes properly, retrieves the articles, and outputs the correct result from the custom functions, compared to the numpy functions.


In [10]:
import requests # a better package than urllib2

In [50]:
def my_mean(input_list):
    list_sum = 0
    list_count = 0
    for el in input_list:
        if el is not None: #Checking if the element is None
            list_sum += el
            list_count += 1 #NOT COUNTING THE ARTICLE THAT HAS NONETYPE AS A RESULT. IF PUT OUTSIDE THE IF, ARTICLE WILL BE COUNTED.
    return list_sum / list_count

In [75]:
def my_median(input_list):
    list_length = len(input_list)
    return input_list[int(list_length/2)] #RETURNING AN INTEGER

In [76]:
api_key = "ffaf60d7d82258e112dd4fb2b5e4e2d6:3:72421680"

In [77]:
url = "http://api.nytimes.com/svc/search/v2/articlesearch.json?q=gay+marriage&api-key=%ffaf60d7d82258e112dd4fb2b5e4e2d6:3:72421680"

In [78]:
r = requests.get(url)

In [79]:
wc_list = []
for article in r.json()['response']['docs']:
    if article['word_count'] is not None:
        wc_list.append(int(article['word_count']))

In [80]:
wc_list


Out[80]:
[25, 920, 576, 868, 1101, 684, 588, 367, 1358]

In [81]:
my_mean(wc_list)


Out[81]:
720.7777777777778

In [82]:
import numpy as np

In [83]:
np.mean(wc_list)


Out[83]:
720.77777777777783

In [84]:
my_median(wc_list)


Out[84]:
1101

In [85]:
np.median(wc_list)


Out[85]:
684.0

In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]: