Question

The file Senate113.txt contains the members of the 113th U.S. Senate— that is, the Senate prior...

The file Senate113.txt contains the members of the 113th U.S. Senate— that is, the Senate prior to the November 2014 election. Each record of the file consists 3 ofthreefields—name,state,andpartyaffiliation. Somerecordsinthefileareasfollows:

Richard Shelby,Alabama,R

Bernard Sanders,Vermont,I

Kristen Gillibrand,New York,D

The file RetiredSen.txt contains the records from the file Senate113.txt for senators who left the Senate after the November 2014 election due to retirement, defeat, death, or resignation. Some records in the file are as follows:

John Rockefeller,West Virginia,D

Tom Coburn,Oklahoma,R

Carl Levin,Michigan,D

The file NewSen.txt contains records for the senators who were newly elected in November 2014 or who were appointed to fill the seats of senators who left after the November 2014 election. Some records in the file are as follows:

Shelly Capito,West Virginia,R

Steve Daines,Montana,R

Gary Peters,Michigan,D

(a) Write a python program that uses the three files above to create the file Senate114.txt that contains records (each consisting of three fields) for the members of the 114th Senate where the members are ordered by state. Use this file in parts (b), (c), and (d).

(b) Write a python program that determines the number of senators of each party affiliation. See Fig. 5.49.

(c) Write a python program that determines the number of states whose two senators have the same party affiliation.

(d) Write a python program that asks the user to input a state, and then displays the two sena- tors from that state. See Fig. 5.50.

Figure 5.49 Outcome of 4(b)

Party Affiliations:
  Republicans: 54
  Democrats: 44
  Independents: 2

Figure 5.50 Outcome of 4(d)

Enter the name of a state: Maryland

Benjamin Cardin Barbara Mikulski

0 0
Add a comment Improve this question Transcribed image text
Answer #1

The python program to perform the above operations is as follows

# creating new file from the existing file contents
def createNewFile():
# save the filenames in a list
fileNames = ['Senate113.txt', 'RetiredSen.txt', 'NewSen.txt']
# open the new file to which the contentsto be written
with open('Senate114.txt','w') as f:
for file in fileNames: # iterate through the files
with open(file, 'r') as f1: # open the file
for line in f1:
f.write(line) # write the content to the new file
f.write('\n')
f1.close()
f.close()
  
# find the senator count for each party affliation
def findSenatorsCount():
fileName = 'Senate114.txt'
# initialise the count of each party
r_count = 0
d_count = 0
i_count = 0
with open(fileName, 'r') as f: # open the file
for line in f:
data = line.split(',')
party = str(data[-1]).strip() # find the party affliation
if party == 'I': # check for the party to increment the count
i_count = i_count + 1
elif party == 'D':
d_count += 1
else:
r_count += 1
# print the count of senators under each party affliation
print('''Party Affliations:
Republicans : {r}
Democrats : {d}
Independants : {i}'''.format(r = r_count, i = i_count, d = d_count))

# find the number of states whose two senators have the same party affliation
def findStatesCount():
fileName = 'Senate114.txt'
stateAndParty = []
count = 0 # initialise count to 0
# iterate through the file content and create a list of state and party affliation
with open(fileName, 'r') as f: # open the file
data = f.readlines()
for datum in data:
content = datum.strip().split(',')
stateAndParty.append(content[1] + content[2]) # create the state party pair
# iterate through the list to find the match and increase the count of states
for content_num,content in enumerate(stateAndParty):
length = len(data)
for i in range(content_num+1,length):
if str(content) == str(stateAndParty[i]):
count += 1
print(count)
  
def displayTwoSenators():
state = input("Enter the name of a state : ") # read the input state
fileName = 'Senate114.txt'
count = 0 # initialise the count
with open(fileName, 'r') as f: # open the file
data = f.readlines()
for datum in data:
content = datum.strip().split(',')
if str(content[1]) == state: # check for the state
print(content[0])
count += 1
if count == 2:
break
  
# createNewFile()
# findSenatorCount()   
# findStatesCount()
displayTwoSenators()

Files :

Senate113.txt

Richard Shelby,Alabama,R
Bernard Sanders,Vermont,I
Kristen Gillibrand,New York,D

RetiredSen.txt

John Rockefeller,West Virginia,D
Tom Coburn,Oklahoma,R
Carl Levin,Michigan,D

NewSen.txt

Shelly Capito,West Virginia,R
Steve Daines,Montana,R
Gary Peters,Michigan,D

Senate114,txt

Screenshots :

Source code:

Output :

output for part 4(d)

Add a comment
Know the answer?
Add Answer to:
The file Senate113.txt contains the members of the 113th U.S. Senate— that is, the Senate prior...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • In Python The file Senate113_sorted.txt contains a list of the 100 US Senators that made up the 1...

    In Python The file Senate113_sorted.txt contains a list of the 100 US Senators that made up the 113th Senate, sorted in alphabetical order by Senator last name. Write a function named different_party that accepts one argument, a file name, and returns a list of US states whose Senators come from 2 different political parties (as indicated by D, R, or I). Here's a few rows from the file Lamar Alexander,Tennessee,R Kelly Ayotte,New Hampshire,R Tammy Baldwin,Wisconsin,D John Barrasso,Wyoming,R Max Baucus,Montana,D Mark...

  • Write a C program that takes inventory data from a file and loads a structure of up to 100 items ...

    Write a C program that takes inventory data from a file and loads a structure of up to 100 items defined as: struct item { int item_number; char item_name[20]; char item_desc[30]; float item_price; } I called mine: struct item inventory[100]; (you may use any name you wish) I will let you decide the appropriate prompts and edit messages. You will read the data from the data file and store the info in an array. Assume no more than 100 records...

  • Please Help!(Write a C++ program Only):- The attached file has a number of records giving US...

    Please Help!(Write a C++ program Only):- The attached file has a number of records giving US state names, populations, and number of Federal electors. The fields are delimited by spaces. The first field is a single integer giving the number of states that follow. Guidelines:- 1)Read the first integer and use it to allocate dynamic arrays to contain the state name and the state population. 2) Read in the population data. The electors field is not used. 3) Calculate the...

  • It's Python :D Write a program that does the following: Allow the user to specify the...

    It's Python :D Write a program that does the following: Allow the user to specify the name of an input file containing voter participation data (that way, different data files can be tested). Read the data from the file and write a report out to a new file as follows: The name of the output file should be the name of the input file preceded with the word 'REPORT-'. So, if the input file is named 'PresidentialElections.txt', then the output...

  • The file “EX10-38TUIT.csv” contains the undergraduate tuition in 2008 and 2014 for 33 public universities. Use...

    The file “EX10-38TUIT.csv” contains the undergraduate tuition in 2008 and 2014 for 33 public universities. Use R to carry out the analysis. a) (2 points) Plot the data with the 2008 tuition on the x axis and describe the relationship. Are there any outliers or unusual values? Does a linear relationship between the tuition in 2008 and 2014 seem reasonable? b) (2 points) Run the simple linear regression and give the least-squares regression line. c) (1 point) Obtain the residuals...

  • The file “EX10-38TUIT.csv” contains the undergraduate tuition in 2008 and 2014 for 33 public universities. Use R to carr...

    The file “EX10-38TUIT.csv” contains the undergraduate tuition in 2008 and 2014 for 33 public universities. Use R to carry out the analysis. a) (2 points) Plot the data with the 2008 tuition on the x axis and describe the relationship. Are there any outliers or unusual values? Does a linear relationship between the tuition in 2008 and 2014 seem reasonable? b) (2 points) Run the simple linear regression and give the least-squares regression line. c) (1 point) Obtain the residuals...

  • JAVA Create a Governor class with the following attributes: name : String party - char (the...

    JAVA Create a Governor class with the following attributes: name : String party - char (the character will be either D, R or I) ageWhenElected : int Create a State class with the following attributes: name : String abbreviation : String population : long governor : Governor Your classes will have all setters, getters, typical methods to this point (equals(), toString()) and at least 3 constructors (1 must be the default, 1 must be the copy). You will be turning...

  • Python 3 Question Do NOT use global variables (This is an edit to a question I've...

    Python 3 Question Do NOT use global variables (This is an edit to a question I've asked before because I forgot to include a template. So if you have answered this question already I ask that you do not copy and paste a previous answer.) PLEASE use the template given, keep the code introductory friendly, and include comments. Many thanks. Prompt: The results of a survey of the households in your township are available for public scrutiny. Each record contains...

  • Write a c++ program in that file to perform a “Search and Replace All” operation. This...

    Write a c++ program in that file to perform a “Search and Replace All” operation. This operation consists of performing a case-sensitive search for all occurrences of an arbitrary sequence of characters within a file and substituting another arbitrary sequence in place of them. Please note: One of the biggest problems some students have with this exercise occurs simply because they don’t read the command line information in the course document titled “Using the Compiler’s IDE”. Your program: 1. must...

  • Question 1. (Minitab or R) The Environmental Protection Agency (EPA) tracks the management of certain toxic chemicals th...

    Question 1. (Minitab or R) The Environmental Protection Agency (EPA) tracks the management of certain toxic chemicals that may pose a threat to human health and the environment. U.S. facilities in different industry sectors must report annually how much of each chemical is released to the environment and/or managed through recycling, energy recovery and treatment. (A "release" of a chemical means that it is emitted to the air or water, or placed in some type of land disposal.) The information...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT