Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Python Programming Task 2.12.1: Write a procedure create voting dict(strlist) th

ID: 3598615 • Letter: P

Question

Python Programming

Task 2.12.1: Write a procedure create voting dict(strlist) that, given a list of strings (voting records from the source file), returns a dictionary that maps the last name of a senator to a list of numbers representing that senator’s voting record. You will need to use the built-in procedure int(·) to convert a string representation of an integer (e.g. ‘1’) to the actual integer (e.g. 1).

Task 2.12.2: Write a procedure policy compare(sen a, sen b, voting dict) that, given two names of senators and a dictionary mapping senator names to lists representing voting records, returns the dot-product representing the degree of similarity between two senators’ voting policies.

Task 2.12.3: Write a procedure most similar(sen, voting dict) that, given the name of a senator and a dictionary mapping senator names to lists representing voting records, returns the name of the senator whose political mindset is most like the input senator (excluding, of course, the input senator him/herself).

Task 2.12.4: Write a very similar procedure least similar(sen, voting dict) that returns the name of the senator whose voting record agrees the least with the senator whose name is sen.

Explanation / Answer

def create_voting_dict(strlist):
voting_dict = {}
for detail in strlist:
senator = detail.split()
voting_dict[senator[0]] = [ int(i) for i in senator[3:len(senator)] ]
return voting_dict

def policy_compare(sen_a, sen_b, voting_dict):
sen_a_votes = voting_dict[sen_a]
sen_b_votes = voting_dict[sen_b]
similarity = 0
for i in range(len(sen_a_votes)):
similarity += sen_a_votes[i]*sen_b_votes[i]
return similarity

def most_similar(sen, voting_dict):
similarity = { k:policy_compare(sen, k, voting_dict) for k in voting_dict if k != sen }
voting_similarity = list(distance.values())
senetors = list(distance.keys())
return senetors[voting_similarity.index(max(voting_similarity))]

def least_similar(sen, voting_dict):
similarity = { k:policy_compare(sen, k, voting_dict) for k in voting_dict if k != sen }
voting_similarity = list(distance.values())
senetors = list(distance.keys())
return senetors[voting_similarity.index(min(voting_similarity))]

# copy pastable code: https://paste.ee/p/MyIx3