A document from MCS 260 Fall 2021, instructor Emily Dumas. You can also get the notebook file.

MCS 260 Fall 2021 Homework 5 Solutions

  • Course instructor: Emily Dumas
  • Solutions prepared by: Johnny Joyce and Emily Dumas

Instructions:

  • Complete the problems below, which ask you to write Python scripts.
  • Upload your python code directly to gradescope, i.e. upload the .py files containing your work. (If you upload a screenshot or other file format, you won't get credit.)

Deadline

This homework assignment must be submitted in Gradescope by 10am CST on Tuesday, September 28, 2021.

Topic

This homework assignment is about the topics of worksheet 5, i.e.

  • functions
  • dictionaries
  • additional features of strings (e.g. .split(), .strip(), .replace())
  • the math module
  • the random module

Collaboration

Collaboration is prohibited, and you may only access resources (books, online, etc.) listed below.

Resources you may consult

The course materials you may refer to for this homework are:

Point distribution

This homework assignment has 2 problems, numbered 2 and 3. The grading breakdown is:

Points Item
2 Autograder
4 Problem 2
4 Problem 3
10 Total

What to do if you're stuck

Ask your instructor or TA a question by email, in office hours, or on discord.

( 1. There's no problem 1 )

Gradescope will show the results of the automated syntax check of all submitted files as the score for problem 1.

2. String stats function

Write a function called string_stats(s) that accepts a string s and returns a dictionary with the following keys and values:

  • key "length" -> the length of s
  • key "words" -> the number of words in s, as determined by the .split() method
  • key "exclamation_count" -> the number of times the character "!" appears in s

The function must not print anything to the terminal. Do not use the print() function at all.

You don't need to write any code to actually call this function, but that might be helpful while you're preparing it (for testing). Here are some sample inputs and expected return values from the function. What you see below displays the return value after each function call, just as the Python REPL would do. The function itself isn't printing anything.

In [11]:
string_stats("Did you see the new project description?  It's available now!")
Out[11]:
{'length': 61, 'words': 10, 'excalamation_count': 1}
In [12]:
string_stats("wheeee!!!!!!!!!!!!!")
Out[12]:
{'length': 19, 'words': 1, 'excalamation_count': 13}
In [13]:
string_stats("nothing to see here")
Out[13]:
{'length': 19, 'words': 4, 'excalamation_count': 0}

Put the function definition in a file homework5.py. The next problem will have you add another function to that file.

Solution

In [2]:
def string_stats(s):
    '''
    Returns a dictionary with statistics about a string `s`
    '''
    # Use curly braces to define a dictionary
    stats = { "length": len(s),
              "words": len(s.split()),
              "exclamation_count": len( [c for c in s if c == "!"]) }
    return stats # Return the dictionary we made

# test code
print(string_stats("Did you see the new project description?  It's available now!"))
print(string_stats("wheeee!!!!!!!!!!!!!"))
print(string_stats("nothing to see here"))
{'length': 61, 'words': 10, 'exclamation_count': 1}
{'length': 19, 'words': 1, 'exclamation_count': 13}
{'length': 19, 'words': 4, 'exclamation_count': 0}

Remark: There is also a method of str in Python that will count how many times a character appears. Using this, the number of exclamation points could be counted using

In [ ]:
s.count("!")

in place of the list comprehension appearing in the solution above.

3. Random letter function

Write a function random_letter() that returns a randomly selected capital letter from the alphabet (A-Z).

The function must not print anything to the terminal. Do not use the print() function at all.

You don't need to write any code to actually call this function, but that might be helpful while you're preparing it (for testing). Here are some sample calls and the return values from such a function (but of course, due to the random element, it will behave differently every time it is run):

In [8]:
random_letter()
Out[8]:
'J'
In [9]:
random_letter()
Out[9]:
'U'
In [10]:
random_letter()
Out[10]:
'S'

Put the definition in a file homework5.py (i.e. the same file where you put the function requested in problem 2). Make sure the file imports any modules your function requires.

In [6]:
import random

def random_letter():
    '''
    Return a capital letter chosen from the alphabet at random
    '''
    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    letter = random.choice(alphabet)
    return letter

# test code
for i in range(3):
    print(random_letter())
B
Q
V

Revision history

  • 2021-09-29 Initial release