Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- import sys
- # map of candidate names to candidate numbers
- candidates = {}
- # the highest candidate number seen so far
- maxCandidateNum = 0
- # open ballots.txt for writing
- with open("ballots.txt", "w") as ballotFile:
- # loop through all command-line args except the first (the program name)
- for filename in sys.argv[1:]:
- # start an empty ballot for this file
- ballot = []
- # open the file for reading and loop through all lines in it
- with open(filename, "r") as currentFile:
- for line in currentFile:
- # the current candidate is the line with all leading and trailing whitespace stripped
- candidateName = line.strip()
- # if the candidate has already been seen, get its number
- # otherwise, assign a new number to it
- if candidateName in candidates:
- candidateNum = candidates[candidateName]
- else:
- maxCandidateNum += 1
- candidateNum = maxCandidateNum
- candidates[candidateName] = candidateNum
- # add the candidate number to the current ballot
- ballot.append(candidateNum)
- # write the current ballot, as one line with > between each candidate number
- ballotString = " > ".join(str(num) for num in ballot)
- ballotFile.write(ballotString + "\n")
- # now that we've read all candidates from all files, write candidates.txt
- with open("candidates.txt", "w") as candidateFile:
- # define a comparison function which, given two candidate names, returns the one with the lower candidate number
- def candidateNumberSort(name1, name2):
- num1 = candidates[name1]
- num2 = candidates[name2]
- return cmp(num1, num2)
- # use this function to loop through the candidate map in order of number, and write the name
- candidateNames = candidates.keys()
- for candidateName in sorted(candidateNames, candidateNumberSort):
- candidateFile.write(candidateName + "\n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement