Python Exam Help
datecheck.py
#!/usr/local/bin/python3 import re matcher = re.compile(r"^(0[1-9]|1[0-2])/(0[1-9]|[12][0-9]|3[01])/(19[0-9]{2}|20(?: 0[0-9]|1[0-8])|[0-9]{2})$") m = matcher.search("11/31/02") if m : print("Date = ", m.group(0), "Month = ", m.group(1), "Day = ", m.group(2), "Year = ", m.group(3)) else : print("Invalid date")
Election/electresults2.py
#!/usr/local/bin/python3 electfile = "electoral.txt" votefile = "vote.txt" elect = open(electfile,"r") electoraldata = elect.readlines() elect.close() vote = open(votefile,"r") votedata = vote.readlines() vote.close() stateinfo = {} for index in range(0, len(electoraldata)) : data = electoraldata[index].split() stateinfo[data[0]] = [int(data[1])] for index in range(0, len(votedata)) : data = votedata[index].split(",") stateinfo[data[0]].extend([int(data[1]), int(data[2])]) cand1votes = 0 cand2votes = 0 cand1electors = 0 cand2electors = 0 for statename in stateinfo.keys() : cand1votes += stateinfo[statename][1] cand2votes += stateinfo[statename][2] if stateinfo[statename][1] > stateinfo[statename][2] : cand1electors += stateinfo[statename][0] else : cand2electors += stateinfo[statename][0] print("Popular vote results:") if cand1votes > cand2votes : print("Candidate 1 wins: ", cand1votes, " -- ", cand2votes) else : print("Candidate 2 wins: ", cand2votes, " -- ", cand1votes) print("Electoral college results:") if cand1electors > cand2electors : print("Candidate 1 wins: ", cand1electors, " -- ", cand2electors) else : print("Candidate 2 wins: ", cand2electors, " -- ", cand1electors)
Election/makeelection.py
#!/usr/local/bin/python3 import random import math NUMSTATES = 72 electfile = "electoral.txt" votefile = "vote.txt" def makenames (num) : statenames = [] for index in range(1, num+1) : name = "State" + str(index) statenames.append(name) return statenames def makepops (num) : populations = [] for index in range(0, num) : pop = random.randint(50000,50000000) populations.append(pop) return populations def makeelectorals (pops) : electorals = [] for pop in pops : elect = math.ceil(0.00001 * pop) electorals.append(elect) return electorals def makeelectfile (names,electors,filename=electfile) : outfile = open(filename, "w") for index in range(0,NUMSTATES) : outfile.write(names[index] + " " + str(electors[index]) + "\n") outfile.close() def makevotes (pops) : votes = [] for pop in pops : voters = pop * random.uniform(0.4, 0.6) perc = random.uniform(0,1) votes.append((math.ceil(voters*perc), math.floor(voters*(1-perc)))) return votes def makevotefile (states, votes, filename=votefile) : states.reverse() votes.reverse() outfile = open(filename, "w") for index in range(0, NUMSTATES) : outfile.write(states[index] + "," + str(votes[index][0]) + "," + str(votes[index][1]) + "\n") outfile.close() states = makenames(NUMSTATES) people = makepops(NUMSTATES) people.sort() electreps = makeelectorals(people) makeelectfile(states, electreps) candvotes = makevotes(people) makevotefile(states, candvotes)
form previous term.jpg
marketing.py
#!/usr/local/bin/python3 import random receipts = [] for index in range(0,1000) : receipts.append([index,random.randint(0,1),random.randint(0,1),random.randint(0,1),random.randint(0,1), random.randint(0,1)]) sets = [set(),set(),set(),set(),set()] for index in range(0,1000) : for index1 in range(0,5) : if receipts[index][index1+1] == 1 : sets[index1].add(receipts[index][0]) everybody = set() for index in range(0,1000) : everybody.add(receipts[index][0]) bums = everybody - sets[0] - sets[1] - sets[2] - sets[3] - sets[4] numbums = len(bums) print("There are", numbums, "bums: ", bums) bums = everybody - (sets[0] | sets[1] | sets[2] | sets[3] | sets[4]) numbums = len(bums) print("There are", numbums, "bums: ", bums) maxitem = 0 maxindex = 0 for index in range(0,5) : if len(sets[index]) > maxitem : maxitem = len(sets[index]) maxindex = index print("The most popular product is #", maxindex, "because", maxitem, "people bought it.") maxpop = maxindex maxitem = 0 maxindex = 0 for index in range(0,5) : if index != maxpop : if len(sets[index] & sets[maxpop]) > maxitem : maxitem = len(sets[index] & sets[maxpop]) maxindex = index print("The most popular product bought with item #", maxpop, "was #", maxindex, "because", maxitem, "people bought them.") maxitem = 0 maxindex = 0 for index1 in range(0,4) : for index2 in range(index1+1,5) : if len(sets[index1] & sets[index2]) > maxitem : maxitem = len(sets[index1] & sets[index2]) maxindex = (index1,index2) print("The most popular product pairing is #", maxindex[0], "and #", maxindex[1], "because", maxitem, "people bought them.")
prettyprint.py
#!/usr/local/bin/python3 import sys import os import os.path as osp import time def printdir1 (currentdir, level) : try : things = os.listdir(currentdir) except PermissionError : print("\t" * level, "You do not have permission to access the directory ", currentdir) return files = [] subdirs = [] for thing in things : if osp.isdir(osp.join(currentdir,thing)) : subdirs.append(thing) else : files.append(thing) files.sort() for file in files : print("\t" * level, file) subdirs.sort() for subdir in subdirs : print("\t" * level, osp.join(currentdir,subdir)) printdir1(osp.join(currentdir,subdir),level+1) def printdir2 (currentdir, level) : #print(os.getcwd()) try : os.chdir(currentdir) except PermissionError : print("\t" * level, "You do not have permission to enter the directory ", currentdir) return try : things = os.listdir(".") except PermissionError : print("\t" * level, "You do not have permission to read the directory ", currentdir) os.chdir("..") return files = [] subdirs = [] links = [] for thing in things : if osp.islink(thing) : links.append(thing) elif osp.isdir(thing) : subdirs.append(thing) else : files.append(thing) files.sort() for file in files : print("\t" * level, file) links.sort() for link in links : print("\t" * level, link, " - not exploring") subdirs.sort() for subdir in subdirs : print("\t" * level, osp.join(currentdir,subdir)) printdir2(subdir,level+1) os.chdir("..") def getrwx (filename) : if os.access(filename, os.R_OK) : rwx = "r" else : rwx = "-" if os.access(filename, os.W_OK) : rwx += "w" else : rwx += "-" if os.access(filename, os.X_OK) : rwx += "x" else : rwx += "-" return rwx def printdir3 (currentdir) : for currentpath, dirs, files in os.walk(currentdir) : level = currentpath.count("/") print("\t" * level, currentpath) for file in files : size = osp.getsize(osp.join(currentpath,file)) mtime = osp.getmtime(osp.join(currentpath, file)) fancytime = time.strftime("%H:%M:%S %m/%d/%y", time.localtime(mtime)) perms = getrwx(osp.join(currentpath,file)) print("\t" * (level+1), file, " size = ", size, "time = ", fancytime, "permissions =", perms) #time.ctime(mtime)) if len(sys.argv) == 1 : print("You are an idiot, supply a directory name.") elif len(sys.argv) > 2 : print("You can't count, supply only one directory name.") else : dirname = sys.argv[1] if not osp.exists(dirname) : print("The file ", dirname, "does not exist. Try again.") elif not osp.isdir(dirname) : print("The name ", dirname, "corresponds to a file, not a directory. Try again.") else : try : things = os.listdir(dirname) except PermissionError : print("You do not have permission to access the directory ", dirname) sys.exit() #printdir1(dirname, 0) #printdir2(dirname, 0) printdir3(dirname)
Summary.docx
Encryption and decryption (tcrypt.py) :
We then discussed the next program we would write, doing transpositional encryption of a string based on a keyword. We discussed how we could using a list of nested lists as a basic structure to hold the letters of the original message as we worked on the rearrangement, which was a basic concatenation of the elements in this list based on an ordering determined from the keyword. This ordering will also be most easily determined by converting the keyword into a list, using the list() type conversion, then sorting the characters to determine their alphabetical ordering. We will write the actual program to do this next time.
Today we wrote the columnar transpositional encryption program based on the algorithm we discussed last class. The program is given above. During the process we encountered a few things worth noting. The first involved using the replication operation, *, to try and make a list of empty lists by replicating a list containing one empty list. Rather than creating separate empty lists at each location, a set of references to one empty list were generated, similar to a shallow copy operation. Instead we needed to write a simple loop that would append an appropriate number of empty lists instead. The second involved converting a list to a string. When using the string type conversion, str(), we don't get exactly what we want. Instead we get a displayable version of the list, exactly what the print function displays. To merge the elements of the list together into one string, the join() method must be used. The syntax was a little tricky, in that the method is called from the string representing the fill character that would be placed between each character in the list.
After we finished the encryption program, we discussed how a decryption process would work, essentially by extracting substrings from the encrypted string and placing them back into the columns of the table we took them from during encryption. Then we can simply read out the rows of the table to get the original string. We just got started on trying to code this. We will finish it next time and move onto additional topics.
We started the day by working on completing the decryption part of our program. The final version is given above. In order to do this we did not need to introduce any new functionality. We had to do various index calculations to determine where each appropriate length substring in the encrypted string would be and what column in the final table it should be placed in based on the keyword. Then a final loop was used to merge together all of the characters in the list of lists into the original message
Election:
We then started the program that would analyze these data files to determine the winner of the election. The data from each file was read in and converted to lists of lists, where each sublist represented one state's information. We then computed the winner of the popular vote by simply adding up all of the individual state votes and printing out a winner. Next time we will finish the program by computing the electoral college winner. The current version of the second program is given above as well.
We started the day by finishing the election program we wrote last week. In order to compute the winner of the election by counting electoral representatives, we had to determine each state's winner from the data in one list, and then look up the number of electoral representatives for that state in the other list and add it to the appropriate sum. This final version is given above. We noted that doing the search through the other list for each state was somewhat inefficient. One potential solution was to merge the data from the two lists, but even that would require a certain amount of searching. Another potential solution is to use a different data structure, namely a dictionary.
tcrypt(1).py
#!/usr/local/bin/python3 import math message = input("Please enter the message to encrypt: ") keyword = input("Please enter the keyword: ") keylength = len(keyword) # outlist = [[]] * keylength outlist = [] for i in range(0,keylength): outlist.append([]) ind = 0 for letter in message : col = ind % keylength outlist[col].append(letter) ind += 1 keylist = list(keyword) keylist.sort() #print(keylist) encryptlist = [] for keyletter in keyword : keyind = keylist.index(keyletter) encryptlist.extend(outlist[keyind]) #print(encryptlist) #encryptstr = "" #for letter in encryptlist : # encryptstr += letter encryptstr = "".join(encryptlist) print("The encrypted version is: ", encryptstr) outlist = [] for i in range(0,keylength): outlist.append([]) numrows = len(encryptstr) / keylength numrows = math.ceil(numrows) fullcols = len(encryptstr) % keylength if fullcols == 0 : fullcols = keylength begslice = 0 for index in range(0,keylength) : keyletter = keyword[index] keyindex = keylist.index(keyletter) if keyindex >= fullcols : lenslice = numrows - 1 else : lenslice = numrows colslice = encryptstr[begslice:begslice+lenslice] begslice += lenslice outlist[keyindex] = list(colslice) outstr = "" for index in range(0,len(encryptstr)): row = index // keylength col = index % keylength outstr += outlist[col][row] print("Decrypted string is: ", outstr)