Program of the Day #17

This program will analyze a tic-tac-toe game whose board is read from a file and determine whether and how a player has won.

The main program reads the game state from the first three lines of a file that represents the game in the following format:

x| |x
x|o|o
o| |x

As in P16, the first time you run the test program, it will create a folder called P17_games containing seven input game files. You can use these for testing.

The program prints a message such as the following (for the example input above):

After 7 moves, nobody has won.
X| |X
X|O|O
O| |X

Here’s another example input file, where the o player has won:

x| |o
x|o|o
o| |x

The output for this game is:

After 7 moves, player o has won on diagonal 1.
X| |O
X|O|O
O| |X

To accomplish this, you will write a number of helper functions, whose behavior is detailed in the functions’ specs in the skeleton code. A couple of notes:

The test cases will check correctness of the helper funtions; there are currently no tests for the main program.

Other Practice Problems

  1. Implement the following function:

    def charcount(in_string):
        """ Return a dictionary that maps each unique character in 
        in_string to the number of times it appears in the string.
        Precondition: in_string is a string
        Example: count("hahah") # => {"a": 2, "h": 3} """   
  2. Implement the following function; you may call the function you wrote for Problem 1.

    def strmode(in_str):
        """ Return the most frequently-appearing character in   
        in_str, or any of the most frequent characters in case of a
        tie. Precondition: in_str is a string with nonzero length.
        Examples: strmode('hahah') # => 'h'
                  strmode('who') # => could return 'w', 'h', or 'o'
        """
  3. Implement the following function:

    def dict_intersection(d1, d2):
      """ Return a dictionary containing only keys that appear in both d1 and d2.
      Each key's value is the sum of the corresponding values in d1 and d2.
      Example: dict_intersection({1: 2, 2: 3}, {2: -1, 3: 10}) => {2: 2}"""
  4. Implement the following function:

    def same_elements(list1, list2):
      """Return true if list1 and list2 contain exactly the same elements, possibly
      in a different order from each other. 
      Examples: same_elements([1, 2], [1, 2]) => True
                same_elements([1, 2], [2, 1]) => True
                same_elements([1, 2, 3], [2, 1, 3]) => True
                same_elements([1, 2], [2, 2]) => False
                same_elements([1, 1, 2], [2, 1, 1]) => True
                same_elements([1, 2, 2], [1, 1, 2]) => False
      Precondition: list1 and list2 are lists """