Last active
October 14, 2016 23:18
-
-
Save izolate/3a20e05a485bf23a1396 to your computer and use it in GitHub Desktop.
Calculate the average number of students per section
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Solution for Clever's job application. | |
Figuring out the average number of students per section. | |
""" | |
import requests | |
import json | |
class Clever: | |
def __init__(self, auth): | |
""" Setup the interface to Clever API """ | |
self.url = 'https://api.clever.com/v1.1/sections' | |
self.headers = {'Authorization': auth} | |
self.sections = [] | |
self.page, self.total_pages = 1, 1 | |
def get_sections(self): | |
""" GET request to /sections """ | |
url = '{0}?page={1}'.format(self.url, self.page) | |
req = requests.get(url, headers=self.headers) | |
if req.status_code is not 200: | |
print('Error connecting to Clever API') | |
raise SystemExit | |
else: | |
body = json.loads(req.text) | |
for section in body['data']: | |
self.sections.append(section) | |
self.total_pages = body['paging']['total'] | |
self.page += 1 | |
while self.page <= self.total_pages: | |
self.get_sections() | |
if __name__ == '__main__': | |
clever = Clever('Bearer DEMO_TOKEN') | |
clever.get_sections() | |
students = [] | |
for section in clever.sections: | |
students.append(len(section['data']['students'])) | |
# sum of students divided by number of sections | |
average = sum(students) / float(len(clever.sections)) | |
print('On average, there are {0} students per section.'.format(round(average, 2))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment