problem23 spring
pdf
keyboard_arrow_up
School
Georgia Institute Of Technology *
*We aren’t endorsed by this school
Course
6040
Subject
Computer Science
Date
Dec 6, 2023
Type
Pages
41
Uploaded by ChefStraw5566
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
1/41
Midterm 1: How partisan is the US Congress?
Version 1.1b (Simplified sample solution for Exercise 6)
This problem is about basic data processing using Python. It exercises your fundamental knowledge of Python
data structures, such as lists, dictionaries, and strings. It has seven exercises, numbered 0-6.
Each exercise builds on the previous one. However, they may be completed independently. That is, if you can't
complete an exercise, we provide some code that can run to load precomputed results for the next exercise.
That way, you can keep moving even if you get stuck.
Pro-tips.
If your program behavior seem strange, try resetting the kernel and rerunning everything.
If you mess up this notebook or just want to start from scratch, save copies of all your partial
responses and use
Actions
Reset Assignment
to get a fresh, original copy of this notebook.
(Resetting will wipe out any answers you've written so far, so be sure to stash those somewhere safe if
you intend to keep or reuse them!)
If you generate excessive output (e.g., from an ill-placed
print
statement) that causes the notebook
to load slowly or not at all, use
Actions
Clear Notebook Output
to get a clean copy. The
clean copy will retain your code but remove any generated output.
However
, it will also
rename
the
notebook to
clean.xxx.ipynb
. Since the autograder expects a notebook file with the original name,
you'll need to rename the clean notebook accordingly.
Good luck!
Background
The United States Congress is the part of the US government that makes laws for the entire country. It is
dominated by two rival political parties, the Democrats and the Republicans. You would expect that these
parties oppose each other on most issues but occasionally agree.
Some have conjectured that, over time, the two parties agree less and less, which would reflect a perceived
growing ideological or political divide in the US. But is that the real trend? In this problem, you'll explore this
question using data collected by
ProPublica
(https://www.propublica.org/), a nonprofit investigative media
organization.
Setup and data loading
Run the code cells below to load the data. This code will hold the data in two variables, one named
votes
and
another named
positions
.
→
→
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
2/41
In [1]:
import
sys
print(f"* Python version:
{sys.version}
")
from
testing_tools
import
load_json, save_json, load_pickle, save_pick
le
votes = load_json("votes.json")
vote_positions = [p
for
p
in
load_json("positions.json")
if
p['positio
ns']]
print("
\n
==> Data loading complete.")
### BEGIN HIDDEN TESTS
%
load_ext
autoreload
%
autoreload
2
### END HIDDEN TESTS
Part 0: Analyzing vote results
The Congress votes on various things, like new laws or political nominations. The results of these votes are
stored in the
votes
variable loaded above. Let's look at it. First, note that
votes
is a list:
In [2]:
print(type(votes))
print("Length:", len(votes))
Vote results.
What is
votes
a list of? Each element is one
vote result.
Let's look at the first entry.
* Python version: 3.7.5 (default, Dec 18 2019, 06:24:58)
[GCC 5.5.0 20171010]
* JSON module version: 2.0.9
'./resource/asnlib/publicdata/votes.json': 28596
'./resource/asnlib/publicdata/positions.json': 279
==> Data loading complete.
<class 'list'>
Length: 28596
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
3/41
In [3]:
from
testing_tools
import
inspect_data
inspect_data(votes[0])
# View the first element of the list, `votes`
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
4/41
{
"congress": 106,
"chamber": "Senate",
"session": 1,
"roll_call": 374,
"source": "https://www.senate.gov/legislative/LIS/roll_call_votes/
vote1061/vote_106_1_00374.xml",
"url": "https://www.senate.gov/legislative/LIS/roll_call_lists/rol
l_call_vote_cfm.cfm?congress=106&session=1&vote=00374",
"vote_uri": "https://api.propublica.org/congress/v1/106/senate/ses
sions/1/votes/374.json",
"bill": {
"bill_id": "h.r.3194-106",
"number": "H.R..3194",
"sponsor_id": null,
"api_uri": null,
"title": null,
"latest_action": null
},
"question": "On the Conference Report",
"question_text": "",
"description": "H.R.3194 Conference report; Consolidated Appropria
tions Act, 2000",
"vote_type": "1/2",
"date": "1999-11-19",
"time": "17:45:00",
"result": "Agreed to",
"democratic": {
"yes": 32,
"no": 12,
"present": 0,
"not_voting": 1,
"majority_position": "Yes"
},
"republican": {
"yes": 42,
"no": 12,
"present": 0,
"not_voting": 1,
"majority_position": "Yes"
},
"independent": {
"yes": 0,
"no": 0,
"present": 0,
"not_voting": 0
},
"total": {
"yes": 74,
"no": 24,
"present": 0,
"not_voting": 2
}
}
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
5/41
Observation 0.
This first entry of the list is a dictionary, and the data structure is nested even more. For
instance, the
"bill"
key has another dictionary as its value.
Remember that what you see above is
votes[0]
, the first entry of the
votes
list. For the rest of this problem,
you may assume that all other entries of
votes
have the same keys and nesting structure.
Exercise 0
(2 points). Let's pick out a subset of the data to analyze. Complete the function below,
filter_votes(votes)
.
The input,
votes
, is a list of vote results like the one above.
Your function should return a copy of this list, keeping
only
vote results meeting the following criteria:
1. The
'vote_type'
is one of the following:
"1/2"
,
"YEA-AND-NAY"
,
"RECORDED VOTE"
2. Notice that the
'total'
key is a dictionary. Retain only the vote results where this dictionary
has
all
of the fields
'yes'
,
'no'
,
'present'
, and
'not_voting'
.
Your copy should include vote results in the same order as the input list.
Note 0:
The reason for Condition 2 above is that for some vote results, the
'total'
dictionary
does not have those fields. For an example, see
votes[18319]
. You would not include that
vote result in your output.
Note 1:
The test cell does not use real vote results, but randomly generated synthetic ones. Your
solution should
not
depend on the presence of any specific keys other than the ones you need
for filtering, namely,
'vote_type'
and
'total'
.
As an example, suppose
V
is the following vote results list (only the salient keys are included):
V = [ {'vote_type': "1/2", 'total': {'yes': 5, 'no': 8, 'present': 0, 'not_v
oting': 2}, ...},
{'vote_type': "RECORDED VOTE", 'total': {'yes': 12, 'present': 2, 'not
_voting': 1}, ...},
{'vote_type': "3/5", 'total': {'yes': 50, 'no': 14, 'present': 0, 'not
_voting': 0}, ...},
{'vote_type': "YEA-AND-NAY", 'total': {'yes': 25, 'no': 3, 'present':
3, 'not_voting': 0}, ...} ]
Then running
filter_votes(V)
would return the following new list:
[ {'vote_type': "1/2", 'total': {'yes': 5, 'no': 8, 'present': 0, 'not_votin
g': 2}, ...},
{'vote_type': "YEA-AND-NAY", 'total': {'yes': 25, 'no': 3, 'present': 3,
'not_voting': 0}, ...} ]
In this case,
V[1]
is omitted because its
'total'
key is missing the
'no'
key; and
V[2]
is omitted because
the
'vote_type'
is not one of
"1/2"
,
"YEA-AND-NAY"
, or
"RECORDED VOTE"
.
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
6/41
In [4]:
def
filter_votes(votes):
assert
isinstance(votes, list)
and
len(votes) >= 1
assert
isinstance(votes[0], dict)
### BEGIN SOLUTION
def
matches(v):
return
(v["vote_type"]
in
{"1/2", "YEA-AND-NAY", "RECORDED VOT
E"}) \
and
(set(v["total"].keys()) == {"yes", "no", "present",
"not_voting"})
return
[v
for
v
in
votes
if
matches(v)]
### END SOLUTION
In [5]:
# Demo cell (feel free to use and edit for debugging)
V = [ {'vote_type': "1/2", 'total': {'yes': 5, 'no': 8, 'present': 0,
'not_voting': 2}},
{'vote_type': "RECORDED VOTE", 'total': {'yes': 12, 'present':
2, 'not_voting': 1}},
{'vote_type': "3/5", 'total': {'yes': 50, 'no': 14, 'present':
0, 'not_voting': 0}},
{'vote_type': "YEA-AND-NAY", 'total': {'yes': 25, 'no': 3, 'pres
ent': 3, 'not_voting': 0}} ]
inspect_data(filter_votes(V))
print(len(filter_votes(votes)))
[
{
"vote_type": "1/2",
"total": {
"yes": 5,
"no": 8,
"present": 0,
"not_voting": 2
}
},
{
"vote_type": "YEA-AND-NAY",
"total": {
"yes": 25,
"no": 3,
"present": 3,
"not_voting": 0
}
}
]
22178
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
7/41
In [6]:
# Test cell: ex0__filter_votes (2 points)
### BEGIN HIDDEN TESTS
def
ex0__gen_soln(fn="votes_subset.json", overwrite=
False
):
from
testing_tools
import
file_exists
if
file_exists(fn)
and
not
overwrite:
print(f"'
{fn}
' exists; skipping ...")
else
:
print(f"Generating '
{fn}
' ...")
V = load_json("votes.json")
V_out = filter_votes(V)
# Assume it works
save_json(V_out, fn)
ex0__gen_soln()
### END HIDDEN TESTS
from
testing_tools
import
ex0__check
print("Testing...")
for
trial
in
range(10):
ex0__check(filter_votes)
print("
\n
(Passed.)")
Precomputed filtered vote results.
In case Exercise 0 does not pass, we've precomputed the filtered subset of
votes
we'll need in the remainder of the problem. Whether or not you passed, please run the following cell now
to load this result, which will be stored in the variable,
votes_subset
.
In [7]:
votes_subset = load_json("votes_subset.json")
print(len(votes_subset))
Observation 1-A: A
passing
vote.
Recall the first vote result from above, which is present in
votes_subset
as
votes_subset[0]
. Here is how to interpret it.
'votes_subset.json' exists; skipping ...
Testing...
(Passed.)
'./resource/asnlib/publicdata/votes_subset.json': 22178
22178
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
8/41
In [8]:
inspect_data(votes_subset[0])
{
"congress": 106,
"chamber": "Senate",
"session": 1,
"roll_call": 374,
"source": "https://www.senate.gov/legislative/LIS/roll_call_votes/
vote1061/vote_106_1_00374.xml",
"url": "https://www.senate.gov/legislative/LIS/roll_call_lists/rol
l_call_vote_cfm.cfm?congress=106&session=1&vote=00374",
"vote_uri": "https://api.propublica.org/congress/v1/106/senate/ses
sions/1/votes/374.json",
"bill": {
"bill_id": "h.r.3194-106",
"number": "H.R..3194",
"sponsor_id": null,
"api_uri": null,
"title": null,
"latest_action": null
},
"question": "On the Conference Report",
"question_text": "",
"description": "H.R.3194 Conference report; Consolidated Appropria
tions Act, 2000",
"vote_type": "1/2",
"date": "1999-11-19",
"time": "17:45:00",
"result": "Agreed to",
"democratic": {
"yes": 32,
"no": 12,
"present": 0,
"not_voting": 1,
"majority_position": "Yes"
},
"republican": {
"yes": 42,
"no": 12,
"present": 0,
"not_voting": 1,
"majority_position": "Yes"
},
"independent": {
"yes": 0,
"no": 0,
"present": 0,
"not_voting": 0
},
"total": {
"yes": 74,
"no": 24,
"present": 0,
"not_voting": 2
}
}
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
9/41
It concerns a vote on November 19, 1999 (
"date": "1999-11-19"
). There were a total of 74 "yes" votes, 24
"no" votes, and 2 non-votes (abstentions or absences). Since there was a simple majority of "yes" votes---
meaning strictly more "yes" votes than "no" votes---the result is considered to be
passing
.
Of the "yes" votes, 32 were cast by Democrats and 42 by Republicans; of the "no" votes, 12 were by
Democrats and 12 by Republicans.
Observation 1-B: A
failing
vote.
Let's take a look at a vote with a different result,
votes_subset[8]
:
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
10/41
In [9]:
inspect_data(votes_subset[8])
{
"congress": 106,
"chamber": "House",
"session": 1,
"roll_call": 609,
"source": "http://clerk.house.gov/evs/1999/roll609.xml",
"url": "http://clerk.house.gov/evs/1999/roll609.xml",
"vote_uri": "https://api.propublica.org/congress/v1/106/house/sess
ions/1/votes/609.json",
"bill": {
"bill_id": "hr3194-106",
"number": "H.R.3194",
"sponsor_id": "I000047",
"api_uri": "https://api.propublica.org/congress/v1/106/bills/h
r3194.json",
"title": "Making consolidated appropriations for the fiscal ye
ar ending September 30, 2000, and for other purposes.",
"latest_action": "Became Public Law No: 106-113"
},
"question": "On Motion to Recommit Conference Report",
"question_text": "",
"description": "District of Columbia Appropriations Act, 2000",
"vote_type": "YEA-AND-NAY",
"date": "1999-11-18",
"time": "17:25:00",
"result": "Failed",
"democratic": {
"yes": 207,
"no": 2,
"present": 0,
"not_voting": 3,
"majority_position": "Yes"
},
"republican": {
"yes": 4,
"no": 217,
"present": 0,
"not_voting": 1,
"majority_position": "No"
},
"independent": {
"yes": 1,
"no": 0,
"present": 0,
"not_voting": 0
},
"total": {
"yes": 212,
"no": 219,
"present": 0,
"not_voting": 4
}
}
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
11/41
This vote took place on November 18, 1999. There were a total of 207+2+0+3 = 212 votes by Democrats and
4+217+0+1 = 222 votes by Republicans. The measure did
not
pass: there were more "no" votes (219) than
"yes" votes (212). Of the 219 "no" votes, 217 were cast by Republicans and 2 by Democrats.
Exercise 1
(2 points). Suppose you are given a
single
voting result,
v
(e.g.,
v == votes_subset[0]
or
v ==
votes_subset[8]
). Complete the function
is_passing(v)
so that it returns
True
if the vote "passed" and
False
otherwise.
To determine if a vote is passing or not, check whether the number of
"yes"
votes associated with the
"total"
key is
strictly greater than
the number of
"no"
votes.
Note:
The test cell does not use real vote results but rather randomly generated synthetic ones.
Your implementation should not depend on the presence of any specific keys other than the
ones mentioned in the statement of this exercise.
In [10]:
def
is_passing(v):
### BEGIN SOLUTION
return
v['total']['yes'] > v['total']['no']
### END SOLUTION
In [11]:
# Demo cell
print(is_passing(votes_subset[0]))
# Should return `True`
print(is_passing(votes_subset[8]))
# Should return `False`
In [12]:
# Another demo cell
num_passing = sum([is_passing(v)
for
v
in
votes_subset])
print(f"Of {len(votes_subset)} vote results,
{num_passing}
passed.")
True
False
Of 22178 vote results, 14646 passed.
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
12/41
In [13]:
# Test cell: ex1__is_passing (2 points)
### BEGIN HIDDEN TESTS
def
ex1__gen_soln(fn="votes_pf.json", overwrite=
False
):
from
testing_tools
import
file_exists
if
file_exists(fn)
and
not
overwrite:
print(f"'
{fn}
' exists; skipping ...")
else
:
print(f"Generating '
{fn}
' ...")
V = load_json("votes_subset.json")
V_out = []
for
v
in
V:
v_pf = v.copy()
v_pf["passed"] = is_passing(v_pf)
# assume it works
V_out.append(v_pf)
save_json(V_out, fn)
ex1__gen_soln()
### END HIDDEN TESTS
from
testing_tools
import
ex1__check
print("Testing...")
for
trial
in
range(1000):
ex1__check(is_passing)
print("
\n
(Passed.)")
Passing and failing votes.
In case your code for Exercise 1 does not pass the test cell, we've precomputed a
list of vote results annotated with the result. Whether or not you passed, please run the following code cell,
which produces a list of vote results named
votes_pf
, where
votes_pf["passed"]
is
True
if the outcome
is a "pass," and
False
otherwise.
In [14]:
votes_pf = load_json('votes_pf.json')
num_passed = sum([1
for
v
in
votes_pf
if
v["passed"]])
print(f"
{num_passed}
vote results were passing, {len(votes_pf) - num_p
assed} were failing.")
'votes_pf.json' exists; skipping ...
Testing...
(Passed.)
'./resource/asnlib/publicdata/votes_pf.json': 22178
14646 vote results were passing, 7532 were failing.
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
13/41
Definition: The partisan "vote" gap.
Given a voting result, let's define a measure of how well the Democrats
and Republicans agree.
Suppose a bill has some outcome, either "pass" or "fail." Let
be the proportion of Democrats who voted for
that outcome, and let
be the proportion of Republicans who voted for that outcome. Then the
partisan vote
gap
for that bill is the absolute difference between
and , or
. The more Democrats and Republicans
agree, the closer this value is to zero. But when they disagree strongly, this value could be
.
For example, recall that in the first example,
votes_subset[0]
, the bill passed with 74 "yes" votes, 32 from
Democrats and 42 from Republicans. Since there were 45 Democrats (32 yes, 12 no, and 1 non-voting), then
. And since there were 55 Republicans (42 yes, 12 no, and 1 non-voting), then
.
Thus, the partisan vote gap is
.
In the second example,
votes_subset[8]
, recall that the vote failed with 219 "no" votes, 217 by Republicans
out of 222 total, and 2 by Democrats out of 212 total. Thus,
.
Comparing the two cases, the first is an example of reasonable agreement, whereas the second shows strong
disagreement.
Exercise 2
(2 points). Given one voting result,
v
, complete the function
calc_partisan_vote_gap(v)
so
that it returns the partisan voting gap as defined above. Assume that
v["passed"]
is
True
if the vote was a
passing vote (majority "yes"), or
False
otherwise (majority "no").
Note 0:
To determine the total number of Democrats or Republicans, add together all of their
"yes"
,
"no"
,
"present"
, and
"not_voting"
values using the appropriate party's object in
v
.
Note 1:
If a vote result has
no
Democrats or Republicans, then use
or
, respectively.
This scenario can happen if the sum of Democratic or Republican
"yes"
,
"no"
,
"present"
,
and
"not_voting"
values is 0.
Note 2:
You do not need to round your results. The test cell accounts for possible rounding
errors when comparing your computed result against the expected one.
Note 3:
The test cell does not use real vote results, but rather randomly generated synthetic
ones. Your code should only depend on the presence of the relevant keys, namely, the party
votes (
"democratic"
and
"republican"
) and
"passed"
.
d
r
d
r
d − r
1
d =
≈ 0.711
32
45
r =
≈ 0.764
42
55
d − r =
−
≈ 0.0525
∣
∣
32
45
42
55
∣
∣
d − r =
−
≈ 0.968
∣
∣
2
212
217
222
∣
∣
d = 0
r = 0
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
14/41
In [15]:
def
calc_partisan_vote_gap(v):
assert
isinstance(v, dict)
assert
"passed"
in
v
and
"democratic"
in
v
and
"republican"
in
v
### BEGIN SOLUTION
def
party_total(k):
return
v[k]["yes"] + v[k]["no"] + v[k]["present"] + v[k]["not_
voting"]
total_d = party_total("democratic")
total_r = party_total("republican")
majority_key = "yes"
if
v["passed"]
else
"no"
d = v["democratic"][majority_key] / total_d
if
total_d > 0
else
0
r = v["republican"][majority_key] / total_r
if
total_r > 0
else
0
return
abs(d - r)
### END SOLUTION
In [16]:
# Demo cell to help you debug
print(calc_partisan_vote_gap(votes_pf[0]))
# should be about 0.0525
print(calc_partisan_vote_gap(votes_pf[8]))
# ~ 0.968
In [17]:
# Test cell: ex2__calc_partisan_vote_gap (2 points)
### BEGIN HIDDEN TESTS
def
ex2__gen_soln(fn="votes_gap.json", overwrite=
False
):
from
testing_tools
import
file_exists
if
file_exists(fn)
and
not
overwrite:
print(f"'
{fn}
' exists; skipping ...")
else
:
print(f"Generating '
{fn}
' ...")
V = load_json("votes_pf.json")
for
v
in
V:
v["gap"] = calc_partisan_vote_gap(v)
save_json(V, fn)
ex2__gen_soln()
### END HIDDEN TESTS
from
testing_tools
import
ex2__check
print("Testing...")
for
trial
in
range(2500):
ex2__check(calc_partisan_vote_gap)
print("
\n
(Passed.)")
0.05252525252525253
0.9680435152133265
'votes_gap.json' exists; skipping ...
Testing...
(Passed.)
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
15/41
Precomputed partisan vote gaps.
In case your Exercise 2 did not pass the test cell, we've precomputed a list
of vote results with their partisan vote gaps. Whether or not you passed, please run the following cell to load this
result, which will be stored in the variable,
votes_gap
. Each entry
v
of
votes_gap
will have a key,
v["gap"]
,
that holds the vote gap.
In [18]:
votes_gap = load_json("votes_gap.json")
from
statistics
import
mean
overall_gap = mean([v["gap"]
for
v
in
votes_gap])
print(f"Average overall vote gap:
{overall_gap}
")
In [19]:
type(votes_gap)
Exercise 3
(2 points): We are now ready to calculate the voting gap over time. Complete the function,
tally_gaps(votes_gap)
, below, where:
the input
votes_gap
is a list of vote results augmented with the
"gap"
key as defined in Exercise 2;
the function returns a list of tuples holding the year-by-year average vote gaps, as follows.
For example, suppose you run
gaps_over_time = tally_gaps(votes_gap)
is the output. Then,
gaps_over_time
is a list.
Each element is a pair,
(yyyy, g)
, where
yyyy
is the year represented as an
integer
(
int
) and
g
is
the
average
vote gap across all votes that took place in that year.
To determine the year of a vote, recall that each vote result has a
"date"
field. You may assume each vote
result
v
in
votes_gap
has a key,
v["gap"]
holding its vote gap.
Note:
The test cell does not use real vote results, but rather randomly generated synthetic ones.
Your solution should not depend on any particular keys in a vote result other than
"date"
and
"gap"
.
'./resource/asnlib/publicdata/votes_gap.json': 22178
Average overall vote gap: 0.5878119584149253
Out[19]:
list
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
16/41
In [20]:
def
tally_gaps(votes_gap):
### BEGIN SOLUTION
from
collections
import
defaultdict
years = set()
votes_per_year = defaultdict(int)
gaps_per_year = defaultdict(float)
for
v
in
votes_gap:
yyyy = int(v["date"][:4])
years.add(yyyy)
votes_per_year[yyyy] += 1
gaps_per_year[yyyy] += v["gap"]
gaps_over_time = [(yyyy, gaps_per_year[yyyy] / votes_per_year[yyy
y])
for
yyyy
in
years]
return
gaps_over_time
### END SOLUTION
In [21]:
# Demo cell you can use for debugging
gaps_over_time = tally_gaps(votes_gap)
for
yyyy, g_avg
in
sorted(gaps_over_time, key=
lambda
x: x[0]):
print(f"
{yyyy}
:
{g_avg:.3f}
")
1991: 0.412
1992: 0.445
1993: 0.535
1994: 0.474
1995: 0.581
1996: 0.495
1997: 0.450
1998: 0.489
1999: 0.484
2000: 0.452
2001: 0.465
2002: 0.444
2003: 0.578
2004: 0.539
2005: 0.552
2006: 0.557
2007: 0.632
2008: 0.646
2009: 0.633
2010: 0.637
2011: 0.674
2012: 0.683
2013: 0.691
2014: 0.710
2015: 0.730
2016: 0.745
2017: 0.771
2018: 0.638
2019: 0.684
2020: 0.759
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
17/41
In [22]:
# Test cell: ex3__tally_gaps (2 points)
from
testing_tools
import
ex3__check
print("Testing...")
for
trial
in
range(100):
ex3__check(tally_gaps)
print("
\n
(Passed.)")
Gaps over time.
If your demo worked correctly, you should have seen a steady trend in which the vote gap
increases over time, starting at around 0.41 in 1991 and increasing to 0.76 in 2020. That is one quantitative
indicator of growing partisanship in the US Congress.
Part 1: Finding "compatible" lawmakers from opposing parties
Are there any pairs of lawmakers from opposing parties---that is, one Democrat and one Republican---who tend
to vote similarly to one another? Perhaps such pairs can help bridge the divide between the two parties.
To help find such a pair, here is one final dataset, stored in the list,
vote_positions
. It consists of vote results
from the last two years (2019-2020) along with
how each lawmaker voted
(yes or no). There are 278 such vote
results available, which we can confirm by printing the length of the
vote_positions
list:
In [23]:
print(len(vote_positions))
Let's inspect one of these vote results,
vote_positions[0]
:
Testing...
(Passed.)
278
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
18/41
In [24]:
inspect_data(vote_positions[0])
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
19/41
{
"congress": 116,
"session": 2,
"chamber": "Senate",
"roll_call": 130,
"source": "https://www.senate.gov/legislative/LIS/roll_call_votes/
vote1162/vote_116_2_00130.xml",
"url": "https://www.senate.gov/legislative/LIS/roll_call_lists/rol
l_call_vote_cfm.cfm?congress=116&session=2&vote=00130",
"bill": {},
"amendment": {},
"nomination": {
"nomination_id": "PN1726-116",
"number": "PN1726",
"name": "Russell",
"agency": "Executive Office of the President"
},
"question": "On the Cloture Motion",
"question_text": "On the Cloture Motion PN1726",
"description": "Russell Vought, of Virginia, to be Director of the
Office of Management and Budget",
"vote_type": "1/2",
"date": "2020-07-02",
"time": "13:33:00",
"result": "Cloture Motion Agreed to",
"tie_breaker": "",
"tie_breaker_vote": "",
"document_number": "1726",
"document_title": "Russell Vought, of Virginia, to be Director of
the Office of Management and Budget",
"democratic": {
"yes": 0,
"no": 42,
"present": 0,
"not_voting": 3,
"majority_position": "No"
},
"republican": {
"yes": 47,
"no": 0,
"present": 0,
"not_voting": 6,
"majority_position": "Yes"
},
"independent": {
"yes": 0,
"no": 2,
"present": 0,
"not_voting": 0
},
"total": {
"yes": 47,
"no": 44,
"present": 0,
"not_voting": 9
},
"positions": [
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
20/41
{
"member_id": "A000360",
"name": "Lamar Alexander",
"party": "R",
"state": "TN",
"vote_position": "Yes",
"dw_nominate": 0.324
},
{
"member_id": "B001230",
"name": "Tammy Baldwin",
"party": "D",
"state": "WI",
"vote_position": "No",
"dw_nominate": -0.494
},
{
"member_id": "B001261",
"name": "John Barrasso",
"party": "R",
"state": "WY",
"vote_position": "Yes",
"dw_nominate": 0.54
},
{
"member_id": "B001267",
"name": "Michael Bennet",
"party": "D",
"state": "CO",
"vote_position": "No",
"dw_nominate": -0.223
},
{
"member_id": "B001243",
"name": "Marsha Blackburn",
"party": "R",
"state": "TN",
"vote_position": "Yes",
"dw_nominate": 0.618
},
{
"member_id": "B001277",
"name": "Richard Blumenthal",
"party": "D",
"state": "CT",
"vote_position": "No",
"dw_nominate": -0.431
},
{
"member_id": "B000575",
"name": "Roy Blunt",
"party": "R",
"state": "MO",
"vote_position": "Yes",
"dw_nominate": 0.426
},
{
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
21/41
"member_id": "B001288",
"name": "Cory Booker",
"party": "D",
"state": "NJ",
"vote_position": "No",
"dw_nominate": -0.604
},
{
"member_id": "B001236",
"name": "John Boozman",
"party": "R",
"state": "AR",
"vote_position": "Yes",
"dw_nominate": 0.399
},
{
"member_id": "B001310",
"name": "Mike Braun",
"party": "R",
"state": "IN",
"vote_position": "Yes",
"dw_nominate": null
},
{
"member_id": "B000944",
"name": "Sherrod Brown",
"party": "D",
"state": "OH",
"vote_position": "No",
"dw_nominate": -0.43
},
{
"member_id": "B001135",
"name": "Richard M. Burr",
"party": "R",
"state": "NC",
"vote_position": "Not Voting",
"dw_nominate": 0.45
},
{
"member_id": "C000127",
"name": "Maria Cantwell",
"party": "D",
"state": "WA",
"vote_position": "No",
"dw_nominate": -0.303
},
{
"member_id": "C001047",
"name": "Shelley Moore Capito",
"party": "R",
"state": "WV",
"vote_position": "Yes",
"dw_nominate": 0.263
},
{
"member_id": "C000141",
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
22/41
"name": "Benjamin L. Cardin",
"party": "D",
"state": "MD",
"vote_position": "No",
"dw_nominate": -0.321
},
{
"member_id": "C000174",
"name": "Thomas R. Carper",
"party": "D",
"state": "DE",
"vote_position": "No",
"dw_nominate": -0.175
},
{
"member_id": "C001070",
"name": "Bob Casey",
"party": "D",
"state": "PA",
"vote_position": "No",
"dw_nominate": -0.312
},
{
"member_id": "C001075",
"name": "Bill Cassidy",
"party": "R",
"state": "LA",
"vote_position": "Yes",
"dw_nominate": 0.457
},
{
"member_id": "C001035",
"name": "Susan Collins",
"party": "R",
"state": "ME",
"vote_position": "Yes",
"dw_nominate": 0.112
},
{
"member_id": "C001088",
"name": "Christopher A. Coons",
"party": "D",
"state": "DE",
"vote_position": "No",
"dw_nominate": -0.226
},
{
"member_id": "C001056",
"name": "John Cornyn",
"party": "R",
"state": "TX",
"vote_position": "Yes",
"dw_nominate": 0.494
},
{
"member_id": "C001113",
"name": "Catherine Cortez Masto",
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
23/41
"party": "D",
"state": "NV",
"vote_position": "No",
"dw_nominate": -0.371
},
{
"member_id": "C001095",
"name": "Tom Cotton",
"party": "R",
"state": "AR",
"vote_position": "Yes",
"dw_nominate": 0.57
},
{
"member_id": "C001096",
"name": "Kevin Cramer",
"party": "R",
"state": "ND",
"vote_position": "Yes",
"dw_nominate": 0.387
},
{
"member_id": "C000880",
"name": "Michael D. Crapo",
"party": "R",
"state": "ID",
"vote_position": "Yes",
"dw_nominate": 0.511
},
{
"member_id": "C001098",
"name": "Ted Cruz",
"party": "R",
"state": "TX",
"vote_position": "Yes",
"dw_nominate": 0.818
},
{
"member_id": "D000618",
"name": "Steve Daines",
"party": "R",
"state": "MT",
"vote_position": "Yes",
"dw_nominate": 0.551
},
{
"member_id": "D000622",
"name": "Tammy Duckworth",
"party": "D",
"state": "IL",
"vote_position": "No",
"dw_nominate": -0.332
},
{
"member_id": "D000563",
"name": "Richard J. Durbin",
"party": "D",
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
24/41
"state": "IL",
"vote_position": "No",
"dw_nominate": -0.35
},
{
"member_id": "E000285",
"name": "Michael B. Enzi",
"party": "R",
"state": "WY",
"vote_position": "Not Voting",
"dw_nominate": 0.545
},
{
"member_id": "E000295",
"name": "Joni Ernst",
"party": "R",
"state": "IA",
"vote_position": "Yes",
"dw_nominate": 0.529
},
{
"member_id": "F000062",
"name": "Dianne Feinstein",
"party": "D",
"state": "CA",
"vote_position": "No",
"dw_nominate": -0.267
},
{
"member_id": "F000463",
"name": "Deb Fischer",
"party": "R",
"state": "NE",
"vote_position": "Yes",
"dw_nominate": 0.473
},
{
"member_id": "G000562",
"name": "Cory Gardner",
"party": "R",
"state": "CO",
"vote_position": "Yes",
"dw_nominate": 0.443
},
{
"member_id": "G000555",
"name": "Kirsten E. Gillibrand",
"party": "D",
"state": "NY",
"vote_position": "No",
"dw_nominate": -0.474
},
{
"member_id": "G000359",
"name": "Lindsey Graham",
"party": "R",
"state": "SC",
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
25/41
"vote_position": "Yes",
"dw_nominate": 0.406
},
{
"member_id": "G000386",
"name": "Charles E. Grassley",
"party": "R",
"state": "IA",
"vote_position": "Yes",
"dw_nominate": 0.346
},
{
"member_id": "H001075",
"name": "Kamala Harris",
"party": "D",
"state": "CA",
"vote_position": "No",
"dw_nominate": -0.709
},
{
"member_id": "H001076",
"name": "Margaret Hassan",
"party": "D",
"state": "NH",
"vote_position": "No",
"dw_nominate": -0.24
},
{
"member_id": "H001089",
"name": "Joshua Hawley",
"party": "R",
"state": "MO",
"vote_position": "Yes",
"dw_nominate": null
},
{
"member_id": "H001046",
"name": "Martin Heinrich",
"party": "D",
"state": "NM",
"vote_position": "No",
"dw_nominate": -0.325
},
{
"member_id": "H001042",
"name": "Mazie K. Hirono",
"party": "D",
"state": "HI",
"vote_position": "No",
"dw_nominate": -0.511
},
{
"member_id": "H001061",
"name": "John Hoeven",
"party": "R",
"state": "ND",
"vote_position": "Yes",
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
26/41
"dw_nominate": 0.342
},
{
"member_id": "H001079",
"name": "Cindy Hyde-Smith",
"party": "R",
"state": "MS",
"vote_position": "Not Voting",
"dw_nominate": 0.373
},
{
"member_id": "I000024",
"name": "James M. Inhofe",
"party": "R",
"state": "OK",
"vote_position": "Yes",
"dw_nominate": 0.556
},
{
"member_id": "J000293",
"name": "Ron Johnson",
"party": "R",
"state": "WI",
"vote_position": "Yes",
"dw_nominate": 0.605
},
{
"member_id": "J000300",
"name": "Doug Jones",
"party": "D",
"state": "AL",
"vote_position": "No",
"dw_nominate": -0.086
},
{
"member_id": "K000384",
"name": "Tim Kaine",
"party": "D",
"state": "VA",
"vote_position": "No",
"dw_nominate": -0.241
},
{
"member_id": "K000393",
"name": "John Kennedy",
"party": "R",
"state": "LA",
"vote_position": "Yes",
"dw_nominate": 0.592
},
{
"member_id": "K000383",
"name": "Angus King",
"party": "ID",
"state": "ME",
"vote_position": "No",
"dw_nominate": -0.154
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
27/41
},
{
"member_id": "K000367",
"name": "Amy Klobuchar",
"party": "D",
"state": "MN",
"vote_position": "No",
"dw_nominate": -0.28
},
{
"member_id": "L000575",
"name": "James Lankford",
"party": "R",
"state": "OK",
"vote_position": "Yes",
"dw_nominate": 0.589
},
{
"member_id": "L000174",
"name": "Patrick J. Leahy",
"party": "D",
"state": "VT",
"vote_position": "No",
"dw_nominate": -0.361
},
{
"member_id": "L000577",
"name": "Mike Lee",
"party": "R",
"state": "UT",
"vote_position": "Yes",
"dw_nominate": 0.916
},
{
"member_id": "L000594",
"name": "Kelly Loeffler",
"party": "R",
"state": "GA",
"vote_position": "Yes",
"dw_nominate": null
},
{
"member_id": "M001183",
"name": "Joe Manchin III",
"party": "D",
"state": "WV",
"vote_position": "No",
"dw_nominate": -0.056
},
{
"member_id": "M000133",
"name": "Edward J. Markey",
"party": "D",
"state": "MA",
"vote_position": "Not Voting",
"dw_nominate": -0.511
},
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
28/41
{
"member_id": "M000355",
"name": "Mitch McConnell",
"party": "R",
"state": "KY",
"vote_position": "Yes",
"dw_nominate": 0.402
},
{
"member_id": "M001197",
"name": "Martha McSally",
"party": "R",
"state": "AZ",
"vote_position": "Not Voting",
"dw_nominate": 0.345
},
{
"member_id": "M000639",
"name": "Robert Menendez",
"party": "D",
"state": "NJ",
"vote_position": "No",
"dw_nominate": -0.366
},
{
"member_id": "M001176",
"name": "Jeff Merkley",
"party": "D",
"state": "OR",
"vote_position": "No",
"dw_nominate": -0.444
},
{
"member_id": "M000934",
"name": "Jerry Moran",
"party": "R",
"state": "KS",
"vote_position": "Yes",
"dw_nominate": 0.414
},
{
"member_id": "M001153",
"name": "Lisa Murkowski",
"party": "R",
"state": "AK",
"vote_position": "Not Voting",
"dw_nominate": 0.211
},
{
"member_id": "M001169",
"name": "Christopher S. Murphy",
"party": "D",
"state": "CT",
"vote_position": "No",
"dw_nominate": -0.272
},
{
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
29/41
"member_id": "M001111",
"name": "Patty Murray",
"party": "D",
"state": "WA",
"vote_position": "Not Voting",
"dw_nominate": -0.351
},
{
"member_id": "P000603",
"name": "Rand Paul",
"party": "R",
"state": "KY",
"vote_position": "Yes",
"dw_nominate": 0.878
},
{
"member_id": "P000612",
"name": "David Perdue",
"party": "R",
"state": "GA",
"vote_position": "Yes",
"dw_nominate": 0.565
},
{
"member_id": "P000595",
"name": "Gary Peters",
"party": "D",
"state": "MI",
"vote_position": "No",
"dw_nominate": -0.245
},
{
"member_id": "P000449",
"name": "Rob Portman",
"party": "R",
"state": "OH",
"vote_position": "Yes",
"dw_nominate": 0.373
},
{
"member_id": "R000122",
"name": "Jack Reed",
"party": "D",
"state": "RI",
"vote_position": "No",
"dw_nominate": -0.369
},
{
"member_id": "R000584",
"name": "Jim Risch",
"party": "R",
"state": "ID",
"vote_position": "Yes",
"dw_nominate": 0.631
},
{
"member_id": "R000307",
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
30/41
"name": "Pat Roberts",
"party": "R",
"state": "KS",
"vote_position": "Yes",
"dw_nominate": 0.413
},
{
"member_id": "R000615",
"name": "Mitt Romney",
"party": "R",
"state": "UT",
"vote_position": "Yes",
"dw_nominate": null
},
{
"member_id": "R000608",
"name": "Jacky Rosen",
"party": "D",
"state": "NV",
"vote_position": "No",
"dw_nominate": -0.28
},
{
"member_id": "R000605",
"name": "Mike Rounds",
"party": "R",
"state": "SD",
"vote_position": "Yes",
"dw_nominate": 0.404
},
{
"member_id": "R000595",
"name": "Marco Rubio",
"party": "R",
"state": "FL",
"vote_position": "Yes",
"dw_nominate": 0.568
},
{
"member_id": "S000033",
"name": "Bernard Sanders",
"party": "ID",
"state": "VT",
"vote_position": "No",
"dw_nominate": -0.527
},
{
"member_id": "S001197",
"name": "Ben Sasse",
"party": "R",
"state": "NE",
"vote_position": "Yes",
"dw_nominate": 0.794
},
{
"member_id": "S001194",
"name": "Brian Schatz",
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
31/41
"party": "D",
"state": "HI",
"vote_position": "No",
"dw_nominate": -0.448
},
{
"member_id": "S000148",
"name": "Charles E. Schumer",
"party": "D",
"state": "NY",
"vote_position": "No",
"dw_nominate": -0.358
},
{
"member_id": "S001217",
"name": "Rick Scott",
"party": "R",
"state": "FL",
"vote_position": "Yes",
"dw_nominate": null
},
{
"member_id": "S001184",
"name": "Tim Scott",
"party": "R",
"state": "SC",
"vote_position": "Yes",
"dw_nominate": 0.637
},
{
"member_id": "S001181",
"name": "Jeanne Shaheen",
"party": "D",
"state": "NH",
"vote_position": "No",
"dw_nominate": -0.238
},
{
"member_id": "S000320",
"name": "Richard C. Shelby",
"party": "R",
"state": "AL",
"vote_position": "Yes",
"dw_nominate": 0.429
},
{
"member_id": "S001191",
"name": "Kyrsten Sinema",
"party": "D",
"state": "AZ",
"vote_position": "No",
"dw_nominate": -0.102
},
{
"member_id": "S001203",
"name": "Tina Smith",
"party": "D",
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
32/41
"state": "MN",
"vote_position": "No",
"dw_nominate": -0.392
},
{
"member_id": "S000770",
"name": "Debbie Stabenow",
"party": "D",
"state": "MI",
"vote_position": "No",
"dw_nominate": -0.342
},
{
"member_id": "S001198",
"name": "Dan Sullivan",
"party": "R",
"state": "AK",
"vote_position": "Yes",
"dw_nominate": 0.483
},
{
"member_id": "T000464",
"name": "Jon Tester",
"party": "D",
"state": "MT",
"vote_position": "No",
"dw_nominate": -0.217
},
{
"member_id": "T000250",
"name": "John Thune",
"party": "R",
"state": "SD",
"vote_position": "Yes",
"dw_nominate": 0.41
},
{
"member_id": "T000476",
"name": "Thom Tillis",
"party": "R",
"state": "NC",
"vote_position": "Not Voting",
"dw_nominate": 0.429
},
{
"member_id": "T000461",
"name": "Patrick J. Toomey",
"party": "R",
"state": "PA",
"vote_position": "Yes",
"dw_nominate": 0.648
},
{
"member_id": "U000039",
"name": "Tom Udall",
"party": "D",
"state": "NM",
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
33/41
"vote_position": "Not Voting",
"dw_nominate": -0.453
},
{
"member_id": "V000128",
"name": "Chris Van Hollen",
"party": "D",
"state": "MD",
"vote_position": "No",
"dw_nominate": -0.39
},
{
"member_id": "W000805",
"name": "Mark Warner",
"party": "D",
"state": "VA",
"vote_position": "No",
"dw_nominate": -0.201
},
{
"member_id": "W000817",
"name": "Elizabeth Warren",
"party": "D",
"state": "MA",
"vote_position": "No",
"dw_nominate": -0.77
},
{
"member_id": "W000802",
"name": "Sheldon Whitehouse",
"party": "D",
"state": "RI",
"vote_position": "No",
"dw_nominate": -0.358
},
{
"member_id": "W000437",
"name": "Roger Wicker",
"party": "R",
"state": "MS",
"vote_position": "Yes",
"dw_nominate": 0.376
},
{
"member_id": "W000779",
"name": "Ron Wyden",
"party": "D",
"state": "OR",
"vote_position": "No",
"dw_nominate": -0.329
},
{
"member_id": "Y000064",
"name": "Todd Young",
"party": "R",
"state": "IN",
"vote_position": "Yes",
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
34/41
It is a vote result with some more keys. The most important new key is
'positions'
. Its value is a list of
everyone and what vote they cast. For example, for the vote result stored in
vote_positions[0]
, above, you
can verify that
"Lamar Alexander"
is a Republican who voted yes (
'name'
:
"Lamar Alexander"
,
'party':
"R"
,
'vote_position': "Yes"
); and
"Tammy Baldwin"
is a Democrat who voted no (
'name'
:
"Tammy Baldwin"
,
'party': "D"
,
'vote_position': "No"
).
Note:
The
'vote_position'
key can take on a third value, which is
"Not Voting"
. In this
example, that is the case for
"Cindy Hyde-Smith"
.
Exercise 4
(2 points). Complete the function,
get_parties(vps)
, below. It should take as input a vote results
list
vps
similar to
vote_positions
above. It should return a
dictionary,
where each key is the name of a
lawmaker and the corresponding value is that person's party, taken from the
'party'
key.
For example, suppose you run
parties = get_parties(vote_positions)
. Then,
parties["Lamar Alexander"] == "R"
parties["Tammy Baldwin"] == "D"
parties["Angus King"] == "ID"
Note 0:
You may assume that the party of a member does not change and that member names
are unique.
Note 1:
You may assume there are only three possible party values in the data:
"R"
for
Republican,
"D"
for Democrat, and
"ID"
for Independent.
Note 2:
Do
not
assume that every name appears in every vote result. Therefore, to ensure you
get all the names, your solution needs to sweep all vote results. The test code may check
whether you've done so.
Note 3:
The test cell does not use real data; rather, it uses randomly generated synthetic data.
Your solution should not depend on the existence of any keys other than
'positions'
and, for
each element of positions,
'name'
and
'party'
.
"dw_nominate": 0.474
}
]
}
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
35/41
In [25]:
def
get_parties(vps):
### BEGIN SOLUTION
parties = {}
for
p
in
vps:
for
v
in
p['positions']:
name = v['name']
party = v['party']
parties[name] = party
return
parties
### END SOLUTION
In [26]:
# Demo cell you can use for debugging
parties_demo = get_parties(vote_positions)
print(parties_demo["Lamar Alexander"])
# "R"
print(parties_demo["Tammy Baldwin"])
# "D"
print(parties_demo["Angus King"])
# "ID"
In [27]:
# Test cell: ex4__get_parties (2 points)
### BEGIN HIDDEN TESTS
def
ex4__gen_soln(fn="parties.pickle", overwrite=
False
):
from
testing_tools
import
file_exists
if
file_exists(fn)
and
not
overwrite:
print(f"'
{fn}
' exists; skipping ...")
else
:
print(f"Generating '
{fn}
' ...")
P = [p
for
p
in
load_json("positions.json")
if
p['positions']]
R = get_parties(P)
save_pickle(R, fn)
ex4__gen_soln()
### END HIDDEN TESTS
from
testing_tools
import
ex4__check
print("Testing...")
for
trial
in
range(1000):
ex4__check(get_parties)
print("
\n
(Passed.)")
Precomputed parties.
Whether your solution to the previous exercise passes or not, we have precomputed the
party affiliations of the members for you. Run the following code cell, which defines a dictionary named
parties
holding these affiliations. You'll need
parties
in a subsequent exercise.
R
D
ID
'parties.pickle' exists; skipping ...
Testing...
(Passed.)
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
36/41
In [28]:
parties = load_pickle('parties.pickle')
for
member
in
["Lamar Alexander", "Tammy Baldwin", "Angus King"]:
print(member, "=>", parties[member])
Voting vectors.
To help us compare voting records between lawmakers, let's construct their
voting vectors
.
Each lawmaker will be represented by one voting vector. A voting vector is a Python
list
. Each element of the list
is for a voting result and holds one of three values:
True
for a
"Yes"
vote,
False
for a
"No"
vote, and
None
for
"Not Voting"
.
For example, since there are 278 vote results in this
vote_positions
list, the length of a voting vector will be
278. Now suppose Lamar Alexander's voting vector is
x
, Tammy Baldwin's is
y
, and Cindy Hyde-Smith's is
z
.
Then for the example voting position above, we would have
x[0] == True
,
y[0] == False
, and
z[0] ==
None
.
Exercise 5
(2 points). Complete the function,
build_voting_vectors(vps)
. It should take as input a vote
results list
vps
like
vote_positions
above. It should return a
dictionary
where each key is the name of a
lawmaker and the corresponding value is a voting vector. Recall that a voting vector is a Python list of
True
or
False
values.
For example, suppose you run
results = build_voting_vectors(vote_positions)
. Then, from the
example of
vote_positions[0]
, we would expect the following:
results["Lamar Alexander"][0] == True
results["Tammy Baldwin"][0] == False
results["Cindy Hyde-Smith"][0] == None
Note 0:
The test cell does not use real vote results, but rather randomly generated synthetic
ones. Your code should not assume the existence of keys other than the ones directly relevant
to this exercise's problem statement, namely,
'positions'
, and for each lawmaker's vote,
'name'
and
'vote_position'
.
Note 1:
Although the sample voting dataset has 278 vote results, each synthetic test cases
might have a different number.
Note 2:
Your code should not assume that every lawmaker voted in every vote result. See
Demo
cell 0
, below, where
"Anita Borg"
did not vote in the first vote result, and in one instance,
"Alan Turing"
is marked as
"Not Voting"
.
Lamar Alexander => R
Tammy Baldwin => D
Angus King => ID
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
37/41
In [29]:
def
build_voting_vectors(vps):
### BEGIN SOLUTION
from
collections
import
defaultdict
vote_values = {"Yes":
True
, "No":
False
}
results = defaultdict(
lambda
: [
None
] * len(vps))
for
k, p
in
enumerate(vps):
for
v
in
p['positions']:
name = v['name']
vote = v["vote_position"]
results[name][k] = vote_values.get(vote,
None
)
return
results
### END SOLUTION
In [30]:
# Demo cell 0, which you can use for debugging
# Example with three vote results and three different lawmakers:
vps_example = [{'positions': [{'name': 'Grace Hopper', 'vote_positio
n': 'Yes'},
{'name': 'Alan Turing', 'vote_position':
'No'}]},
{'positions': [{'name': 'Anita Borg', 'vote_position':
'Yes'},
{'name': 'Alan Turing', 'vote_position':
'Not Voting'},
{'name': 'Grace Hopper', 'vote_positio
n': 'No'}]},
{'positions': [{'name': 'Grace Hopper', 'vote_positio
n': 'No'},
{'name': 'Anita Borg', 'vote_position':
'Yes'},
{'name': 'Alan Turing', 'vote_position':
'Yes'}]}
]
build_voting_vectors(vps_example)
# Should print something like
#
{'Grace Hopper': [True, False, False],
#
'Alan Turing': [False, None, True],
#
'Anita Borg': [None, True, True]}
Out[30]:
defaultdict(<function __main__.build_voting_vectors.<locals>.<lambda>
()>,
{'Grace Hopper': [True, False, False],
'Alan Turing': [False, None, True],
'Anita Borg': [None, True, True]})
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
38/41
In [31]:
# Demo cell 1
results = build_voting_vectors(vote_positions)
# Lamar Alexander cast 236 "Yes" votes, 7 "No" votes, and did not vote
35 times.
# The collections.Counter object can help verify that fact from your r
esults.
Lamars_votes = results["Lamar Alexander"]
from
collections
import
Counter
Counter(Lamars_votes)
In [32]:
# Test cell: ex5__build_voting_vectors (2 points)
### BEGIN HIDDEN TESTS
def
ex5__gen_soln(fn="voting_vectors.pickle", overwrite=
False
):
from
testing_tools
import
file_exists
if
file_exists(fn)
and
not
overwrite:
print(f"'
{fn}
' exists; skipping ...")
else
:
print(f"Generating '
{fn}
' ...")
P = [p
for
p
in
load_json("positions.json")
if
p['positions']]
R = build_voting_vectors(P)
save_pickle(dict(R), fn)
ex5__gen_soln()
### END HIDDEN TESTS
from
testing_tools
import
ex5__check
for
trial
in
range(1000):
ex5__check(build_voting_vectors)
print("
\n
(Passed.)")
Precomputed voting vectors.
Whether or not your previous solution passed, we've precomputed the voting
vectors for this dataset. The following code cell loads these results into the object
voting_vectors
, which
you'll need in subsequent exercises.
In [33]:
voting_vectors = load_pickle('voting_vectors.pickle')
from
collections
import
Counter
for
example
in
["Lamar Alexander", "Tammy Baldwin"]:
example_vv = voting_vectors[example]
print(example, "==>", Counter(example_vv))
Out[31]:
Counter({True: 236, None: 35, False: 7})
'voting_vectors.pickle' exists; skipping ...
(Passed.)
Lamar Alexander ==> Counter({True: 236, None: 35, False: 7})
Tammy Baldwin ==> Counter({False: 174, True: 103, None: 1})
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
39/41
Exercise 6
(2 points). For this last exercise, complete the function
opposing_pairs(voting_vectors,
parties)
. This function takes two inputs:
voting_vectors
is the dictionary that maps each member of Congress to their voting vector
parties
is the dictonary that holds the party affiliation of each member
It should then do the following:
Consider every pair of opposing members. That is, let
(a, b)
be a pair of names, where
a
is some
Republican and
b
is some Democrat. (
a
must be a Republican and
b
a Democrat; do not flip these.)
Ignore any Independents.
Use their voting vectors to count how many times
a
and
b
cast
identical
and
non-
None
votes. That is,
if they both voted
"Yes"
or they both voted
"No"
, those are identical votes. However, if either or both
has
None
recorded for a vote, that should
not
be counted.
Denote the count between
a
and
b
by
c
. Then, the function should return a list of all tuples,
(a, b,
c)
.
For example, suppose you run the following:
P = {"alice": "R", "bob": "D", "carol": "D", "dale": "ID"}
V = {"alice": [True, True, False, True, None],
"bob": [True, False, None, True, True],
"carol": [False, False, False, None, None],
"dale": [False, None, None, False, False]}
pairs = opposing_pairs(V, P)
Then
pairs
should be the following list:
[('alice', 'bob', 2), ('alice', 'carol', 1)]
For instance, the result contains
('alice', 'bob', 2)
, since
'alice'
is a Republican,
'bob'
is a
Democrat, and they cast the same vote twice (entries 0 and 3 of their voting vectors). It also contains
('alice', 'carol', 1)
, since
'alice'
is a Republican and
'carol'
is a Democrat, and they cast the
same non-
None
votes just once.
Note:
Your function does not have to return the list with entries in the same
order
as above; any
permutation is fine, as long as it contains all valid pairs.
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
40/41
In [34]:
def
opposing_pairs(voting_vectors, parties):
### BEGIN SOLUTION
Rs = {name
for
name, party
in
parties.items()
if
party == "R"}
Ds = {name
for
name, party
in
parties.items()
if
party == "D"}
pairs = []
for
r
in
Rs:
v_r = voting_vectors[r]
for
d
in
Ds:
v_d = voting_vectors[d]
c = count_common(v_r, v_d)
pairs.append((r, d, c))
return
pairs
def
count_common(x, y):
assert
len(x) == len(y)
return
sum([(xi == yi)
for
xi, yi
in
zip(x, y)
if
(xi
is
not
None
)
and
(yi
is
not
None
)])
### END SOLUTION
In [35]:
# Demo cell
P = {"alice": "R", "bob": "D", "carol": "D", "dale": "ID"}
V = {"alice": [
True
,
True
,
False
,
True
,
None
],
"bob": [
True
,
False
,
None
,
True
,
True
],
"carol": [
False
,
False
,
False
,
None
,
None
],
"dale": [
False
,
None
,
None
,
False
,
False
]}
pairs = opposing_pairs(V, P)
pairs
In [36]:
# Test cell: ex6__opposing_pairs (2 points)
from
testing_tools
import
ex6__check
for
trial
in
range(1000):
ex6__check(opposing_pairs)
print("
\n
(Passed.)")
Most and least "compatible" opposing pairs.
If your
opposing_pair
implementation works, then the
following code should print the "most compatible" opposing pairs. (If it doesn't work, that's okay -- the cell
below will fail, but it shouldn't affect your final score.)
Out[35]:
[('alice', 'bob', 2), ('alice', 'carol', 1)]
(Passed.)
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
11/28/23, 8:39 PM
problem
file:///Users/dannie/Downloads/pmt1-sample-solutions-su21/problem23-sample-solutions.html
41/41
In [37]:
congress_pairs = opposing_pairs(voting_vectors, parties)
print("Top opposing pairs:")
sorted(congress_pairs, key=
lambda
x: x[-1], reverse=
True
)[:11]
In [38]:
print("Most polar (least compatible) opposing pairs:")
sorted(congress_pairs, key=
lambda
x: x[-1], reverse=
True
)[-11:]
Epilogue.
The analysis contained herein is just the tip of the iceberg of what you could do with this data, as well
as all the other data available through
ProPublica's Congress APIs
(https://projects.propublica.org/api-
docs/congress-api/). If you live in the US and are civic-minded, consider mining it for even more interesting
information!
Fin!
You’ve reached the end of Midterm 1. Don’t forget to restart and run all cells again to make sure it’s all
working when run in sequence; and make sure your work passes the submission process. Good luck!
Top opposing pairs:
Out[37]:
[('Susan Collins', 'Joe Manchin III', 202),
('Susan Collins', 'Doug Jones', 190),
('Susan Collins', 'Kyrsten Sinema', 183),
('Rob Portman', 'Joe Manchin III', 176),
('Cory Gardner', 'Joe Manchin III', 175),
('Roger Wicker', 'Joe Manchin III', 175),
('Shelley Moore Capito', 'Joe Manchin III', 174),
('Roy Blunt', 'Joe Manchin III', 174),
('John Boozman', 'Joe Manchin III', 173),
('Mitch McConnell', 'Joe Manchin III', 173),
('Mitt Romney', 'Joe Manchin III', 173)]
Most polar (least compatible) opposing pairs:
Out[38]:
[('Patrick J. Toomey', 'Elizabeth Warren', 7),
('Michael B. Enzi', 'Cory Booker', 7),
('James Lankford', 'Cory Booker', 7),
('James Lankford', 'Elizabeth Warren', 7),
('James M. Inhofe', 'Cory Booker', 7),
('James M. Inhofe', 'Elizabeth Warren', 6),
('Kelly Loeffler', 'Kamala Harris', 5),
('Kelly Loeffler', 'Cory Booker', 5),
('Kelly Loeffler', 'Kirsten E. Gillibrand', 5),
('Kelly Loeffler', 'Elizabeth Warren', 4),
('Kelly Loeffler', 'Edward J. Markey', 0)]
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
Related Documents
Recommended textbooks for you

C++ for Engineers and Scientists
Computer Science
ISBN:9781133187844
Author:Bronson, Gary J.
Publisher:Course Technology Ptr

Systems Architecture
Computer Science
ISBN:9781305080195
Author:Stephen D. Burd
Publisher:Cengage Learning

C++ Programming: From Problem Analysis to Program...
Computer Science
ISBN:9781337102087
Author:D. S. Malik
Publisher:Cengage Learning
Programming Logic & Design Comprehensive
Computer Science
ISBN:9781337669405
Author:FARRELL
Publisher:Cengage

EBK JAVA PROGRAMMING
Computer Science
ISBN:9781337671385
Author:FARRELL
Publisher:CENGAGE LEARNING - CONSIGNMENT

New Perspectives on HTML5, CSS3, and JavaScript
Computer Science
ISBN:9781305503922
Author:Patrick M. Carey
Publisher:Cengage Learning
Recommended textbooks for you
- C++ for Engineers and ScientistsComputer ScienceISBN:9781133187844Author:Bronson, Gary J.Publisher:Course Technology PtrSystems ArchitectureComputer ScienceISBN:9781305080195Author:Stephen D. BurdPublisher:Cengage LearningC++ Programming: From Problem Analysis to Program...Computer ScienceISBN:9781337102087Author:D. S. MalikPublisher:Cengage Learning
- Programming Logic & Design ComprehensiveComputer ScienceISBN:9781337669405Author:FARRELLPublisher:CengageEBK JAVA PROGRAMMINGComputer ScienceISBN:9781337671385Author:FARRELLPublisher:CENGAGE LEARNING - CONSIGNMENTNew Perspectives on HTML5, CSS3, and JavaScriptComputer ScienceISBN:9781305503922Author:Patrick M. CareyPublisher:Cengage Learning

C++ for Engineers and Scientists
Computer Science
ISBN:9781133187844
Author:Bronson, Gary J.
Publisher:Course Technology Ptr

Systems Architecture
Computer Science
ISBN:9781305080195
Author:Stephen D. Burd
Publisher:Cengage Learning

C++ Programming: From Problem Analysis to Program...
Computer Science
ISBN:9781337102087
Author:D. S. Malik
Publisher:Cengage Learning
Programming Logic & Design Comprehensive
Computer Science
ISBN:9781337669405
Author:FARRELL
Publisher:Cengage

EBK JAVA PROGRAMMING
Computer Science
ISBN:9781337671385
Author:FARRELL
Publisher:CENGAGE LEARNING - CONSIGNMENT

New Perspectives on HTML5, CSS3, and JavaScript
Computer Science
ISBN:9781305503922
Author:Patrick M. Carey
Publisher:Cengage Learning