Python Homework 3

# Replace "Your Name" with your name :)

my_name = "Your Name"

# I'm hoping this will be pretty straightforward.

# First, this little bit of code will make sure you have

# Project Gutenberg's "Adventures of Sherlock Holmes" text

# file in the same directory (folder) as this quiz file.

# It's designed so that you only download it once regardless

# of how many times you run this file.

 

import os.path as path

import requests

if not path.isfile('sherlock.txt'):

    response = requests.get('https://www.gutenberg.org/files/1661/1661.txt')

    with open('sherlock.txt', 'w') as sherlock:

        sherlock.write(response.text)

# Here's the whole problem this week: open that file, read it,

# and count how many times "Moriarty" appears, how many times

# "Watson" appears, how many times "Adler" appears, and finally

# how many times "Holmes" appears.

# The values should be in a dictionary called "counts" with 

# keys for (at least) Moriarty, Watson, Holmes, and Adler.

# IMPORTANT: if one of those names doesn't appear, then the count 

#            should be zero for that name

# Hints: 1. Python For Everybody walks through an example using

#        a dictionary as a counter. You may or may not fund that useful.

#        2. Think about how you might find these names: could they

#        appear separated by whitespace, or are there other characters

#        (like punctuation) that might also be present? Is there a

#        solution where this doesn't matter?

#        3. There's more than one way to approach this, but the split

#        method of the re (regex) package might be useful. So might findall.

counts = {}

### Your implementation here

 

#### Do not modify anything below this line

try: 

    assert my_name != 'Your Name'

except AssertionError:

    print('Please make my_name variable your actual name.')

    raise

got_em_all = True

problems = []

try:

    assert counts['Adler'] == 15

except AssertionError:

    got_em_all = False

    problems.append('Count for Adler is off.')

try:

    assert counts['Watson'] == 81

except AssertionError:

    got_em_all = False

    problems.append('Count for Watson is off.')

try:

    assert counts['Holmes'] == 461

except AssertionError:

    got_em_all = False

    problems.append('Count for Holmes is off.')

try:

    assert counts['Moriarty'] == 0

except AssertionError:

    got_em_all = False

    problems.append('Count for Moriarty is off.')

except KeyError:

    got_em_all = False

    problems.append('Read the instructions carefully!')

 

if got_em_all:

    print(f'Well done, {my_name}! All correct.')

else:

    print('Not quite there, yet:')

    print('\n'.join(problems))

Need a custom answer at your budget?

This assignment has been answered 2 times in private sessions.

Or buy a ready solution below.

Buy ready solution

Solution previews

© 2024 Codify Tutor. All rights reserved