Software Carpentry Day 1: Exercises

Morning

  1. Using while, %, and if, write a loop that adds up the values of the odd numbers that are less than 50.
  2. Using two while loops, write a program that prints a triangle like this:
    *
    **
    ***
    ****
    *****
    
  3. Consider the following simple rule:
    if N is 1:
      stop
    else if N is even:
      halve it
    else:
      multiply it by three and add one
    
    If N is 5, this generates the sequence 5, 16, 8, 4, 2, 1. If N is 3, this generates 3, 10, 5, 16, 8, 4, 2, 1. Write a program that calculates the number of steps in the sequence for each value of N from 1 to 100. Do you see any patterns? (If so, please publish them---this is an open problem in computer science.)

Afternoon

  1. Write a program that reads a file containing a list of words, one per line, like:
    hello
    there
    
    and prints a list of pig Latin words like:
    ellohay
    heretay
    
    (Yes, it should be "erethay", but we'll keep it simple for now.)
  2. Write a program that takes a nested list like [[1, 2], [3, 4, 5]] and produces a flattened list like [1, 2, 3, 4, 5].
  3. Write a program that reads the files data.txt and writes the non-empty lines in it to useful.txt.

Homework

  1. Write a function longer(first, second) that returns the longer of two strings. What should it do if the strings are of equal length?
  2. Write a function earlier(first, second) that returns the string that would come first in the dictionary.
  3. Write a function endsic(string) that returns True if a string ends in ic, and False otherwise.
  4. Write a function isnum(string) that returns True if a string contains only digits, and False otherwise.
  5. Write a function delfirst(vals, target) that removes the first instance of target from vals, or does nothing.
  6. Write a function sample(vals, stride) that returns a list containing every stride'th element of the list vals (e.g., every 2nd or 5th). What should it do if stride is 1? 0? Negative?
  7. Write a function issquare(matrix) that returns True if the list-of-lists called matrix is square (all sublists the same length, exactly as many sublists as the main list is long), and False otherwise.
  8. Write a function sumto(list, threshold) that return the first index i such that the sum of the list values up to and including i is greater than or equal to the threshold.
  9. In genetic cryptography, the four bases ACGT represent the digits 0123 in a base-4 numerical system, so CGA is (1*4^2)+(2*4)+0 = 20. Write a function dna2num(str) to convert a DNA string to a number, and another function num2dna(int) to convert an integer to a DNA string.