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

2.12 Python Lab: Comparing voting records using dot-product In this lab, we will

ID: 3594160 • Letter: 2

Question

2.12 Python Lab: Comparing voting records using dot-product In this lab, we will represent a US senator’s voting record as a vector over R, and will use dot-products to compare voting records. For this lab, we will just use a list to represent a vector.

Task 2.12.7: Write a procedure find average similarity(sen, sen set, voting dict) that, given the name sen of a senator, compares that senator’s voting record to the voting records of all senators whose names are in sen set, computing a dot-product for each, and then returns the average dot-product. Use your procedure to compute which senator has the greatest average similarity with the set of Democrats (you can extract this set from the input file).

Task 2.12.8: Write a procedure find average record(sen set, voting dict) that, given a set of names of senators, finds the average voting record. That is, perform vector addition on the lists representing their voting records, and then divide the sum by the number of vectors. The result should be a vector.

Explanation / Answer

myvoted_data = list(open("myvotingfile.txt"))

Task 2.12.7

def find_avg_sim(senator, senator_set, v_dict):

     The inputs are the name of the senator, a set of senator names and a vote dictionary
     The output is the average dot product between senators and a set of senenators

return sum([poll_comp(senator,k,v_dict) for k in senator_set])/len(senator_set)

def poll_compare(senator_a, senator_b, v_dict):
    
return sum([v_dict[senator_a][k]*v_dict[senator_b][k] for k in range(len(v_dict[senator_a]))])

Task 2.12.8

def my_avg(senator_set, v_dict):

     The inputs are the name of the senator, a set of senator names and a vote dictionary
     The output is the average dot product between   senators and a set of senenators

    The inputs are a set of senator names, a voting dictionary
    The output is a vector containing the average components of the voting records of the senators
    ie vector addition on the lists representing their voting records, and then divide the sum by the number of vectors
  
    return [sum([v_dict[senator][k] for senator in senator_set])/len(senator_set) for k in range(len(list(v_dict.values())[0]))]


cheers...