Week 2: Exercises

1. Rolling N Dice

Read a number N from the console. Simulate rolling N 6-sided dice. Write the value of each die roll, followed by the sum of all of them.

How many dice? 4
6 2 6 1
total: 15
===
How many dice? 2
6 2
total: 8

2. Flipping a Coin

Simulate coin flips, printing an 'H' each time the coin falls on heads and 'T' each time it falls on tails. Once you reach the third H, stop and write how many coins were flipped.

HTTTHTH
7 flips
===
TTTHTTTTTHH
11 flips

3. Square

Read a number N, then print an N x N square of asterisks as in the example below.

Enter N: 5
*****
*   *
*   *
*   *
*****

4. Triangle

Read a number N, then print an N x N triangle of asterisks as in the example below.

Enter N: 6
     *
    **
   ***
  ****
 *****
******

5. Spaces In Between

Read a string and write it out with a space between each adjacent pair of characters.

Enter string: waffle
w a f f l e

6. Double Or Nothing

Read a string and print 'double' if any two adjacent characters are the same, or 'nothing' otherwise.

Enter string: abacuses
nothing
===
Enter string: lionesses
double

7. Password Generator

Write a program that generates a random password with 10 lowercase letters. The password should contain alternating consonants and vowels.

Sample outputs:

  kimolonapo
  ritilenora

8. String Comparison

Write a program that reads two string S and T, each on its own line. The program should print the string that is lexicographically greater, i.e. the string that appears later in dictionary order. Do not use the built-in string comparison operator '>'.

Enter S: limerick
Enter T: limeade
limerick

9. 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.

10. AEIOU

Write a program that reads a string on a single line and prints "vowels" if the string contains any vowels, otherwise "no vowels".

11. ASCII or Unicode

Read a string and print either 'ascii' if the string contains only ASCII characters, 'unicode' otherwise.

12. Capitalizing Words

Write a program that reads a string and capitalizes all words in the string. For this exercise, words are sequences of characters separated by one or more spaces. (Do not use the built-in method title(), which does the same thing.)

Sample input:

  one    fine     day

Output:

  One    Fine     Day