Write a program called ```main(filename)``` that reads from an input file called ```filename``` and creates a dictionary called ```capitals``` containing the U.S. states as keys, and their capitals as values.
The program should then randomly quiz the user by displaying the name of a state and asking the user to enter that state's capital.
The program should keep a count of the number of correct and incorrect responses.
The ```main(filename)``` program should call the functions ```read_dictionary(filename)```, ```run_quiz(capitals)```, and ```show_quiz_results(capitals)``` to do its work.
Here is the algorithm for the ```main(filename)``` function:
```
def main(filename):
capitals = read_dictionary(filename)
results_dct = run_quiz(capitals)
show_quiz_results(results_dct)
Guide On Rating System
Vote
Here is the complete code for the program:
```python
import random
def read_dictionary(filename):
capitals = {}
with open(filename, 'r') as file:
for line in file:
state, capital = line.strip().split(',')
capitals[state] = capital
return capitals
def run_quiz(capitals):
correct = 0
incorrect = 0
states = list(capitals.keys())
random.shuffle(states)
for state in states:
capital = capitals[state]
user_input = input("What is the capital of " + state + "? ")
if user_input == capital:
print("Correct!")
correct += 1
else:
print("Incorrect. The capital of " + state + " is " + capital)
incorrect += 1
return {'correct': correct, 'incorrect': incorrect}
def show_quiz_results(results):
print("Quiz Results:")
print("Correct: " + str(results['correct']))
print("Incorrect: " + str(results['incorrect']))
def main(filename):
capitals = read_dictionary(filename)
results_dct = run_quiz(capitals)
show_quiz_results(results_dct)
filename = "states.txt" # Replace with the actual filename
main(filename)
```
To use this program, save it as a Python file (e.g., quiz.py) and create a text file (e.g., states.txt) containing the state-capital pairs in the format "state,capital" on each line. Then, call the ```main()``` function passing the filename of the text file as an argument. The program will read the file, run the quiz, and display the results.