Week 4: 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. Consecutive Sum

Write a function consecutive(a, n, t) with parameters a (a list of integers) and n and t (both integers). The function should return true if any consecutive series of n values in a have the sum t.

For example, consecutive([9, 7, 5, 2, 3, 2], 3, 10) is true, because the consecutive values [5, 2, 3] have sum 10.

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. Local and Global

What will this program print?

a = 2
b = 3

def foo():
  a = b + 1
  a = a + 1
  return a

def bar():
  global b
  b = a + 3
  return b

def baz():
  return a + b

def thud():
  a = b + 1
  b = a + 1
  return a

print(foo())
print(bar())
print(baz())
print(thud())

7. Largest product in a series

Solve Project Euler's problem 8, reading the input number as a series of lines from standard input.

8. Longest Collatz sequence

Solve Project Euler's problem 14.