1. #!/usr/bin/env python
  2. import sys
  3.  
  4. # map of candidate names to candidate numbers
  5. candidates = {}
  6.  
  7. # the highest candidate number seen so far
  8. maxCandidateNum = 0
  9.  
  10. # open ballots.txt for writing
  11. with open("ballots.txt", "w") as ballotFile:
  12.  
  13.     # loop through all command-line args except the first (the program name)
  14.     for filename in sys.argv[1:]:
  15.  
  16.         # start an empty ballot for this file
  17.         ballot = []
  18.  
  19.         # open the file for reading and loop through all lines in it
  20.         with open(filename, "r") as currentFile:
  21.             for line in currentFile:
  22.  
  23.                 # the current candidate is the line with all leading and trailing whitespace stripped
  24.                 candidateName = line.strip()
  25.  
  26.                 # if the candidate has already been seen, get its number
  27.                 # otherwise, assign a new number to it
  28.                 if candidateName in candidates:
  29.                     candidateNum = candidates[candidateName]
  30.                 else:
  31.                     maxCandidateNum += 1
  32.                     candidateNum = maxCandidateNum
  33.                     candidates[candidateName] = candidateNum
  34.  
  35.                 # add the candidate number to the current ballot
  36.                 ballot.append(candidateNum)
  37.  
  38.         # write the current ballot, as one line with > between each candidate number
  39.         ballotString = " > ".join(str(num) for num in ballot)
  40.         ballotFile.write(ballotString + "\n")
  41.  
  42. # now that we've read all candidates from all files, write candidates.txt
  43. with open("candidates.txt", "w") as candidateFile:
  44.  
  45.     # define a comparison function which, given two candidate names, returns the one with the lower candidate number
  46.     def candidateNumberSort(name1, name2):
  47.         num1 = candidates[name1]
  48.         num2 = candidates[name2]
  49.         return cmp(num1, num2)
  50.  
  51.     # use this function to loop through the candidate map in order of number, and write the name
  52.     candidateNames = candidates.keys()
  53.     for candidateName in sorted(candidateNames, candidateNumberSort):
  54.         candidateFile.write(candidateName + "\n")