GEOG 485:
GIS Programming and Automation

Lesson 4 Practice Exercise B Solution

PrintPrint

This practice exercise is a little trickier than previous exercises. If you were not able to code a solution, study the following solution carefully and make sure you know the purpose of each line of code.

The code below refers to the "winner" and "loser" of each game. This really refers to the first score given and the second score given, in the case of a tie.

# Reads through a text file of soccer (football)
#  scores and reports the highest number of goals
#  in one game for each team
 
# ***** DEFINE FUNCTIONS *****
 
# This function checks if the number of goals scored
#  is higher than the team's previous max.
def checkGoals(team, goals, dictionary):
    #Check if the team has a key in the dictionary
    if team in dictionary:
        # If a key was found, check goals against team's current max
        if goals > dictionary[team]:
            dictionary[team] = goals
        else:
            pass
    # If no key found, add one with current number of goals
    else:
        dictionary[team] = goals
 
# ***** BEGIN SCRIPT BODY *****

import csv
         
# Open the text file of scores
scoresFilePath = "C:\\Data\\Geog485\\Scores.txt"
scoresFile = open(scoresFilePath)
 
# Read the header line and get the important field indices
csvReader = csv.reader(scoresFile, delimiter=" ")
header = csvReader.next()

winnerIndex = header.index("Winner")
winnerGoalsIndex = header.index("WG")
loserIndex = header.index("Loser")
loserGoalsIndex = header.index("LG")

# Create an empty dictionary. Each key will be a team name.
#  Each value will be the maximum number of goals for that team.
maxGoalsDictionary = {}

for row in csvReader:

    # Create variables for all items of interest in the line of text    
    winner = row[winnerIndex]
    winnerGoals = row[winnerGoalsIndex]
    loser = row[loserIndex]
    loserGoals = row[loserGoalsIndex]
 
    # Check the winning number of goals against the team's max
    checkGoals(winner, winnerGoals, maxGoalsDictionary)
 
    # Also check the losing number of goals against the team's max    
    checkGoals(loser, loserGoals, maxGoalsDictionary)
 
# Print the results
for key in maxGoalsDictionary:
    print key + ": " + maxGoalsDictionary[key]

Below is a video offering some line-by-line commentary on the structure of this solution. Please note two errors in the video: 1) At one point I said "line 30" when I meant "line 31". 2)  I used the word "tie" to refer to the scenario when both teams end up with the same number of goals, when I know you football fans will be quickly reminding me that I should have called this a "draw".  :-)