Skip to content

Instantly share code, notes, and snippets.

@Hydrotoast
Created August 31, 2013 05:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hydrotoast/6396408 to your computer and use it in GitHub Desktop.
Save Hydrotoast/6396408 to your computer and use it in GitHub Desktop.
# reachability.py
# Wesley Wu, Lab 1
# Bohyun Kim, Lab 1
# We certify that we worked cooperatively on this programming
# assignment, according to the rules for pair programming
import prompt
def read_graph(filename):
adict = {}
file = open(filename)
for line in file:
adict.update({line[:line.find(';')]:[]})
file = open(filename)
for line in file:
adict[line[:line.find(';')]].append(line[line.find(';')+1:].rstrip())
return adict
def print_graph(filename):
adict = read_graph(filename)
print('Graph: source -> {destination} nodes')
for i in range(len(set(sorted(adict)))):
print(sorted(adict)[i],'->',set(adict[sorted(adict)[i]]))
def reachable(adict,string):
checks = set([])
for i in adict:
for j in range(len(adict[i])):
checks.add(i)
checks.add(adict[i][j])
reachable_nodes = set([])
exploring_list = [string]
while len(exploring_list) != 0:
try:
for i in range(len(adict[exploring_list[0]])):
if adict[exploring_list[0]][i] not in reachable_nodes:
exploring_list.append(adict[exploring_list[0]][i])
reachable_nodes.add(exploring_list.pop(0))
except KeyError:
if exploring_list[0] in checks:
reachable_nodes.add(exploring_list.pop(0))
else:
return 'Error'
return reachable_nodes
filename = prompt.for_string('Enter file name with graph')
while True:
input_node = prompt.for_string('Enter starting node')
if input_node == 'quit':
break
if reachable(read_graph(filename),input_node) == 'Error':
print("Entry error: '",input_node,"'; Not a source node\nPlease enter a legal String",sep="")
else:
print('From '+input_node+' the reachable nodes are',reachable(read_graph(filename),input_node))
# secretary.py
# Wesley Wu, Lab 1
# Bohyun Kim, Lab 1
# We certify that we worked cooperatively on this programming
# assignment, according to the rules for pair programming
import prompt, predicate
from goody import irange
from random import random as gen_preference
from listlib import rank,print_histogram
# define hire_exceed/do_experiment/do_experiments/good_percent here
def hire_exceed(l,f):
for i in range(len(l)):
if l[i] > f:
return l[i]
return l[-1]
def do_experiment(ic,ip):
l = [gen_preference()*1000 for i in range(ic+ip)]
maxgn = max(l[0:ip])
c = hire_exceed(l[ip:],maxgn)
return rank(c,l)
def do_experiments(ncandidate, npreinterview, nexperiment):
list_ = [0]*(ncandidate+npreinterview)
for i in range(nexperiment):
rank = do_experiment(ncandidate,npreinterview)
list_[rank-1] = list_[rank-1] +1
return list_
def good_percent(histogram_,pparameter):
total = 0
sumvalue = sum(histogram_)
for i in range(len(histogram_)):
if pparameter(i):
total += histogram_[i]
return total/sumvalue*100
# define the script here
number_interview = prompt.for_int('Number of candidates in interview(>=10)',100,lambda x : x >= 10)
number_preinterview = prompt.for_int('Number of candidates to pre-interview (>= 1, <100)',20,lambda x : x >= 1 and x < 100 and x < number_interview)
number_experiments = prompt.for_int('Number of experiments to simulate',1000)
histogram = do_experiments(number_interview,number_preinterview,number_experiments)
print_histogram('Rank Hire%',histogram)
goodlambda = eval(prompt.for_string('Enter lambda to define good', 'lambda x : x <= 3'))
print('goodness for above histogram = ',good_percent(histogram,goodlambda),'%',sep='')
print('Results for many good experiments, one set for each different pre-interview number')
new_histogram = []
for i in range(1,number_interview):
new_histogram.append(do_experiments(number_interview,i,number_experiments))
print_histogram('PreI good%',new_histogram)
# dnamaker.py
import prompt
from goody import irange
from listlib import remove
# define overlaps/max_overlap here
def overlaps(upper, lower, n):
return upper[len(upper)-n:len(upper)] == lower[0:n]
def max_overlap(upper, lower):
nlist = [0]
for n in range(len(upper)):
if overlaps(upper,lower,n):
nlist.append(n)
return max(nlist)
'''
def test_max_overlap():
while True:
u = prompt.for_string('\nEnter upper')
l = prompt.for_string('Enter lower')
mo = max_overlap(u,l)
print('overlap='+str(mo), u, (len(u)-mo)*' '+l, sep='\n')
test_max_overlap()
'''
# define read_fragments/choose here
def read_fragments(filename):
list = []
file = open(filename)
for line in file:
list.append(line.rstrip())
return list
def choose(list,min_overlap):
for i in range(len(list)):
for j in range(len(list)):
if max_overlap(list[i],list[j]) >= min_overlap:
return list[i],list[j],max_overlap(list[i],list[j])
return '','',0
#print(choose(['aacc','ccgg','ggtt'],2))
#print(choose(['aacc','ggtt','ccgg'],2))
#print(choose(['ccgg','aacc','ggtt'],2))
#print(choose(['aacc','ccgg','ggtt'],3))
# define assemble here
def assemble(list,min_overlap):
if choose(list,min_overlap) == ('','',0):
return
else:
upper = choose(list,min_overlap)[0]
lower = choose(list,min_overlap)[1]
new = choose(list,min_overlap)[0][:-min_overlap] + choose(list,min_overlap)[1]
if trace:
print("\nassembling with ",len(list)," fragments\n",list,"\nRemoving upper = '",upper,"' and lower = '",lower,"'\nAdding '",new,"'",sep="")
remove(list,lambda x : x == upper)
remove(list,lambda x : x == lower)
list.append(new)
# define script here
file = prompt.for_string('Enter file to process')
min_overlap = prompt.for_int('Enter minimum overlap')
trace = prompt.for_bool('Tracing on?', True)
list = read_fragments(file)
while choose(list,min_overlap) != ('','',0):
assemble(list,min_overlap)
out_file = open('assembled-'+file,'w')
print('\nAssembled with',len(list),'strand(s) remaining')
for i in range(len(list)):
print(list[i])
print(list[i],file=out_file)
print('Answer written into file:','assembled-'+file)
# bag.py
from collections import defaultdict # you can use dict or this
class Bag:
def __init__(self,initial_contents=[]):
#initialize _counts to an empty dictionary
self._counts = defaultdict(int)
def total(self):
#returns the total number of values in the bag
#(counting duplicates)
return sum(self._counts.values())
def unique(self):
#returns the number of unique values in the bag
#(not counting duplicates)
return len(self._counts)
def count(self,v):
#returns how often a value occurs in the bag: 0 if
#not there, or the number of times in _counts dictionary
return self._counts[v] if v in self._counts else 0
def add(self,v):
#add a value to the _counts dictionary
self._counts[v] += 1
def remove(self,v):
#remove a value from the _counts dictionary
#if it is not there, raise a ValueError exception
# with an appropriate message
#if the value in _counts drops to 0, remove that
# value: del d[k] remove key k from dictionary d
if v in self._counts:
self._counts[v] -= 1
if self._counts[v] == 0:
del self._counts[v]
else:
raise ValueError('Bag.remove('+str(v)+'): not in Bag')
def as_list(self):
#returns a list that has all the values in the
# bag: e.g., if the count of a value is 3, that
# value appears 3 times in the list; the order
# in which values appear in the list is unimportant,
# but the same values should appear together
alist = []
for k,v in self._counts.items():
alist = alist + v*[k]
#append alternative to catenation
# for i in range(v):
# alist.append(k)
return alist
def see_dict(self):
return self._counts
if __name__ == '__main__':
print('\nDefining and adding to Bag')
b = Bag()
for v in ['a','b','c','d','b','d','d']:
b.add(v)
print(' added',v,':',b.see_dict())
print('\nTesting queries: total, unique, and count')
print('b.total() =',b.total())
print('b.unique() =',b.unique())
for c in 'abcdx':
print('b.count('+c+') =',b.count(c))
print('\nTesting as_list (values can appear in any order; same values must appear together')
print(b.as_list())
print('\nTesting remove (printing the dictionary')
for v in ['a', 'b', 'b', 'c', 'd', 'd', 'd']:
b.remove(v)
print(' removed',v,':',b.see_dict())
print('removing non existent value from dict; should raise exception')
b.remove('a')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment