Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #
- # CS1010S --- Programming Methodology
- #
- # Sidequest 12.1 Template
- #
- # Note that written answers are commented out to allow us to run your
- # code easily while grading your problem set.
- import json
- # Reading json file
- def read_json(filename):
- """
- Reads a json file and returns a list of modules
- To find out more about json, please google ;)
- For example, cs1010s-fbdata.json contains:
- {
- "members": {
- "data": [
- {
- "name": "Sunyoung Hwang",
- "id": "970478132994592"
- },
- {
- "name": "Nguy\u1ec5n Th\u1ea3o Ng\u00e2n",
- "id": "790182697716021"
- },
- {
- "name": "Tu Anh",
- "id": "10201625605746698"
- },
- ...
- ]
- },
- ...
- "description": "This is the official FB Group for CS1010S: Programming Methodology taught in Python.",
- "name": "CS1010S",
- "feed": {
- "data": [
- {
- "message": "Yay! :D \n\nhttps://www.facebook.com/saosin1994/posts/10204422037065788",
- "from": {
- "name": "Jeffrey Lee",
- "id": "718371011538995"
- },
- "name": "If you're new to coding, this is the programming language you should learn first",
- "id": "422428264540999_888704734580014",
- "likes": {
- "data": [
- {
- "id": "187291868313225",
- "name": "May Tan"
- },
- {
- "id": "10153290038157072",
- "name": "Goh See Ting"
- }
- ],
- ...
- }
- }
- ]
- }
- }
- """
- datafile = open(filename, 'r', encoding='utf-8')
- return json.loads(datafile.read())
- # CS1010S Facebook Group Data as a dictionary object
- fb_data = read_json('cs1010s-fbdata.json')
- ##########
- # Task a #
- ##########
- def count_comments(data):
- result = 0
- for post in data["feed"]["data"]:
- if 'comments' in post.keys():
- result += len(post['comments']['data'])
- return result
- print("Number of Comments in CS1010S: ", count_comments(fb_data))
- ##########
- # Task b #
- ##########
- def count_likes(data):
- # Returns the total number of likes (in feed posts and comments)
- result = 0
- for post in data["feed"]["data"]:
- if 'likes' in post.keys():
- result += len(post['likes']['data'])
- if 'comments' in post.keys():
- for comment in post['comments']['data']:
- result += comment['like_count']
- return result
- print("Number of Likes in CS1010S: ", count_likes(fb_data))
- ##########
- # Task c #
- ##########
- def create_member_dict(data):
- # Lookup table where key is id and value is member data object
- members_dict = dict()
- for member in data["members"]["data"]:
- members_dict[member['id']] = dict([(key,value) for key, value in member.items() if key != 'id'])
- return members_dict
- member_dict = create_member_dict(fb_data)
- #print(member_dict["10202689170610256"])
- # Q: Why did we choose the id of the member data object to be the key?
- # A:
- # Q: It is inappropriate to use the name as the key. What will happen if we use the name as the key of member_dict?
- # A:
- ##########
- # Task d #
- ##########
- def posts_freq(data):
- # Returns a dict where key is fb_id and value is number of posts in feed
- result = dict()
- for post in data["feed"]["data"]:
- if post['from']['id'] in result.keys():
- result[post['from']['id']] += 1
- else:
- result[post['from']['id']] = 1
- return result
- #print("Posts Frequency: ", posts_freq(fb_data))
- ##########
- # Task e #
- ##########
- def comments_freq(data):
- # Returns a dict where key is fb_id and value is number of comments in feed
- result = dict()
- for post in data["feed"]["data"]:
- if 'comments' in post.keys():
- for comment in post['comments']['data']:
- if comment['from']['id'] in result.keys():
- result[comment['from']['id']] += 1
- else:
- result[comment['from']['id']] = 1
- return result
- #print("Comments Frequency: ", comments_freq(fb_data))
- ##########
- # Task f #
- ##########
- def likes_freq(data):
- # Returns a dict where key is fb_id and value is number of likes in feed
- result = dict()
- for post in data["feed"]["data"]:
- if 'likes' in post.keys():
- for like in post['likes']['data']:
- if like['id'] in result.keys():
- result[like['id']] += 1
- else:
- result[like['id']] = 1
- return result
- # print("Likes Frequency: ", likes_freq(fb_data))
- ##########
- # Task g #
- ##########
- def popularity_score(data):
- # Returns a dict where key is fb_id and value is the number of likes
- # a person's posts and comments have
- result = dict()
- for post in data["feed"]["data"]:
- if 'likes' in post.keys():
- if post['from']['id'] in result.keys():
- result[post['from']['id']] += len(post['likes']['data'])
- else:
- result[post['from']['id']] = len(post['likes']['data'])
- if 'comments' in post.keys():
- for comment in post['comments']['data']:
- if comment['like_count'] != 0:
- if comment['from']['id'] in result.keys():
- result[comment['from']['id']] += comment['like_count']
- else:
- result[comment['from']['id']] = comment['like_count']
- return result
- # print("Popularity Score: ", popularity_score(fb_data))
- ##########
- # Task h #
- ##########
- def member_stats(data):
- # Expand the member dict to include the keys:
- # 'posts_count', 'comments_count' and 'likes_count'
- post = posts_freq(data)
- cmt = comments_freq(data)
- likes = likes_freq(data)
- input_dict = create_member_dict(data)
- for member_id in input_dict.keys():
- if member_id in post.keys():
- input_dict[member_id]['posts_count'] = post[member_id]
- else:
- input_dict[member_id]['posts_count'] = 0
- if member_id in cmt.keys():
- input_dict[member_id]['comments_count'] = cmt[member_id]
- else:
- input_dict[member_id]['comments_count'] = 0
- if member_id in likes.keys():
- input_dict[member_id]['likes_count'] = likes[member_id]
- else:
- input_dict[member_id]['likes_count'] = 0
- return input_dict
- stats = member_stats(fb_data)
- #print(stats["625742960877771"], '\n')
- ##########
- # Task i #
- ##########
- def activity_score(data):
- input_dict = member_stats(data)
- result = dict()
- for member_id in input_dict.keys():
- score = input_dict[member_id]['posts_count'] * 3 + input_dict[member_id]['comments_count'] * 2 + input_dict[member_id]['likes_count'] * 1
- result[member_id] = score
- return result
- scores = activity_score(fb_data)
- #print(scores["806647796032627"]) # => 25
- #print(scores["773847432675142"]) # => 0
- ##########
- # Task j #
- ##########
- def active_members_of_type(data, k, type_fn):
- # This is a higher order function, where type is a function and
- # can be either posts_freq, comments_freq, likes_freq, etc
- # and filters out the pairs that have frequency >= k
- result =[]
- members_dict = create_member_dict(data)
- output_type = list(type_fn(data).items())
- for mem in output_type:
- if mem[1] >= k and mem[0] in members_dict.keys():
- result.append([members_dict[mem[0]]['name'],mem[1]])
- result.sort()
- result.sort(key = lambda x: x[1], reverse = True)
- return result
- print(active_members_of_type(fb_data, 2, posts_freq))
- #print(active_members_of_type(fb_data, 20, comments_freq))
- #print(active_members_of_type(fb_data, 40, likes_freq))
- #print(active_members_of_type(fb_data, 20, popularity_score))
- print(active_members_of_type(fb_data, 80, activity_score))
- ########### DO NOT REMOVE THE TEST BELOW ###########
- def gradeit():
- print("\n*** Facebook Stalker Autograding ***")
- print('==================')
- answers = json.loads(open('grading.json', 'r', encoding='utf-8').read())
- total, correct = 0, 0
- def pass_or_fail(code, answer):
- nonlocal total
- total += 1
- if code == answer:
- nonlocal correct
- correct += 1
- return 'Passed!'
- else:
- return 'Failed.'
- print('Testing count_comments... ', pass_or_fail(count_comments(fb_data), answers['count_comments']))
- print('Testing count_likes... ', pass_or_fail(count_likes(fb_data), answers['count_likes']))
- print('Testing create_member_dict... ', pass_or_fail(create_member_dict(fb_data), answers['create_member_dict']))
- print('Testing posts_freq... ', pass_or_fail(posts_freq(fb_data), answers['posts_freq']))
- print('Testing comments_freq... ', pass_or_fail(comments_freq(fb_data), answers['comments_freq']))
- print('Testing likes_freq... ', pass_or_fail(likes_freq(fb_data), answers['likes_freq']))
- print('Testing popularity_score... ', pass_or_fail(popularity_score(fb_data), answers['popularity_score']))
- print('Testing member_stats... ', pass_or_fail(member_stats(fb_data), answers['member_stats']))
- print('Testing activity_score... ', pass_or_fail(activity_score(fb_data), answers['activity_score']))
- print('Testing members with >= 1 posts... ', pass_or_fail(active_members_of_type(fb_data, 1, posts_freq), answers['active_posters']))
- print('Testing members with >= 4 comments... ', pass_or_fail(active_members_of_type(fb_data, 4, comments_freq), answers['active_commenters']))
- print('Testing members with >= 4 likes... ', pass_or_fail(active_members_of_type(fb_data, 4, likes_freq), answers['active_likers']))
- print('Testing members who have >= 3 likes... ', pass_or_fail(active_members_of_type(fb_data, 3, popularity_score), answers['popular']))
- print('Testing members with an activity score of >= 10... ', pass_or_fail(active_members_of_type(fb_data, 10, activity_score), answers['overall_active']))
- print('==================')
- print('Grades: ' + str(correct) + '/' + str(total) + '\n')
- gradeit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement