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 [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:
list_sum += el
list_count += 1
output = list_sum / list_count
return output
In [10]:
def my_median(input_list):
list_length = int(len(input_list))
value = list_length % 2
if value != 0: #if list length is odd, in list it would be even-one less as pos begins at 0
l = (list_length-1) /2
med = input_list[int(l)]
else:
med = (input_list[int(list_length/2)] + input_list[(int(list_length/2)) - 1]) / 2
return med
In [ ]:
#k = [1,2,3,4,5,6] # 4 =k[n-1], 3 = k[n-2], 2= [n-1], 1 =[n-n] - k[n/2] + k[n/2-1]
#my_mean(k)
#my_median(k)
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
In [6]:
response = requests.get(url)
data = response.json()
In [7]:
wc_list = []
docs = data['response']['docs']
for i in docs:
num = i['word_count']
if num ==None:
pass
else:
wc_list.append(int(num))
print(wc_list)
In [8]:
my_mean(wc_list)
Out[8]:
In [11]:
my_median(wc_list)
Out[11]:
In [ ]: