Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Tasks You are to write the following Python functions. M sure you understand whe

ID: 3827338 • Letter: T

Question

Tasks You are to write the following Python functions. M sure you understand where each function fits into the required system described above. 1. def getcandidates file names will be one per getcandidates (f) returns a list containing the candidates' names from the f. The line with no extraneous characters. Disregard any blank lines in f. If f doesn't exist, print an appropriate error message and retum the empty list. For example, getcandidates ("candidates.txt "Major Clanger Soup Dragon "Froglet", Iron Chicken The Cloud" 2. def parsevote (s) parsevote (s) returns the vote from s Retum o for an empty vote, and -1 if there are any non-digits (other th spaces). For example, parse Vote parsevote parsevote -3") parse Vote ("no") parse Vote ("1 5") -1, parse vote ("15") parsevote 15 15 3. def parse Paper ts, n) parse Paper (s, n) retums the votes from the ballot paper s in an election with n candidates, plus an error message if appropriate. If s is formal, retum the list of numbers found in s and the empty string: if s is informal, return an empty list of numbers and the appropriate string below. For example: parse Paper ("14, 2", 4) 14, 0, 2] parse Paper parse Paper blank") rse Paper parse Paper parse Paper pointless n-digits") parse Paper ("1, 2, 4, 5", 4) too long parse Paper will use parsevote. 4. def get Papers (f, n) get Papers (f, n) retums a list containing the ballot papers from the file f, in an election with n candidates. Treat each line of the file as a separate paper. If f doesn't exist, print an appropriate error message and return the empty list. For example: get Papers small file.txt 41 blank non-digits non-digits") 4 long"), ti, blank smallfiletst is available from the project web-site. get Papers will use parsePaper. 5. def normalise Paper (p, n) sum (p) normalise Paper (p, n) retums p with each vote scaled according to its total, and padded to contain n votes. For example: normalise Paper (11,2, 3, 41, 4) 10.1, o.2, o. 3, o.4), normalise Paper (12 J, 3) (1.0, 0.0, 0.01, normalise Paper (10, 4, 496] 3) 10.000 008 9921 6. def normalise Papers (ps, n) for every p on ps, sum (p) o normalise Papers (ps, n) returns pos with each paper normalised, in an election with n candidates. eg, normalise Papers (I12) 17, 2, 11), 3) t[1.0, -0, 0.0], [0.7, 0.2, 0.111 normalise Papers will use normalise Paper.

Explanation / Answer

project1test.py

import project1
import os.path


#a non-existent file
nonfile = "nofile.txt"

def hackb(xs):
    if xs == [] or xs[-1][1] != "blank":
        return xs
    else:
        return xs[:-1]


def test_getCandidates():
    f = "candidates.txt"
    if os.path.exists(f):
        return [(project1.getCandidates(x), y) for (x, y) in
                [(f, ["Major Clanger", "Soup Dragon", "Froglet", "Iron Chicken", "The Cloud"])
                ,(nonfile, [])]]
    else:
        print("You need to download file", f, end = " ")
        return []

def test_parseVote():
    return [(project1.parseVote(x), y) for (x, y) in
            [("", 0), ("no", -1), ("27", 27)]]

def test_parsePaper():
    return [(project1.parsePaper(x, y), z) for (x, y, z) in
            [(",,, ",      4, ([],         "blank"))
            ,(" 3,4,5 ", 2, ([],         "too long"))
            ,("4,-4,4",    3, ([],         "non-digits"))
            ,("4,5, 16",   6, ([4, 5, 16], ""))
            ,("9876",      8, ([9876],     ""))]]

def test_getPapers():
    f = "smallfile.txt"
    if os.path.exists(f):
        nd = ([], "non-digits")
        b = ([], "blank")
        tl = ([], "too long")
        return [(hackb(project1.getPapers(x, 4)), y) for (x, y) in
                [(f, [([1,2,3,4], ""), b, ([0,23,0], ""), nd, nd, ([4,0,4,4], ""), tl])
                ,(nonfile, [])]]
    else:
        print("You need to download file", f, end = " ")
        return []

def test_normalisePaper():
    return [(project1.normalisePaper(x, y), z) for (x, y, z) in
            [([2,1,5], 3, [0.25, 0.125, 0.625])
            ,([8,2],   4, [0.8, 0.2,   0,    0])
            ,([7],     4, [1,    0,     0,    0])]]

def test_normalisePapers():
    return [(project1.normalisePapers(x, y), z) for (x, y, z) in
            [([[2,1,5], [8,2]], 3, [[0.25,0.125,0.625], [0.8,0.2,0]])]]

def test_countVotes():
    cs = ["A", "B", "C"]
    return [(project1.countVotes(cs, ps), x) for (cs, ps, x) in
            [(cs, [[0,0,1], [0,1,0], [0,0,1]], [[2, "C"],   [1, "B"],   [0, "A"]])
            ,(cs, [[0.7, 0.2, 0.1]],           [[0.7, "A"], [0.2, "B"], [0.1, "C"]])]]

def test_printCount():
    return []

def test_main():
    return []


def msg(f, z):
    bs = [x == y for (x, y) in z]
    if bs == []:
        s = "untested"
    elif all(bs):
        s = "all " + str(len(bs)) + " test(s) correct"
    else:
        zs = [k for k in range(len(bs)) if not bs[k]]
        s = "These tests incorrect: " + str(zs)[1:-1]
    print("%20s" % (f + ":"), s)

msg("getCandidates",      test_getCandidates())
msg("parseVote",          test_parseVote())
msg("parsePaper",         test_parsePaper())
msg("getPapers",          test_getPapers())
msg("normalisePaper",     test_normalisePaper())
msg("normalisePapers",    test_normalisePapers())
msg("countVotes",         test_countVotes())
msg("printCount",         test_printCount())
msg("main",               test_main())
print()
input("Hit Enter to finish: ")


project1.py

import os

def getCandidates(f):
   candidates = []
   currentDirectoryPath = os.getcwd()
   listOfFileNames = os.listdir(currentDirectoryPath)
   for name in listOfFileNames:
       if name == f:
           candidatesFile = open(f, 'r')
           for line in candidatesFile:
               line = line.strip()
               if (line == ""):
                   continue
               candidates.append(line)
           return candidates
   print(f, "does not exist.")
   return candidates

def parseVote(s):
   if (s == "" or s == " "):
       return 0
  
   s = s.strip()  

   if not s.isdigit():
       return -1

   return int(s)

def parsePaper(s, n):
   paper = []
   votes = s.split(',')
   sumOfVote = 0
   parsedVotes = []
   for vote in votes:
       vote = parseVote(vote)
       parsedVotes.append(vote)
       sumOfVote += vote
       if vote == -1:
           votes = [""]
           paper.append(votes)
           paper.append("non-digits")
           return paper
   if sumOfVote == 0 or len(votes) < n:
       votes = [""]
       paper.append(votes)
       paper.append("blank")
       return paper
   if len(votes) > n:
           votes = [""]
           paper.append(votes)
           paper.append("too long")
           return paper
   paper.append(parsedVotes)
   paper.append("")
   return paper

def getPapers(f, n):
   papers = []
   currentDirectoryPath = os.getcwd()
   listOfFileNames = os.listdir(currentDirectoryPath)
   for name in listOfFileNames:
       if name == f:
           papersFile = open(f, 'r')
           for line in papersFile:
               paper = parsePaper(line, n)
               if paper[1] == "":
                   papers.append(parsePaper(line, n))
           return papers
   print("File", f, "not found.")
   return papers

def normalisePaper(p, n): # sum(p) > 0
   normal = []
   if p == []:
       return normal
   if p[1] == "":
       for line in p[0]:
           vote = float(line) / sum(p[0])
           normal.append(vote)
       while len(normal) < n:
           normal.append(0.0)
   return normal

def normalisePapers(ps, n): # for every p on ps, sum(p) > 0
   normalised = []
   for paper in ps:
       normalised.append(normalisePaper(paper, n))
   return normalised

def countVotes(cs, ps): # ps have been normalised for an election with len(cs) candidates
   counts = []
   countedVotes = []
   finalCount = []
   for can in cs:
       counts.append(0.0)
   for index in range(0, len(cs)):
       for page in ps:
           if len(page) > 0:
               counts[index] += page[index]
       countedVotes = []
       countedVotes.append(round(counts[index],2))
       countedVotes.append(cs[index])
       finalCount.append(countedVotes)
   finalCount.sort(reverse = True)
   return finalCount

def printCount(c):
   for result in c:
       print(result[0], result[1])

def main():
   canFile = input("Candidates list filename: ")
   papersFile = input("Ballot papers filename: ")
   candidates = getCandidates(canFile)
   if not candidates == []:
       papers = getPapers(papersFile, len(candidates))
       numberOfVotes = len(papers)
       if not papers == []:
           papers = normalisePapers(papers, len(candidates))
           votes = countVotes(candidates, papers)
           print("Nerdvanian election 2014 ")
           print("There were", numberOfVotes-len(votes), "informal votes")
           print("There were", len(papers), "formal votes ")
           printCount(votes)

main()


candidates.txt

Major Clanger
Soup Dragon
Froglet

Iron Chicken
The Cloud

smallfile.txt

1,2, 3, 4

, 23,
9,-8
these people!
4,    ,4,4
5,5,,5,5

results.txt

Nerdvanian election 2014

There were 43 informal votes
There were 250 formal votes

61.99 Soup Dragon
57.09 Froglet
50.52 Major Clanger
42.40 Iron Chicken
37.99 The Cloud

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote