Week 5: Exercises

1. Starts With

Write a function startswith(s, t) that takes strings s and t and returns True if s starts with t. Do not use the built-in method of the same name.

2. Contains

Write a function contains that takes two strings S and T, and returns true if S contains T. For example, contains('key lime pie', 'lime') should return true. Do not use the in operator.

3. Letter Histogram

Write a program that reads a series of input lines and determines how many times each letter A-Z appears in the input. You should ignore case, considering 'a' and 'A' to be the same letter. The input text is guaranteed to contain at least one letter, and will not contain any accented characters such as 'ř'.

The program should print the most frequent letter with a count of its occurrences. It should also print a histogram showing how many times each letter occurred in the input. If a letter occurs 1-3 times, print a single *. If it occurs 4-6 times, print two asterisks (**), and so on.

Sample input:

The quick fox jumped over the lazy dog.
Then the dog got up and jumped over the fox.

Sample output:

Most frequent letter: e (9)

a: *
b: 
c: *
d: **
e: ***
f: *
g: *
h: **

...

4. Lottery Ticket

A country is holding a lottery in which 5 winning numbers are chosen at random from the range 1..25. No two of these numbers will be the same. For example, the winning numbers could be 2 – 4 – 9 – 18 – 22, or 5 – 6 – 11 – 15 – 24.

Write a program that randomly selects 5 winning numbers and prints them on a single line in ascending order.

5. Simulated Rumor

Write a program that reads an integer N, representing a number of people. Simulate a rumor that spreads among these people as follows. A random person starts the rumor. They tell it to another person selected at random, who tells it to someone else, and so on, until someone hears the rumor who has already heard it before. At that point the rumor stops circulating. The program should produce output like this:

Enter N: 100
Person 41 heard the rumor.
Person 83 heard the rumor.
Person 22 heard the rumor.
…
Person 83 heard the rumor again.
14 people heard the rumor in all.

6. Random X's

Write a program that reads an integer N, and writes out a 10 x 10 block of dots (.), with X's in exactly N random positions.

Sample input:

10

Sample output:

. . . . . . . . . . 

. . . . . . . . . . 

. . . . . . . . . . 

. . . . X . . . . . 

. . X . . . X . . . 

. . . . . X . . X . 

. . . X . . . . X . 

. . . . . . . . X . 

X . . . . . . . . . 

. . X . . . . . . .