text
stringlengths
0
1.05M
meta
dict
# 6.00.2x Problem Set 4 import numpy import random import pylab from ps3b import * # # PROBLEM 1 # def simulationDelayedTreatment(numTrials): """Runs simulations and make histograms for problem 1. Runs numTrials simulations to show the relationship between delayed treatment and patient outcome using a histogram. Histograms of final total virus populations are displayed for delays of 300, 150, 75, 0 timesteps (followed by an additional 150 timesteps of simulation). numTrials: number of simulation runs to execute (an integer) """ timestep = 300 population = [] numViruses = 100 maxPop = 1000 maxBirthProb = 0.1 clearProb = 0.05 resistances = {'guttagonol': False} mutProb = 0.005 for i in range(timestep): population.insert(i, 0) rsp = [] for i in range(timestep): rsp.insert(i, 0) for nt in range(numTrials): viruses = [] for i in range(numViruses): virus = ResistantVirus(maxBirthProb, clearProb, resistances, mutProb) viruses.append(virus) patient = TreatedPatient(viruses, maxPop) for t in range(timestep/2): population[t] += float(patient.update()) rsp[t] += float(patient.getResistPop(["guttagonol"])) patient.addPrescription("guttagonol") for t in range(timestep/2, timestep): population[t] += float(patient.update()) rsp[t] += float(patient.getResistPop(["guttagonol"])) for i in range(timestep): population[i] = population[i]/numTrials rsp[i] = rsp[i]/numTrials pylab.hist(population, bins=50) pylab.title('Population') pylab.xlabel('Population') pylab.ylabel('Number of trials') pylab.show() simulationDelayedTreatment(20) # # PROBLEM 2 # def simulationTwoDrugsDelayedTreatment(numTrials): """ Runs simulations and make histograms for problem 2. Runs numTrials simulations to show the relationship between administration of multiple drugs and patient outcome. Histograms of final total virus populations are displayed for lag times of 300, 150, 75, 0 timesteps between adding drugs (followed by an additional 150 timesteps of simulation). numTrials: number of simulation runs to execute (an integer) """ # TODO
{ "repo_name": "xqliu/coursera", "path": "6.00.2x_IntroductionToComputationalThinkingAndDataScience/ProblemSet4/ps4.py", "copies": "1", "size": "2382", "license": "mit", "hash": 2855546330917083000, "line_mean": 27.0235294118, "line_max": 78, "alpha_frac": 0.6570109152, "autogenerated": false, "ratio": 3.704510108864697, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48615210240646967, "avg_score": null, "num_lines": null }
# 6.00.2x Problem Set 5 # Graph optimization # # A set of data structures to represent graphs # class Node(object): def __init__(self, name): self.name = str(name) def getName(self): return self.name def __str__(self): return self.name def __repr__(self): return self.name def __eq__(self, other): return self.name == other.name def __ne__(self, other): return not self.__eq__(other) def __hash__(self): # Override the default hash method # Think: Why would we want to do this? return self.name.__hash__() class Edge(object): def __init__(self, src, dest): self.src = src self.dest = dest def getSource(self): return self.src def getDestination(self): return self.dest def __str__(self): return '{0}->{1}'.format(self.src, self.dest) class Digraph(object): """ A directed graph """ def __init__(self): # A Python Set is basically a list that doesn't allow duplicates. # Entries into a set must be hashable (where have we seen this before?) # Because it is backed by a hashtable, lookups are O(1) as opposed to the O(n) of a list (nifty!) # See http://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset self.nodes = set([]) self.edges = {} def addNode(self, node): if node in self.nodes: # Even though self.nodes is a Set, we want to do this to make sure we # don't add a duplicate entry for the same node in the self.edges list. raise ValueError('Duplicate node') else: self.nodes.add(node) self.edges[node] = [] def addEdge(self, edge): src = edge.getSource() dest = edge.getDestination() if not(src in self.nodes and dest in self.nodes): raise ValueError('Node not in graph') self.edges[src].append(dest) def childrenOf(self, node): return self.edges[node] def hasNode(self, node): return node in self.nodes def __str__(self): res = '' for k in self.edges: for d in self.edges[k]: res = '{0}{1}->{2}\n'.format(res, k, d) return res[:-1] class WeightedEdge(Edge): def __init__(self, src, dest, totDistance, outDistance): Edge.__init__(self, src, dest) self.totDist = totDistance self.outDist = outDistance def getTotalDistance(self): return self.totDist def getOutdoorDistance(self): return self.outDist def __str__(self): return Edge.__str__(self) + " ({0}, {1})".format(self.totDist,self.outDist) class WeightedDigraph(Digraph): def addEdge(self, edge): src = edge.getSource() dest = edge.getDestination() totDist = float(edge.getTotalDistance()) outDist = float(edge.getOutdoorDistance()) if not(src in self.nodes and dest in self.nodes): raise ValueError('Node not in graph') self.edges[src].append([dest , (totDist, outDist)]) def childrenOf(self, node): childList = [] for entry in self.edges[node]: childList.append(entry[0]) return childList def hasNode(self, node): return node in self.nodes def __str__(self): res = '' for k in self.edges: for d in self.edges[k]: res = '{0}{1}->{2} ({3}, {4})\n'.format(res, k, d[0], d[1][0], d[1][1]) return res[:-1] def printPath(path): # a path is a list of nodes result = '' for i in range(len(path)): if i == len(path) - 1: result = result + str(path[i]) else: result = result + str(path[i]) + '->' return result #Test #na = Node('a') #nb = Node('b') #nc = Node('c') #e1 = WeightedEdge(na, nb, 15, 10) ##print e1 ##print e1.getTotalDistance() ##print e1.getOutdoorDistance() #e2 = WeightedEdge(na, nc, 14, 6) #e3 = WeightedEdge(nb, nc, 3, 1) ##print e2 ##print e3 # #g = WeightedDigraph() #g.addNode(na) #g.addNode(nb) #g.addNode(nc) #g.addEdge(e1) #g.addEdge(e2) #g.addEdge(e3) #print g # Testcase Grader #nh = Node('h') #nj = Node('j') #nk = Node('k') #nm = Node('m') #ng = Node('g') #g = WeightedDigraph() #g.addNode(nh) #g.addNode(nj) #g.addNode(nk) #g.addNode(nm) #g.addNode(ng) #randomEdge = WeightedEdge(nm, nh, 90, 55) #g.addEdge(randomEdge) #randomEdge = WeightedEdge(nk, nj, 43, 34) #g.addEdge(randomEdge) #randomEdge = WeightedEdge(nk, nm, 11, 11) #g.addEdge(randomEdge) #randomEdge = WeightedEdge(nj, nk, 67, 47) #g.addEdge(randomEdge) #randomEdge = WeightedEdge(nj, nm, 86, 77) #g.addEdge(randomEdge) #randomEdge = WeightedEdge(nh, nm, 57, 19) #g.addEdge(randomEdge) #randomEdge = WeightedEdge(nh, nj, 81, 63) #g.addEdge(randomEdge) #randomEdge = WeightedEdge(nm, nk, 54, 46) #g.addEdge(randomEdge) #print g.childrenOf(nh)#: [m, j] #print g.childrenOf(nj)#: [[k, (67.0, 47.0)], [m, (86.0, 77.0)]] #print g.childrenOf(nk)#: [[j, (43.0, 34.0)], [m, (11.0, 11.0)]] #print g.childrenOf(nm)#: [[h, (90.0, 55.0)], [k, (54.0, 46.0)]] #print g.childrenOf(ng)#: []
{ "repo_name": "parmarmanojkumar/MITx_Python", "path": "6002x/week5/ProblemSet5/graph.py", "copies": "1", "size": "5161", "license": "mit", "hash": 708466740412439900, "line_mean": 28.838150289, "line_max": 105, "alpha_frac": 0.5851579151, "autogenerated": false, "ratio": 3.0793556085918854, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9055815134007851, "avg_score": 0.021739677936806978, "num_lines": 173 }
# 6.00 Problem Set 10 # Graph optimization # # A set of data structures to represent graphs # class Node(object): def __init__(self, name): self.name = str(name) def getName(self): return self.name def __str__(self): return self.name def __repr__(self): return self.name def __eq__(self, other): return self.name == other.name def __ne__(self, other): return not self.__eq__(other) class Edge(object): def __init__(self, src, dest): self.src = src self.dest = dest def getSource(self): return self.src def getDestination(self): return self.dest def __str__(self): return '%s->%s' % (str(self.src), str(self.dest)) class Digraph(object): """ A directed graph """ def __init__(self): self.nodes = set([]) self.edges = {} def addNode(self, node): if node in self.nodes: raise ValueError('Duplicate node') else: self.nodes.add(node) self.edges[node] = [] def addEdge(self, edge): src = edge.getSource() dest = edge.getDestination() if not(src in self.nodes and dest in self.nodes): raise ValueError('Node not in graph') self.edges[src].append(dest) def childrenOf(self, node): return self.edges[node] def hasNode(self, node): return node in self.nodes def __str__(self): res = '' for k in self.edges: for d in self.edges[str(k)]: res = '%s%s->%s\n' % (res, str(k), str(d)) return res[:-1]
{ "repo_name": "juampi/6.00x", "path": "ProblemSet10/graph.py", "copies": "1", "size": "1632", "license": "mit", "hash": 6502726002925922000, "line_mean": 26.2, "line_max": 58, "alpha_frac": 0.5379901961, "autogenerated": false, "ratio": 3.7006802721088436, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9689832543421237, "avg_score": 0.00976758495752124, "num_lines": 60 }
# 6.00 Problem Set 11 # # graph.py # # A set of data structures to represent graphs # BAD_EDGE_MSG = "Total distance outdoors cannot exceed the total "+\ "distance of the route" class Node(object): def __init__(self, name): self.name = str(name) def getName(self): return self.name def __str__(self): return self.name def __repr__(self): return self.name def __eq__(self, other): return self.name == other.name def __ne__(self, other): return not self.__eq__(other) class Edge(object): def __init__(self, src, dest): self.src = src self.dest = dest def getSource(self): return self.src def getDestination(self): return self.dest def reverse(self): return Edge(self, self.dest, self.src) def __str__(self): return str(self.src) + '->' + str(self.dest) class Route(Edge): def __init__(self, src, dest, total_dist, dist_outdoors): self.src = src self.dest = dest if dist_outdoors > total_dist: raise ValueError(BAD_EDGE_MSG) self.total_dist = total_dist self.dist_outdoors = dist_outdoors class Digraph(object): """ A directed graph """ def __init__(self): self.nodes = set([]) self.edges = {} def addNode(self, node): if node in self.nodes: raise ValueError('Duplicate node') else: self.nodes.add(node) self.edges[node] = [] def addEdge(self, edge): src = edge.getSource() dest = edge.getDestination() if not(src in self.nodes and dest in self.nodes): raise ValueError('Node not in graph') self.edges[src].append(dest) def childrenOf(self, node): print 'Parameter type:', type(node) print 'Key type:', type(self.edges.keys()[0]) print 'Node in keys:', node in self.edges.keys() return self.edges[node] def hasNode(self, node): return node in self.nodes def __str__(self): res = '' for k in self.edges: for d in self.edges[k]: res = res + str(k) + '->' + str(d) + '\n' return res[:-1] class Graph(Digraph): """ A graph with both directed and bidirectional edges. """ def addBidirectionalEdge(self, edge): super(Graph, self).addEdge(edge) super(Graph, self).addEdge(edge.reverse())
{ "repo_name": "downpat/mit-6000", "path": "problem-set-11/graph.py", "copies": "1", "size": "2412", "license": "mit", "hash": 7537011258384121000, "line_mean": 26.724137931, "line_max": 67, "alpha_frac": 0.5733830846, "autogenerated": false, "ratio": 3.5892857142857144, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4662668798885714, "avg_score": null, "num_lines": null }
# 6.00 Problem Set 2 # # Hangman # Name : Solutions # Collaborators : <your collaborators> # Time spent : <total time> # ----------------------------------- # Helper code # You don't need to understand this helper code, # but you will have to know how to use the functions import random import string WORDLIST_FILENAME = "words.txt" def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # line: string line = inFile.readline() # wordlist: list of strings wordlist = string.split(line) print " ", len(wordlist), "words loaded." return wordlist def choose_word(wordlist): """ wordlist (list): list of words (strings) Returns a word from wordlist at random """ return random.choice(wordlist) # end of helper code # ----------------------------------- # load the list of words into the wordlist variable # so that it can be accessed from anywhere in the program wordlist = load_words() def partial_word(secret_word, guessed_letters): """ Return the secret_word in user-visible format, with underscores used to replace characters that have not yet been guessed. """ result = '' for letter in secret_word: if letter in guessed_letters: result = result + letter else: result = result + '_' return result def hangman(): """ Runs the hangman game. """ print 'Welcome to the game, Hangman!' secret_word = choose_word(wordlist) print 'I am thinking of a word that is ' + str(len(secret_word)) + ' letters long.' num_guesses = 8 word_guessed = False guessed_letters = '' available_letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] # Letter-guessing loop. Ask the user to guess a letter and respond to the # user based on whether the word has yet been correctly guessed. while num_guesses > 0 and not word_guessed: print '-------------' print 'You have ' + str(num_guesses) + ' guesses left.' print 'Available letters: ' + ''.join(available_letters) guess = raw_input('Please guess a letter:') if guess not in available_letters: print 'Oops! You\'ve already guessed that letter: ' + partial_word(secret_word, guessed_letters) elif guess not in secret_word: num_guesses -= 1 available_letters.remove(guess) print 'Oops! That letter is not in my word: ' + partial_word(secret_word, guessed_letters) else: available_letters.remove(guess) guessed_letters += guess print 'Good guess: ' + partial_word(secret_word, guessed_letters) if secret_word == partial_word(secret_word, guessed_letters): word_guessed = True if word_guessed: print 'Congratulations, you won!' else: print 'Game over.'
{ "repo_name": "marioluan/mit-opencourseware-cs", "path": "600/unit-1/recursion/problem-set/mit-solutions/ps2_hangman_sol1.py", "copies": "1", "size": "3242", "license": "mit", "hash": -1535458611875630300, "line_mean": 31.7474747475, "line_max": 108, "alpha_frac": 0.5909932141, "autogenerated": false, "ratio": 3.7566628041714947, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48476560182714945, "avg_score": null, "num_lines": null }
# 6.00 Problem Set 2 # # Successive Approximation: Newton's Method # # Name : Solutions # Collaborators : <your collaborators> # Time spent : <total time> # def evaluate_poly(poly, x): """ Computes the value of a polynomial function at given value x. Returns that value. Example: >>> poly = [0.0, 0.0, 5.0, 9.3, 7.0] # f(x) = 5x^2 + 9.3x^3 + 7x^4 >>> x = -13 >>> print evaluate_poly(poly, x) # f(-13) = 5(-13)^2 + 9.3(-13)^3 + 7(-13)^4 180339.9 poly: list of numbers, length > 0 x: number returns: float """ total = 0.0 for i in xrange(len(poly)): total += poly[i] * (x ** i) return total def compute_deriv(poly): """ Computes and returns the derivative of a polynomial function. If the derivative is 0, returns [0.0]. Example: >>> poly = [-13.39, 0.0, 17.5, 3.0, 1.0] # - 13.39 + 17.5x^2 + 3x^3 + x^4 >>> print compute_deriv(poly) # 35^x + 9x^2 + 4x^3 [0.0, 35.0, 9.0, 4.0] poly: list of numbers, length > 0 returns: list of numbers """ poly_deriv = [] if len(poly) < 2: return [0.0] for j in xrange(1, len(poly)): poly_deriv.append(float(j * poly[j])) return poly_deriv def compute_root(poly, x_0, epsilon): """ Uses Newton's method to find and return a root of a polynomial function. Returns a list containing the root and the number of iterations required to get to the root. Example: >>> poly = [-13.39, 0.0, 17.5, 3.0, 1.0] # - 13.39 + 17.5x^2 + 3x^3 + x^4 >>> x_0 = 0.1 >>> epsilon = .0001 >>> print compute_root(poly, x_0, epsilon) [0.80679075379635201, 8] poly: list of numbers, length > 1. Represents a polynomialfunction containing at least one real root. The derivative of this polynomial function at x_0 is not 0. x_0: float epsilon: float > 0 returns: list [float, int] """ root = x_0 counter = 1 while abs(evaluate_poly(poly, root)) >= epsilon: root = (root - evaluate_poly(poly, root) / evaluate_poly(compute_deriv(poly), root)) counter += 1 return [root, counter]
{ "repo_name": "marioluan/mit-opencourseware-cs", "path": "600/unit-1/recursion/problem-set/mit-solutions/ps2_newton_sol1.py", "copies": "1", "size": "2193", "license": "mit", "hash": 644374723076951300, "line_mean": 27.4805194805, "line_max": 85, "alpha_frac": 0.5649794802, "autogenerated": false, "ratio": 3.0628491620111733, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4127828642211173, "avg_score": null, "num_lines": null }
# 6.00 Problem Set 2 # # Successive Approximation # def evaluate_poly(poly, x): """ Computes the polynomial function for a given value x. Returns that value. Example: >>> poly = (0.0, 0.0, 5.0, 9.3, 7.0) # f(x) = 7x^4 + 9.3x^3 + 5x^2 >>> x = -13 >>> print evaluate_poly(poly, x) # f(-13) = 7(-13)^4 + 9.3(-13)^3 + 5(-13)^2 180339.9 poly: tuple of numbers, length > 0 x: number returns: float """ len_poly = len(poly) if len_poly > 0: exponent = len_poly-1 # useful for debugging # print poly[-1], '*', x, '**', exponent, '=', poly[-1]*x**exponent return poly[-1]*x**exponent + evaluate_poly(poly[:-1], x) else: return 0.0 # poly = (0.0, 0.0, 5.0, 9.3, 7.0) # x = -13 # poly_of_x = evaluate_poly(poly, x) # print poly_of_x def compute_deriv(poly): """ Computes and returns the derivative of a polynomial function. If the derivative is 0, returns (0.0,). Example: >>> poly = (-13.39, 0.0, 17.5, 3.0, 1.0) # x^4 + 3x^3 + 17.5x^2 - 13.39 >>> print compute_deriv(poly) # 4x^3 + 9x^2 + 35^x (0.0, 35.0, 9.0, 4.0) poly: tuple of numbers, length > 0 returns: tuple of numbers """ len_poly = len(poly) if len_poly > 0 and len_poly > 1: exponent = len_poly-1 return compute_deriv(poly[:-1]) + (exponent*poly[-1],) else: return () # poly = (-13.39, 0.0, 17.5, 3.0, 1.0) # print compute_deriv(poly) def compute_root(poly, x, epsilon, iterations): """ Uses Newton's method to find and return a root of a polynomial function. Returns a tuple containing the root and the number of iterations required to get to the root. Formula: # Xn+1 = Xn - f(Xn)/f'(Xn) Example: >>> poly = (-13.39, 0.0, 17.5, 3.0, 1.0) #x^4 + 3x^3 + 17.5x^2 - 13.39 >>> x_0 = 0.1 >>> epsilon = .0001 >>> print compute_root(poly, x_0, epsilon) (0.80679075379635201, 8.0) poly: tuple of numbers, length > 1. Represents a polynomial function containing at least one real root. The derivative of this polynomial function at x_0 is not 0. x_0: float epsilon: float > 0 returns: tuple (float, int) """ iterations+=1 len_poly = len(poly) if len_poly > 1: fx = evaluate_poly(poly, x) if fx == 0: return x, iterations else: if abs(fx) < epsilon: return x, iterations else: fxx = evaluate_poly(compute_deriv(poly), x) x = x - fx / fxx return compute_root(poly, x, epsilon, iterations) # poly = (-13.39, 0.0, 17.5, 3.0, 1.0) # x = 0.1 # epsilon = .0001 # iterations = 0 # print compute_root(poly, x, epsilon, iterations)
{ "repo_name": "marioluan/mit-opencourseware-cs", "path": "600/unit-1/recursion/problem-set/ps2_newton.py", "copies": "1", "size": "2798", "license": "mit", "hash": -2008098361653459200, "line_mean": 26.1747572816, "line_max": 81, "alpha_frac": 0.5446747677, "autogenerated": false, "ratio": 2.9989281886387995, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.40436029563388, "avg_score": null, "num_lines": null }
# 6.00 Problem Set 2 # # Successive Approximation # def evaluate_poly(poly, x): """ Computes the polynomial function for a given value x. Returns that value. Example: >>> poly = (0.0, 0.0, 5.0, 9.3, 7.0) # f(x) = 7x^4 + 9.3x^3 + 5x^2 >>> x = -13 >>> print evaluate_poly(poly, x) # f(-13) = 7(-13)^4 + 9.3(-13)^3 + 5(-13)^2 180339.9 poly: tuple of numbers, length > 0 x: number returns: float """ sum = 0 for i in range(0, len(poly)): # print "i: ", i # print "x: ", x # print "coefficient: ", poly[i] sum += poly[i]*(x**i) # print "sum: ", sum return sum def compute_deriv(poly): """ Computes and returns the derivative of a polynomial function. If the derivative is 0, returns (0.0,). Example: >>> poly = (-13.39, 0.0, 17.5, 3.0, 1.0) # x^4 + 3x^3 + 17.5x^2 - 13.39 >>> print compute_deriv(poly) # 4x^3 + 9x^2 + 35^x (0.0, 35.0, 9.0, 4.0) poly: tuple of numbers, length > 0 returns: tuple of numbers """ derivative = [] for i in range(0, len(poly)): if i == 0: 1 else: derivative.append(i*(poly[i])) return tuple(derivative) def compute_root(poly, x_0, epsilon): """ Uses Newton's method to find and return a root of a polynomial function. Returns a tuple containing the root and the number of iterations required to get to the root. Example: >>> poly = (-13.39, 0.0, 17.5, 3.0, 1.0) #x^4 + 3x^3 + 17.5x^2 - 13.39 >>> x_0 = 0.1 >>> epsilon = .0001 >>> print compute_root(poly, x_0, epsilon) (0.80679075379635201, 8.0) poly: tuple of numbers, length > 1. Represents a polynomial function containing at least one real root. The derivative of this polynomial function at x_0 is not 0. x_0: float epsilon: float > 0 returns: tuple (float, int) """ guesses = 1 guess = x_0 polyval = evaluate_poly(poly, guess) print "guesses: ", guesses print "guess: ", guess print "polyval: ", polyval if abs(polyval) < epsilon: return guess else: while abs(polyval) >= epsilon: deriv = evaluate_poly(compute_deriv(poly), guess) guess = guess - polyval/deriv polyval = evaluate_poly(poly, guess) guesses += 1 print "guesses: ", guesses print "guess: ", guess print "polyval: ", polyval return tuple([guess, guesses])
{ "repo_name": "willcohen/mit-6.00sc-python", "path": "ps2/ps2_newton.py", "copies": "1", "size": "2534", "license": "mit", "hash": -6270430405376733000, "line_mean": 26.8461538462, "line_max": 81, "alpha_frac": 0.5477505919, "autogenerated": false, "ratio": 3.236270753512133, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9283351283766461, "avg_score": 0.00013401232913428035, "num_lines": 91 }
# 6.00 Problem Set 2 # # Hangman # # Name : Solutions # Collaborators : <your collaborators> # Time spent : <total time> # ----------------------------------- # Helper code # (you don't need to understand this helper code) import random import string WORDLIST_FILENAME = "words.txt" def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # line: string line = inFile.readline() # wordlist: list of strings wordlist = string.split(line) print " ", len(wordlist), "words loaded." return wordlist def choose_word(wordlist): """ wordlist (list): list of words (strings) Returns a word from wordlist at random """ return random.choice(wordlist) # end of helper code # ----------------------------------- # actually load the dictionary of words and point to it with # the wordlist variable so that it can be accessed from anywhere # in the program wordlist = load_words() # your code begins here! def hangman(): """Runs the hangman game""" hidden_word = choose_word(wordlist).lower() print "Welcome to the game Hangman!" print "I am thinking of a word that is %d letters long" %(len(hidden_word)) incorrect_guesses = 8 used_letters = {} while(True): print "-----------" print "You have %d guesses left" %(incorrect_guesses) print "Available Letters: " + get_available_letters(used_letters) new_letter = request_letter(hidden_word, used_letters) if new_letter in hidden_word: print "Good guess: " + get_hidden_word(hidden_word, used_letters) else: print "Oops! That letter is not in my word " \ + get_hidden_word(hidden_word, used_letters) incorrect_guesses -= 1 if incorrect_guesses == 0: print "Sorry, you ran out of guesses. The word was " \ + hidden_word + ". Play again!" break print if found_hidden_word(hidden_word, used_letters): print "Congratulations, you won!" break def get_hidden_word(hidden_word, used_letters): """Returns a string of the form __ad___ by filling in correct guesses""" visible_word = "" for letter in hidden_word: if letter in used_letters: visible_word += letter else: if len(visible_word) > 0 and visible_word[-1] == '_': visible_word += " " visible_word += "_" return visible_word def found_hidden_word(hidden_word, used_letters): """Returns True if the word has been completely uncovered""" for letter in hidden_word: if letter not in used_letters: return False return True def get_available_letters(used_letters): """Returns a list of lowercase letters not in used_letters""" available_letters = "" for letter in string.lowercase: if letter not in used_letters: available_letters += letter return available_letters def request_letter(hidden_word, used_letters): """Asks for another guess and returns (gameover, victory) """ new_letter = raw_input("Please guess a letter: ").lower() used_letters[new_letter] = 1 return new_letter hangman()
{ "repo_name": "marioluan/mit-opencourseware-cs", "path": "600/unit-1/recursion/problem-set/mit-solutions/ps2_hangman_sol2.py", "copies": "1", "size": "3608", "license": "mit", "hash": 6292003318839041000, "line_mean": 29.9292035398, "line_max": 79, "alpha_frac": 0.5898004435, "autogenerated": false, "ratio": 3.9691969196919694, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5058997363191969, "avg_score": null, "num_lines": null }
# 6.00 Problem Set 3A # # The 6.00 Word Game # Created by: Kevin Luu <luuk> and Jenna Wiens <jwiens> # # # Problem Set 3a # Name: Marc Laughton # Collaborators: N/A # Time Spent: 4 hours import random import string VOWELS = 'aeiou' CONSONANTS = 'bcdfghjklmnpqrstvwxyz' HAND_SIZE = 7 SCRABBLE_LETTER_VALUES = { 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10 } # ----------------------------------- # Helper code # (you don't need to understand this helper code) WORDLIST_FILENAME = "words.txt" def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # wordlist: list of strings wordlist = [] for line in inFile: wordlist.append(line.strip().lower()) print " ", len(wordlist), "words loaded." return wordlist def get_frequency_dict(sequence): """ Returns a dictionary where the keys are elements of the sequence and the values are integer counts, for the number of times that an element is repeated in the sequence. sequence: string or list return: dictionary """ # freqs: dictionary (element_type -> int) freq = {} for x in sequence: freq[x] = freq.get(x, 0) + 1 return freq # (end of helper code) # ----------------------------------- # # Problem #1: Scoring a word # def get_word_score(word, n): """ Returns the score for a word. Assumes the word is a valid word. The score for a word is the sum of the points for letters in the word multiplied by the length of the word, plus 50 points if all n letters are used on the first go. Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is worth 3, D is worth 2, E is worth 1, and so on. word: string (lowercase letters) returns: int >= 0 """ wordlen = len(word) score = 0 for letter in word: if letter in SCRABBLE_LETTER_VALUES: score += SCRABBLE_LETTER_VALUES[letter] * wordlen if wordlen == n: return score + 50 return score # # Make sure you understand how this function works and what it does! # def display_hand(hand): """ Displays the letters currently in the hand. For example: display_hand({'a':1, 'x':2, 'l':3, 'e':1}) Should print out something like: a x x l l l e The order of the letters is unimportant. hand: dictionary (string -> int) """ for letter in hand.keys(): for j in range(hand[letter]): print letter, # print all on the same line print # print an empty line # # Make sure you understand how this function works and what it does! # def deal_hand(n): """ Returns a random hand containing n lowercase letters. At least n/3 the letters in the hand should be VOWELS. Hands are represented as dictionaries. The keys are letters and the values are the number of times the particular letter is repeated in that hand. n: int >= 0 returns: dictionary (string -> int) """ hand = {} num_vowels = n / 3 for i in range(num_vowels): x = VOWELS[random.randrange(0, len(VOWELS))] hand[x] = hand.get(x, 0) + 1 for i in range(num_vowels, n): x = CONSONANTS[random.randrange(0, len(CONSONANTS))] hand[x] = hand.get(x, 0) + 1 return hand # # Problem #2: Update a hand by removing letters # def update_hand(hand, word): """ Assumes that 'hand' has all the letters in word. In other words, this assumes that however many times a letter appears in 'word', 'hand' has at least as many of that letter in it. Updates the hand: uses up the letters in the given word and returns the new hand, without those letters in it. >> hand = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1} >> display_hand(hand) a q l l m u i >> hand = update_hand(hand, 'quail') >> hand {'l': 1, 'm': 1} >> display_hand(hand) l m Has no side effects: does not modify hand. word: string hand: dictionary (string -> int) returns: dictionary (string -> int) """ _hand = hand.copy() for letter in word: _hand[letter] -= 1 return _hand # Original (I had originally read the specs as detailing a # return value of all k, v pairs with v > 0...tests # pass with the amended version, but would like to # keep both for my own reference): # _hand = {} # word_freq = get_frequency_dict(word) # for k, v in hand.items(): # if k in word_freq: # remaining_count = hand[k] - word_freq[k] # if remaining_count >= 1: # _hand[k] = remaining_count # else: # _hand[k] = hand[k] # return _hand # # Problem #3: Test word validity # def is_valid_word(word, hand, word_list): """ Returns True if word is in the word_list and is entirely composed of letters in the hand. Otherwise, returns False. Does not mutate hand or word_list. word: string hand: dictionary (string -> int) word_list: list of lowercase strings """ if word not in word_list: return False word_freq = get_frequency_dict(word) for k, v in word_freq.items(): # if freq of letter in word is greater # than occurance in hand, return False if v > hand.get(k, 0): return False return True def calculate_handlen(hand): handlen = 0 for v in hand.values(): handlen += v return handlen # # Problem #4: Playing a hand # def play_hand(hand, word_list): """ Allows the user to play the given hand, as follows: * The hand is displayed. * The user may input a word. * An invalid word is rejected, and a message is displayed asking the user to choose another word. * When a valid word is entered, it uses up letters from the hand. * After every valid word: the score for that word is displayed, the remaining letters in the hand are displayed, and the user is asked to input another word. * The sum of the word scores is displayed when the hand finishes. * The hand finishes when there are no more unused letters. The user can also finish playing the hand by inputing a single period (the string '.') instead of a word. hand: dictionary (string -> int) word_list: list of lowercase strings """ len_count = calculate_handlen(hand) score_total = 0 while calculate_handlen(hand) > 0: print 'Current hand: ' display_hand(hand) user_word = raw_input( '''Please enter a word, or type "." to end the game. ''' ) if user_word == '.': print 'Thanks for playing! Total score: {} points'.format( score_total ) return else: is_valid = is_valid_word(user_word, hand, word_list) if is_valid: score = get_word_score(user_word, len_count) hand = update_hand(hand, user_word) score_total += score print 'You\'ve recieved {} point(s) for the word: {}'.format( score, user_word, ) else: print 'Sorry, please select another word!' print 'You\'re out of letters. Total score: {} points.'.format(score_total) # # Problem #5: Playing a game # Make sure you understand how this code works! def play_game(word_list): """ Allow the user to play an arbitrary number of hands. * Asks the user to input 'n' or 'r' or 'e'. * If the user inputs 'n', let the user play a new (random) hand. When done playing the hand, ask the 'n' or 'e' question again. * If the user inputs 'r', let the user play the last hand again. * If the user inputs 'e', exit the game. * If the user inputs anything else, ask them again. """ game_prompt_msg = ''' Please type "n" to start a new game, "r" to replay previous game hand, or "e" to exit the game: >> ''' hand = deal_hand(HAND_SIZE) while True: user_reply_to_game_prompt = raw_input(game_prompt_msg) if user_reply_to_game_prompt == 'e': print 'Sorry to see you go - but, thanks for playing!' return False elif user_reply_to_game_prompt == 'n': print 'Playing a new hand.' hand = deal_hand(HAND_SIZE) play_hand(hand.copy(), word_list) elif user_reply_to_game_prompt == 'r': print 'Now replaying the last hand.' play_hand(hand.copy(), word_list) else: print 'Sorry! Invalid input, please try again.' # # Build data structures used for entire session and play game # if __name__ == '__main__': word_list = load_words() play_game(word_list)
{ "repo_name": "bashhack/MIT_CompSci_Degree", "path": "MIT_600SC/Unit_1/ps3/ps3a.py", "copies": "1", "size": "9349", "license": "mit", "hash": 892256660378017700, "line_mean": 24.3360433604, "line_max": 79, "alpha_frac": 0.5815595251, "autogenerated": false, "ratio": 3.5751434034416825, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4656702928541682, "avg_score": null, "num_lines": null }
# 6.00 Problem Set 3A Solutions # # The 6.00 Word Game # Created by: Kevin Luu <luuk> and Jenna Wiens <jwiens> # # Name : Solutions # Collaborators : <your collaborators> # Time spent : <total time> import random import string VOWELS = 'aeiou' CONSONANTS = 'bcdfghjklmnpqrstvwxyz' HAND_SIZE = 7 SCRABBLE_LETTER_VALUES = { 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10 } # ----------------------------------- # Helper code # (you don't need to understand this helper code) WORDLIST_FILENAME = "words.txt" def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # wordlist: list of strings wordlist = [] for line in inFile: wordlist.append(line.strip().lower()) print " ", len(wordlist), "words loaded." return wordlist def get_frequency_dict(sequence): """ Returns a dictionary where the keys are elements of the sequence and the values are integer counts, for the number of times that an element is repeated in the sequence. sequence: string or list return: dictionary """ # freqs: dictionary (element_type -> int) freq = {} for x in sequence: freq[x] = freq.get(x,0) + 1 return freq # (end of helper code) # ----------------------------------- # # Problem #1: Scoring a word # def get_word_score(word, n): """ Returns the score for a word. Assumes the word is a valid word. The score for a word is the sum of the points for letters in the word, plus 50 points if all n letters are used on the first go. Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is worth 3, D is worth 2, E is worth 1, and so on. word: string (lowercase letters) returns: int >= 0 """ score = 0 for letter in word: score += SCRABBLE_LETTER_VALUES[letter.lower()]*len(word) if len(word) == n: score += 50 return score # # Make sure you understand how this function works and what it does! # def display_hand(hand): """ Displays the letters currently in the hand. For example: display_hand({'a':1, 'x':2, 'l':3, 'e':1}) Should print out something like: a x x l l l e The order of the letters is unimportant. hand: dictionary (string -> int) """ for letter in hand.keys(): for j in range(hand[letter]): print letter, # print all on the same line print # print an empty line # # Make sure you understand how this function works and what it does! # def deal_hand(n): """ Returns a random hand containing n lowercase letters. At least n/3 the letters in the hand should be VOWELS. Hands are represented as dictionaries. The keys are letters and the values are the number of times the particular letter is repeated in that hand. n: int >= 0 returns: dictionary (string -> int) """ hand={} num_vowels = n / 3 for i in range(num_vowels): x = VOWELS[random.randrange(0,len(VOWELS))] hand[x] = hand.get(x, 0) + 1 for i in range(num_vowels, n): x = CONSONANTS[random.randrange(0,len(CONSONANTS))] hand[x] = hand.get(x, 0) + 1 return hand # # Problem #2: Update a hand by removing letters # def update_hand(hand, word): """ Assumes that 'hand' has all the letters in word. In other words, this assumes that however many times a letter appears in 'word', 'hand' has at least as many of that letter in it. Updates the hand: uses up the letters in the given word and returns the new hand, without those letters in it. Has no side effects: does not modify hand. word: string hand: dictionary (string -> int) returns: dictionary (string -> int) """ new_hand = hand.copy() for letter in word: new_hand[letter] -= 1 return new_hand # # Problem #3: Test word validity # def is_valid_word(word, hand, word_list): """ Returns True if word is in the word_list and is entirely composed of letters in the hand. Otherwise, returns False. Does not mutate hand or word_list. word: string hand: dictionary (string -> int) word_list: list of lowercase strings """ if word not in word_list: return False wordFreq = get_frequency_dict(word) for letter in wordFreq.keys(): if wordFreq[letter] > hand.get(letter, 0): return False return True # # Problem #4: Playing a hand # def calculate_handlen(hand): """ Returns the length (number of letters) in the current hand. hand: dictionary (string-> int) returns: integer """ return sum([v for v in hand.values()]) def play_hand(hand, word_list): """ Allows the user to play the given hand, as follows: * The hand is displayed. * The user may input a word. * An invalid word is rejected, and a message is displayed asking the user to choose another word. * When a valid word is entered, it uses up letters from the hand. * After every valid word: the score for that word is displayed, the remaining letters in the hand are displayed, and the user is asked to input another word. * The sum of the word scores is displayed when the hand finishes. * The hand finishes when there are no more unused letters. The user can also finish playing the hand by inputing a single period (the string '.') instead of a word. hand: dictionary (string -> int) word_list: list of lowercase strings """ original_handlen=calculate_handlen(hand) total = 0 while calculate_handlen(hand) > 0: print 'Current Hand:', display_hand(hand) userWord = raw_input('Enter word, or a "." to indicate that you are finished: ') if userWord == '.': print 'Total score: %d points.' % total return else: isValid = is_valid_word(userWord, hand, word_list) if not isValid: print 'That is not a valid word. Please choose another word' else: # if valid point = get_word_score(userWord, original_handlen) # calculate points total += point # add points to total print '"%s" earned %d points. Total: %d points' % (userWord, point, total)# display points and total hand = update_hand(hand, userWord) # update hand print 'Run out of letters. Total score: %d points.' % total # # Problem #5: Playing a game # Make sure you understand how this code works! # def play_game(word_list): """ Allow the user to play an arbitrary number of hands. * Asks the user to input 'n' or 'r' or 'e'. * If the user inputs 'n', let the user play a new (random) hand. When done playing the hand, ask the 'n' or 'e' question again. * If the user inputs 'r', let the user play the last hand again. * If the user inputs 'e', exit the game. * If the user inputs anything else, ask them again. """ # TO DO ... # print "play_game not implemented." # delete this once you've completed Problem #4 # play_hand(deal_hand(HAND_SIZE), word_list) # delete this once you've completed Problem #4 ## uncomment the following block of code once you've completed Problem #4 hand = deal_hand(HAND_SIZE) # random init while True: cmd = raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ') if cmd == 'n': hand = deal_hand(HAND_SIZE) play_hand(hand.copy(), word_list) print elif cmd == 'r': play_hand(hand.copy(), word_list) print elif cmd == 'e': break else: print "Invalid command." # # Build data structures used for entire session and play game # if __name__ == '__main__': word_list = load_words() play_game(word_list)
{ "repo_name": "marioluan/mit-opencourseware-cs", "path": "600/unit-1/debugging/problem-set/ps3asol.py", "copies": "2", "size": "8407", "license": "mit", "hash": -4689418768166067000, "line_mean": 27.7910958904, "line_max": 212, "alpha_frac": 0.6036636137, "autogenerated": false, "ratio": 3.6615853658536586, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.019096059157802055, "num_lines": 292 }
# 6.00 Problem Set 3A Solutions # # The 6.00 Word Game # Created by: Kevin Luu <luuk> and Jenna Wiens <jwiens> # # import random import string VOWELS = 'aeiou' CONSONANTS = 'bcdfghjklmnpqrstvwxyz' HAND_SIZE = 7 SCRABBLE_LETTER_VALUES = { 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10 } # ----------------------------------- # Helper code # (you don't need to understand this helper code) WORDLIST_FILENAME = "words.txt" def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # wordlist: list of strings wordlist = [] for line in inFile: wordlist.append(line.strip().lower()) print " ", len(wordlist), "words loaded." return wordlist def get_frequency_dict(sequence): """ Returns a dictionary where the keys are elements of the sequence and the values are integer counts, for the number of times that an element is repeated in the sequence. sequence: string or list return: dictionary """ # freqs: dictionary (element_type -> int) freq = {} for x in sequence: freq[x] = freq.get(x,0) + 1 return freq # (end of helper code) # ----------------------------------- # # Problem #1: Scoring a word # def get_word_score(word, n): """ Returns the score for a word. Assumes the word is a valid word. The score for a word is the sum of the points for letters in the word multiplied by the length of the word, plus 50 points if all n letters are used on the first go. Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is worth 3, D is worth 2, E is worth 1, and so on. word: string (lowercase letters) returns: int >= 0 """ # TO DO... score = 0 for letter in word: score += SCRABBLE_LETTER_VALUES[letter] bonus = 50 if len(word) == n and score > 0 else 0 return (score * len(word)) + bonus # # Make sure you understand how this function works and what it does! # def display_hand(hand): """ Displays the letters currently in the hand. For example: display_hand({'a':1, 'x':2, 'l':3, 'e':1}) Should print out something like: a x x l l l e The order of the letters is unimportant. hand: dictionary (string -> int) """ for letter in hand.keys(): for j in range(hand[letter]): print letter, # print all on the same line print # print an empty line # # Make sure you understand how this function works and what it does! # def deal_hand(n): """ Returns a random hand containing n lowercase letters. At least n/3 the letters in the hand should be VOWELS. Hands are represented as dictionaries. The keys are letters and the values are the number of times the particular letter is repeated in that hand. n: int >= 0 returns: dictionary (string -> int) """ hand={} num_vowels = n / 3 for i in range(num_vowels): x = VOWELS[random.randrange(0,len(VOWELS))] hand[x] = hand.get(x, 0) + 1 for i in range(num_vowels, n): x = CONSONANTS[random.randrange(0,len(CONSONANTS))] hand[x] = hand.get(x, 0) + 1 return hand # # Problem #2: Update a hand by removing letters # def update_hand(hand, word): """ Assumes that 'hand' has all the letters in word. In other words, this assumes that however many times a letter appears in 'word', 'hand' has at least as many of that letter in it. Updates the hand: uses up the letters in the given word and returns the new hand, without those letters in it. Has no side effects: does not modify hand. word: string hand: dictionary (string -> int) returns: dictionary (string -> int) """ # TO DO ... new_hand = hand.copy() for letter in word: if new_hand[letter]: if new_hand[letter] > 0: new_hand[letter] -= 1 else: del new_hand[letter] return new_hand # # Problem #3: Test word validity # def is_valid_word(word, hand, word_list, skip_word_list_validation = False): """ Returns True if word is in the word_list and is entirely composed of letters in the hand. Otherwise, returns False. Does not mutate hand or word_list. word: string hand: dictionary (string -> int) word_list: list of lowercase strings """ # TO DO... new_hand = hand.copy() word = word.lower() in_word_list = skip_word_list_validation or word in word_list in_hand = True for letter in word: if letter in new_hand and new_hand[letter] > 0: new_hand = update_hand(new_hand, letter) else: in_hand = False return in_word_list and in_hand def calculate_handlen(hand): handlen = 0 for v in hand.values(): handlen += v return handlen # # Problem #4: Playing a hand # def play_hand(hand, word_list): """ Allows the user to play the given hand, as follows: * The hand is displayed. * The user may input a word. * An invalid word is rejected, and a message is displayed asking the user to choose another word. * When a valid word is entered, it uses up letters from the hand. * After every valid word: the score for that word is displayed, the remaining letters in the hand are displayed, and the user is asked to input another word. * The sum of the word scores is displayed when the hand finishes. * The hand finishes when there are no more unused letters. The user can also finish playing the hand by inputing a single period (the string '.') instead of a word. hand: dictionary (string -> int) word_list: list of lowercase strings """ # TO DO ... score = 0 word = "" display_hand(hand) keep_playing = True while keep_playing and len(hand) > 0: word = raw_input("Type a valid word or 'exit' to indicate that you are finished: ") if word == "exit": keep_playing = False elif is_valid_word(word, hand, word_list): word_score = get_word_score(word, HAND_SIZE) print "word score: ", word_score score += word_score print "partial score: ", score hand = update_hand(hand, word) display_hand(hand) print "total score: ", score # # Problem #5: Playing a game # Make sure you understand how this code works! # def play_game(word_list): """ Allow the user to play an arbitrary number of hands. * Asks the user to input 'n' or 'r' or 'e'. * If the user inputs 'n', let the user play a new (random) hand. When done playing the hand, ask the 'n' or 'e' question again. * If the user inputs 'r', let the user play the last hand again. * If the user inputs 'e', exit the game. * If the user inputs anything else, ask them again. """ # TO DO... keep_playing = True hand = None while keep_playing: user_input = raw_input("Choose: 'n' (new hand), 'r' (repeat last hand) or 'e' (exit)\n") if user_input == "n": hand = deal_hand(HAND_SIZE) elif user_input == "r" and hand == None: continue; elif user_input == "e": keep_playing = False break; else: continue; play_hand(hand, word_list) while keep_playing: user_input = raw_input("Choose: 'r' (repeat) or 'e' (exit) \n") if user_input == "r": play_hand(hand, word_list) elif user_input == "e": keep_playing = False else: break; def user_play_game(word_list): play_game(word_list) # # Build data structures used for entire session and play game # if __name__ == '__main__': word_list = load_words() play_game(word_list)
{ "repo_name": "marioluan/mit-opencourseware-cs", "path": "600/unit-1/debugging/problem-set/ps3a.py", "copies": "1", "size": "8309", "license": "mit", "hash": 406862389093253800, "line_mean": 26.1535947712, "line_max": 212, "alpha_frac": 0.5927307739, "autogenerated": false, "ratio": 3.592304366623433, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9670840359534891, "avg_score": 0.002838956197708254, "num_lines": 306 }
# 6.00 Problem Set 3B # # The 6.00 Word Game # Created by: Kevin Luu <luuk> and Jenna Wiens <jwiens> # # # Problem Set 3b # Name: Marc Laughton # Collaborators: N/A # Time Spent: 2 hours 30 minutes from ps3a import * import time from perm import * # # Problem #6A: Computer chooses a word # def comp_choose_word(hand, word_list): """Given a hand and a word_dict, find the word that gives the maximum value score, and return it. This word should be calculated by considering all possible permutations of lengths 1 to HAND_SIZE. hand: dictionary (string -> int) word_list: list (string) """ perms = [] max_score = 0 word_with_max_score = None for length in range(1, HAND_SIZE + 1): perms.extend(get_perms(hand, length)) for word in perms: if word in word_list: curr_score = get_word_score(word, HAND_SIZE) if curr_score > max_score: max_score = curr_score word_with_max_score = word # print 'Word with highest score was \'{}\' and earned {} points'.format( # word_with_max_score, # max_score # ) return word_with_max_score # # Problem #6B: Computer plays a hand # def comp_play_hand(hand, word_list): """ Allows the computer to play the given hand, as follows: * The hand is displayed. * The computer chooses a word using comp_choose_words(hand, word_dict). * After every valid word: the score for that word is displayed, the remaining letters in the hand are displayed, and the computer chooses another word. * The sum of the word scores is displayed when the hand finishes. * The hand finishes when the computer has exhausted its possible choices (i.e. comp_play_hand returns None). hand: dictionary (string -> int) word_list: list (string) """ len_count = calculate_handlen(hand) score_total = 0 while calculate_handlen(hand) > 0: print 'Current hand: ' display_hand(hand) comp_word = comp_choose_word(hand, word_list) if comp_word is None: break else: score = get_word_score(comp_word, len_count) score_total += score hand = update_hand(hand, comp_word) print 'Computer recieved {} point(s) for the word: {}'.format( score, comp_word, ) print 'Computer out of letters. Total score: {} points.'.format( score_total ) # # Problem #6C: Playing a game # def play_game(word_list): """Allow the user to play an arbitrary number of hands. 1) Asks the user to input 'n' or 'r' or 'e'. * If the user inputs 'n', play a new (random) hand. * If the user inputs 'r', play the last hand again. * If the user inputs 'e', exit the game. * If the user inputs anything else, ask them again. 2) Ask the user to input a 'u' or a 'c'. * If the user inputs 'u', let the user play the game as before using play_hand. * If the user inputs 'c', let the computer play the game using comp_play_hand (created above). * If the user inputs anything else, ask them again. 3) After the computer or user has played the hand, repeat from step 1 word_list: list (string) """ game_prompt_msg = ''' Please type "n" to start a new game, "r" to replay previous game hand, or "e" to exit the game: >> ''' player_select_msg = ''' Please type "u" to play the game, or type "c" to let the computer play the game: >> ''' hand = deal_hand(HAND_SIZE) while True: user_cmd = raw_input(game_prompt_msg) while user_cmd != 'n' and user_cmd != 'e' and user_cmd != 'r': print 'Sorry! Invalid input, please try again.' user_cmd = raw_input(game_prompt_msg) if user_cmd == 'e': print 'Sorry to see you go - but, thanks for playing!' return False player = raw_input(player_select_msg) while player != 'u' and player != 'c': print 'Sorry! Invalid input, please try again.' player = raw_input(player_select_msg) if user_cmd == 'n': print 'Playing a new hand.' hand = deal_hand(HAND_SIZE) if user_cmd == 'r': print 'Now replaying the last hand.' if player == 'u': play_hand(hand.copy(), word_list) else: comp_play_hand(hand.copy(), word_list) if player == 'u' and user_cmd != 'r': play_hand(hand.copy(), word_list) elif user_cmd != 'r': comp_play_hand(hand.copy(), word_list) # # Build data structures used for entire session and play game # if __name__ == '__main__': word_list = load_words() play_game(word_list)
{ "repo_name": "bashhack/MIT_CompSci_Degree", "path": "MIT_600SC/Unit_1/ps3/ps3b.py", "copies": "1", "size": "4862", "license": "mit", "hash": 7889581519952670000, "line_mean": 27.1040462428, "line_max": 77, "alpha_frac": 0.5890580008, "autogenerated": false, "ratio": 3.633781763826607, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4722839764626607, "avg_score": null, "num_lines": null }
# 6.00 Problem Set 3B Solutions # # The 6.00 Word Game # Created by: Kevin Luu <luuk> and Jenna Wiens <jwiens> # # Name : Solutions # Collaborators : <your collaborators> # Time spent : <total time> from ps3asol import * import time from perm import * # Problem #6A: Computer chooses a word # # def comp_choose_word(hand, word_list): """ Given a hand and a word_list, find the word that gives the maximum value score, and return it. This word should be calculated by considering all possible permutations of lengths 1 to HAND_SIZE. If all possible permutations are not in word_list, return None. hand: dictionary (string -> int) word_list: list (string) """ # Create an empty list to store all possible permutations of length 1 to HAND_SIZE possibleWords = [] # For all lengths from 1 to HAND_SIZE (including! HAND_SIZE): for length in range(1, HAND_SIZE+1): # Get the permutations of this length perms = get_perms(hand, length) # And store the permutations in the list we initialized earlier # (hint: don't overwrite the list - you want to add to it) possibleWords.extend(perms) # Create a new variable to store the maximum score seen so far (initially 0) maxScore = 0 # Create a new variable to store the best word seen so far (initially None) maxWord = None # For each possible word permutation: for word in possibleWords: # If the permutation is in the word list: if word in word_list: # Get the word's score p_score = get_word_score(word, HAND_SIZE) # If the word's score is larger than the maximum score seen so far: if p_score > maxScore: # Save the current score and the current word as the best found so far maxScore = p_score maxWord = word # return the best word seen return maxWord # # # Problem #6B: Computer plays a hand # # def comp_play_hand(hand, word_list): original_handlen = calculate_handlen(hand) total = 0 while calculate_handlen(hand) > 0: print 'Current Hand:', display_hand(hand) computerWord = comp_choose_word(hand, word_list) if computerWord == None: break else: point = get_word_score(computerWord, original_handlen) # calculate points total += point # add points to total print '"%s" earned %d points. Total: %d points' % (computerWord, point, total)# display points and total hand = update_hand(hand, computerWord) # update hand print 'No more valid words. Total score: %d points.' % total # # Problem #6C: Playing a game # def play_game(word_list): hand = deal_hand(HAND_SIZE) while True: cmd = raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ') while cmd != 'n' and cmd != 'r' and cmd != 'e': print "Invalid command." cmd = raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ') if cmd == 'e': break player = raw_input('Enter u to have yourself play, c to have the computer play: ') while player != 'u' and player != 'c': print "Invalid command." player = raw_input('Enter u to have yourself play, c to have the computer play: ') if cmd == 'n': hand = deal_hand(HAND_SIZE) if player == 'u': play_hand(hand.copy(), word_list) else: comp_play_hand(hand.copy(), word_list) # # Build data structures used for entire session and play game # if __name__ == '__main__': word_list = load_words() play_game(word_list) print "Goodbye!"
{ "repo_name": "jdhaines/MIT6.00", "path": "PS3/ps3_sol/ps3bsol.py", "copies": "2", "size": "3819", "license": "mit", "hash": 6934246732193059000, "line_mean": 29.3095238095, "line_max": 112, "alpha_frac": 0.6103692066, "autogenerated": false, "ratio": 3.7962226640159047, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5406591870615904, "avg_score": null, "num_lines": null }
# 6.00 Problem Set 3 # # Hangman game # # ----------------------------------- # Helper code # You don't need to understand this helper code, # but you will have to know how to use the functions # (so be sure to read the docstrings!) import random import string from string import maketrans WORDLIST_FILENAME = "words.txt" def loadWords(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # line: string line = inFile.readline() # wordlist: list of strings wordlist = string.split(line) print len(wordlist), "words loaded." return wordlist def chooseWord(wordlist): """ wordlist (list): list of words (strings) Returns a word from wordlist at random """ return random.choice(wordlist) # end of helper code # ----------------------------------- # Load the list of words into the variable wordlist # so that it can be accessed from anywhere in the program wordlist = loadWords() def isWordGuessed(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: boolean, True if all the letters of secretWord are in lettersGuessed; False otherwise ''' # FILL IN YOUR CODE HERE... if len(secretWord.translate(None,str(lettersGuessed))) == 0: return True return False def getGuessedWord(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters and underscores that represents what letters in secretWord have been guessed so far. ''' # FILL IN YOUR CODE HERE... invalidGuess = secretWord.translate(None,str(lettersGuessed)) temp = secretWord for letter in invalidGuess: temp = temp.replace(letter,"_ ") return temp def getAvailableLetters(lettersGuessed): ''' lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters that represents what letters have not yet been guessed. ''' # FILL IN YOUR CODE HERE... s = 'abcdefghijklmnopqrstuvwxyz' return s.translate(None,str(lettersGuessed)) def hangman(secretWord): # ''' # secretWord: string, the secret word to guess. # Starts up an interactive game of Hangman. # * At the start of the game, let the user know how many # letters the secretWord contains. # * Ask the user to supply one guess (i.e. letter) per round. # * The user should receive feedback immediately after each guess # about whether their guess appears in the computers word. # * After each round, you should also display to the user the # partially guessed word so far, as well as letters that the # user has not yet guessed. # Follows the other limitations detailed in the problem write-up. # ''' # # FILL IN YOUR CODE HERE... print "Welcome to the game, Hangman!" print "I am thinking of a word that is {0} letters long.".format(len(secretWord)) print "-------------" guessCount = 8 lettersGuessed = [] while guessCount > 0 and isWordGuessed(secretWord,lettersGuessed) == False: print "You have {0} guesses left.".format(guessCount) print "Available letters: {0}".format(getAvailableLetters(lettersGuessed)) print "Please guess a letter: ", letter = str(raw_input()).lower() if letter not in lettersGuessed: lettersGuessed.append(letter) if letter in secretWord: print "Good guess: {0}".format(getGuessedWord(secretWord,lettersGuessed)) else: print "Oops! That letter is not in my word: {0}".format(getGuessedWord(secretWord,lettersGuessed)) guessCount-=1 else: print "Oops! You've already guessed that letter: {0}".format(getGuessedWord(secretWord,lettersGuessed)) print "-------------" if isWordGuessed(secretWord,lettersGuessed): print "Congratulations, you won!" else: print "Sorry, you ran out of guesses. The word was else." # When you've completed your hangman function, uncomment these two lines # and run this file to test! (hint: you might want to pick your own # secretWord while you're testing secretWord = chooseWord(wordlist).lower() hangman(secretWord)
{ "repo_name": "shiva92/Contests", "path": "Edx/Week3_ProbSet3/ps3_hangman.py", "copies": "1", "size": "4648", "license": "apache-2.0", "hash": -5785783921072495000, "line_mean": 31.2777777778, "line_max": 115, "alpha_frac": 0.6622203098, "autogenerated": false, "ratio": 3.9389830508474577, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5101203360647457, "avg_score": null, "num_lines": null }
# 6.00 Problem Set 3 # # Hangman game # # ----------------------------------- # Helper code # You don't need to understand this helper code, # but you will have to know how to use the functions # (so be sure to read the docstrings!) import random import string WORDLIST_FILENAME = "words.txt" def loadWords(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # line: string line = inFile.readline() # wordlist: list of strings wordlist = string.split(line) print " ", len(wordlist), "words loaded." return wordlist def chooseWord(wordlist): """ wordlist (list): list of words (strings) Returns a word from wordlist at random """ return random.choice(wordlist) # end of helper code # ----------------------------------- # Load the list of words into the variable wordlist # so that it can be accessed from anywhere in the program wordlist = loadWords() def isWordGuessed(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: boolean, True if all the letters of secretWord are in lettersGuessed; False otherwise ''' # FILL IN YOUR CODE HERE... foundAllLetters = True for letter in range(len(secretWord)): if secretWord[letter] not in lettersGuessed: foundAllLetters = False break return foundAllLetters #lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's'] #secretWord = 'aei' #print isWordGuessed(secretWord, lettersGuessed) def getGuessedWord(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters and underscores that represents what letters in secretWord have been guessed so far. ''' # FILL IN YOUR CODE HERE... blanks = '_ ' * len(secretWord) for letter in range(len(secretWord)): if secretWord[letter] in lettersGuessed: blanks = blanks[:(2 * letter)] + secretWord[letter] + blanks[2 * (letter) + 1:] return blanks """ for letter in range(len(secretWord)): if secretWord[letter] not in lettersGuessed: secretWord = secretWord[:letter] + "_" + secretWord[letter+1:] return secretWord """ #lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's'] #secretWord = 'bbbebbebieii' #print getGuessedWord(secretWord, lettersGuessed) def getAvailableLetters(lettersGuessed): ''' lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters that represents what letters have not yet been guessed. ''' # FILL IN YOUR CODE HERE... import string alphabet = string.ascii_lowercase AvailableLetters = '' for letter in range(len( alphabet)): if alphabet[letter] not in lettersGuessed: AvailableLetters +=alphabet[letter] return AvailableLetters #lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's'] #print getAvailableLetters(lettersGuessed) def hangman(secretWord): ''' secretWord: string, the secret word to guess. Starts up an interactive game of Hangman. * At the start of the game, let the user know how many letters the secretWord contains. * Ask the user to supply one guess (i.e. letter) per round. * The user should receive feedback immediately after each guess about whether their guess appears in the computers word. * After each round, you should also display to the user the partially guessed word so far, as well as letters that the user has not yet guessed. Follows the other limitations detailed in the problem write-up. ''' # FILL IN YOUR CODE HERE... print "Welcome to the game, Hangman! " print "I am thinking of a word that is %d letters long." %(len(secretWord)) lettersGuessed = [] num_Guesses = 8 while num_Guesses>0: print "-------------" print "You have %d guesses left."%(num_Guesses) print "Available letters: %s" % (getAvailableLetters(lettersGuessed)) new_letter = raw_input("Please guess a letter: ") new_letter = new_letter.lower() if new_letter not in lettersGuessed: lettersGuessed.append(new_letter) if new_letter in secretWord: print "Good guess: %s" % (getGuessedWord(secretWord, lettersGuessed)) if isWordGuessed(secretWord, lettersGuessed): print "-------------" print "Congratulations, you won!" break else: print "Oops! That letter is not in my word: %s" % (getGuessedWord(secretWord, lettersGuessed)) num_Guesses -= 1 else: print "Oops! You've already guessed that letter: %s" % (getGuessedWord(secretWord, lettersGuessed)) print "-------------" if num_Guesses==0: print "Sorry, you ran out of guesses. The word was %s ."% (secretWord) return # When you've completed your hangman function, uncomment these two lines # and run this file to test! (hint: you might want to pick your own # secretWord while you're testing) secretWord = chooseWord(wordlist).lower() #secretWord = 'guanabana' hangman(secretWord)
{ "repo_name": "ay1011/MITx-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python", "path": "problem_set_3_hangman/ps3_hangman.py", "copies": "1", "size": "5582", "license": "mit", "hash": -1146782785782658300, "line_mean": 30.5367231638, "line_max": 111, "alpha_frac": 0.6415263346, "autogenerated": false, "ratio": 3.802452316076294, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4943978650676294, "avg_score": null, "num_lines": null }
# 6.00 Problem Set 3 # # Hangman # # ----------------------------------- # Helper code # (you don't need to understand this helper code) import random import string from hangman import Hangman WORDLIST_FILENAME = "words.txt" def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # line: string line = inFile.readline() # wordlist: list of strings wordlist = string.split(line) print " ", len(wordlist), "words loaded." return wordlist def choose_word(wordlist): """ wordlist (list): list of words (strings) Returns a word from wordlist at random """ return random.choice(wordlist) # end of helper code # ----------------------------------- words = load_words() word = choose_word(words) hangman = Hangman(word) hangman.start()
{ "repo_name": "marioluan/mit-opencourseware-cs", "path": "600/unit-1/recursion/problem-set/ps2_hangman.py", "copies": "1", "size": "1036", "license": "mit", "hash": 2783669679339863600, "line_mean": 21.5434782609, "line_max": 74, "alpha_frac": 0.6167953668, "autogenerated": false, "ratio": 3.6868327402135233, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48036281070135234, "avg_score": null, "num_lines": null }
# 6.00 Problem Set 3 # # Hangman # # ----------------------------------- # Helper code # (you don't need to understand this helper code) import random import string WORDLIST_FILENAME = "words.txt" def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print ("Loading word list from file...") # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # line: string line = inFile.readline() # wordlist: list of strings wordlist = string.split(line) print (" ", len(wordlist), "words loaded.") return wordlist def choose_word(wordlist): """ wordlist (list): list of words (strings) Returns a word from wordlist at random """ return random.choice(wordlist) # end of helper code # ----------------------------------- # actually load the dictionary of words and point to it with # the wordlist variable so that it can be accessed from anywhere # in the program wordlist = load_words() # your code begins here!
{ "repo_name": "MarkSmithlxviii/MIT_600_Intro_to_CompSci", "path": "mit600/handouts/PS2/ps2_hangman.py", "copies": "2", "size": "1121", "license": "cc0-1.0", "hash": -3968343846875728000, "line_mean": 22.3541666667, "line_max": 74, "alpha_frac": 0.6235504014, "autogenerated": false, "ratio": 3.852233676975945, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5475784078375946, "avg_score": null, "num_lines": null }
# 6.00 Problem Set 3 # # Hangman # # ----------------------------------- # Helper code # (you don't need to understand this helper code) import random import string WORDLIST_FILENAME = "words.txt" def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # line: string line = inFile.readline() # wordlist: list of strings wordlist = string.split(line) print " ", len(wordlist), "words loaded." return wordlist def choose_word(wordlist): """ wordlist (list): list of words (strings) Returns a word from wordlist at random """ return random.choice(wordlist) # end of helper code # ----------------------------------- # actually load the dictionary of words and point to it with # the wordlist variable so that it can be accessed from anywhere # in the program wordlist = load_words() # your code begins here! def intro(secret): """ Returns opening instructions to player. """ return 1 def available_letters(remaining, guess): """ Check for available letters. """ newstr = "" for i in remaining: # print i # print "Checking " + i if i == guess: # print "removing ", guess # print "new string: ", newstr newstr else: newstr = newstr + i # print "new string: ", newstr return newstr def guess_test(secret, guess, guessed): """ Check the guess. """ hidden = '' global guesses for l in secret: if l in guessed: hidden = hidden + l else: hidden = hidden + '_' if guess in secret: print "Good guess: " + hidden else: print "Oops! That letter is not in my word: " + hidden guesses += -1 if '_' not in hidden: print "Congratulations, you won!" return return "" def hangman(): """ Plays the game hangman. """ secret = choose_word(wordlist) global guesses print "I am thinking of a word that is " + str(len(secret)) + \ " letters long." alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] alphabet = ''.join(alphabet) guessed = [] remaining = alphabet[:] guess = '' global guesses guesses = 8 while guesses > 0: print 'You have ' + str(guesses) + " guesses left." remaining = available_letters(remaining, guess) print 'Available letters: ' + ''.join(remaining) guess = str(raw_input('''Please guess a letter: ''')) guessed.append(guess) print ''.join(guessed) hidden = '' for l in secret: if l in guessed: hidden = hidden + l else: hidden = hidden + '_' if guess in secret: print "Good guess: " + hidden else: print "Oops! That letter is not in my word: " + hidden guesses += -1 if '_' not in hidden: print "Congratulations, you won!" break if guesses == 0: print "You are out of guesses." return
{ "repo_name": "willcohen/mit-6.00sc-python", "path": "ps2/ps2_hangman.py", "copies": "1", "size": "3456", "license": "mit", "hash": -9153964135055827000, "line_mean": 23.6857142857, "line_max": 74, "alpha_frac": 0.5324074074, "autogenerated": false, "ratio": 3.878787878787879, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9906577939249104, "avg_score": 0.000923469387755102, "num_lines": 140 }
# 6.00 Problem Set 4 # # Caesar Cipher Skeleton # import string import random import numbers WORDLIST_FILENAME = "words.txt" # ----------------------------------- # Helper code # (you don't need to understand this helper code) def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print("Loading word list from file...") # inFile: file inFile = open(WORDLIST_FILENAME, 'r') # line: string line = inFile.readline() # wordlist: list of strings wordlist = line.split() print(" ", len(wordlist), "words loaded.") return wordlist wordlist = load_words() def is_word(wordlist, word): """ Determines if word is a valid word. wordlist: list of words in the dictionary. word: a possible word. returns True if word is in wordlist. Example: >>> is_word(wordlist, 'bat') returns True >>> is_word(wordlist, 'asdf') returns False """ word = word.lower() word = word.strip(" !@#$%^&*()-_+={}[]|\:;'<>?,./\"") return word in wordlist def random_word(wordlist): """ Returns a random word. wordlist: list of words returns: a word from wordlist at random """ return random.choice(wordlist) def random_string(wordlist, n): """ Returns a string containing n random words from wordlist wordlist: list of words returns: a string of random words separated by spaces. """ return " ".join([random_word(wordlist) for _ in range(n)]) def random_scrambled(wordlist, n): """ Generates a test string by generating an n-word random string and encrypting it with a sequence of random shifts. wordlist: list of words n: number of random words to generate and scamble returns: a scrambled string of n random words NOTE: This function will ONLY work once you have completed your implementation of apply_shifts! """ s = random_string(wordlist, n) + " " shifts = [(i, random.randint(0, 26)) for i in range(len(s)) if s[i-1] == ' '] return apply_shifts(s, shifts)[:-1] def get_fable_string(): """ Returns a fable in encrypted text. """ f = open("fable.txt", "r") fable = str(f.read()) f.close() return fable # (end of helper code) # ----------------------------------- # # Problem 1: Encryption # def build_coder(shift): """ Returns a dict that can apply a Caesar cipher to a letter. The cipher is defined by the shift value. Ignores non-letter characters like punctuation and numbers. shift: -27 < int < 27 returns: dict Example: >>> build_coder(3) {' ': 'c', 'A': 'D', 'C': 'F', 'B': 'E', 'E': 'H', 'D': 'G', 'G': 'J', 'F': 'I', 'I': 'L', 'H': 'K', 'K': 'N', 'J': 'M', 'M': 'P', 'L': 'O', 'O': 'R', 'N': 'Q', 'Q': 'T', 'P': 'S', 'S': 'V', 'R': 'U', 'U': 'X', 'T': 'W', 'W': 'Z', 'V': 'Y', 'Y': 'A', 'X': ' ', 'Z': 'B', 'a': 'd', 'c': 'f', 'b': 'e', 'e': 'h', 'd': 'g', 'g': 'j', 'f': 'i', 'i': 'l', 'h': 'k', 'k': 'n', 'j': 'm', 'm': 'p', 'l': 'o', 'o': 'r', 'n': 'q', 'q': 't', 'p': 's', 's': 'v', 'r': 'u', 'u': 'x', 't': 'w', 'w': 'z', 'v': 'y', 'y': 'a', 'x': ' ', 'z': 'b'} (The order of the key-value pairs may be different.) """ assert shift >= 0 and shift < 27, 'shift %s is not between 0 and 27' % shift #numbers.Integral used in case of long integers assert isinstance(shift, numbers.Integral), 'shift is not an integer' result = {} upper = list(string.ascii_uppercase) lower = list(string.ascii_lowercase) upper.append(' ') lower.append(' ') for i in range(27): result[lower[i]] = lower[(i + shift) % 27] result[upper[i]] = upper[(i + shift) % 27] return result #print(build_coder(3)) def apply_coder(text, coder): """ Applies the coder to the text. Returns the encoded text. text: string coder: dict with mappings of characters to shifted characters returns: text after mapping coder chars to original text Example: >>> apply_coder("Hello, world!", build_encoder(3)) 'Khoor,czruog!' >>> apply_coder("Khoor,czruog!", build_decoder(3)) 'Hello, world!' """ # Pseudo Code # init empty list # start looping through 'text' # check if current char is a letter .isalpha() or space. # if is alpha or space, append value to temp string or list # if not space or alpha, don't pass element from encoder # return encoded string assert type(text) is str, 'text is not a string' encodedString = [] coderRef = coder i = 0 while i < len(text): if text[i].isalpha() or text[i] == ' ': encodedString.append(coderRef[text[i]]) else: encodedString.append(text[i]) i += 1 return ''.join(encodedString) #print(apply_coder(2, build_coder(4))) #print(apply_coder("Lipps,D svph!", build_coder(23))) def apply_shift(text, shift): """ Given a text, returns a new text Caesar shifted by the given shift offset. The empty space counts as the 27th letter of the alphabet, so spaces should be replaced by a lowercase letter as appropriate. Otherwise, lower case letters should remain lower case, upper case letters should remain upper case, and all other punctuation should stay as it is. text: string to apply the shift to shift: amount to shift the text returns: text after being shifted by specified amount. Example: >>> apply_shift('This is a test.', 8) 'Apq hq hiham a.' """ assert type(text) is str, 'text is not a string' assert shift >= 0 and shift < 27, 'shift %s is not between 0 and 27' % shift return apply_coder(text,build_coder(shift)) # print(apply_shift('This is a test.', 8)) # # Problem 2: Codebreaking. # def find_best_shift(wordlist, text): """ Decrypts the encoded text and returns the plaintext. text: string returns: 0 <= int 27 Example: >>> s = apply_coder('Hello, world!', build_encoder(8)) >>> s 'Pmttw,hdwztl!' >>> find_best_shift(wordlist, s) returns 8 >>> apply_coder(s, build_decoder(8)) returns 'Hello, world!' """ word = "" tempWordList = [] shift = 0 for i in range(27): word = apply_shift(text, i) j = 0 element = '' while j < len(word): if word[j].isalpha(): element += word[j] else: tempWordList.append(element) element = "" tempWordList.append(word[j]) j += 1 for guess in tempWordList: if guess.isalpha(): if guess.lower() in wordlist: print(guess) return i print(tempWordList) tempWordList = [] # s = apply_coder('Hello, world!', build_coder(8)) # print(find_best_shift(wordlist,s)) # # Problem 3: Multi-level encryption. # def apply_shifts(text, shifts): """ Applies a sequence of shifts to an input text. text: A string to apply the Ceasar shifts to shifts: A list of tuples containing the location each shift should begin and the shift offset. Each tuple is of the form (location, shift) The shifts are layered: each one is applied from its starting position all the way through the end of the string. returns: text after applying the shifts to the appropriate positions Example: >>> apply_shifts("Do Androids Dream of Electric Sheep?", [(0,6), (3, 18), (12, 16)]) 'JufYkaolfapxQdrnzmasmRyrpfdvpmEurrb?' """ ### TODO. # # Problem 4: Multi-level decryption. # def find_best_shifts(wordlist, text): """ Given a scrambled string, returns a shift key that will decode the text to words in wordlist, or None if there is no such key. Hint: Make use of the recursive function find_best_shifts_rec(wordlist, text, start) wordlist: list of words text: scambled text to try to find the words for returns: list of tuples. each tuple is (position in text, amount of shift) Examples: >>> s = random_scrambled(wordlist, 3) >>> s 'eqorqukvqtbmultiform wyy ion' >>> shifts = find_best_shifts(wordlist, s) >>> shifts [(0, 25), (11, 2), (21, 5)] >>> apply_shifts(s, shifts) 'compositor multiform accents' >>> s = apply_shifts("Do Androids Dream of Electric Sheep?", [(0,6), (3, 18), (12, 16)]) >>> s 'JufYkaolfapxQdrnzmasmRyrpfdvpmEurrb?' >>> shifts = find_best_shifts(wordlist, s) >>> print apply_shifts(s, shifts) Do Androids Dream of Electric Sheep? """ def find_best_shifts_rec(wordlist, text, start): """ Given a scrambled string and a starting position from which to decode, returns a shift key that will decode the text to words in wordlist, or None if there is no such key. Hint: You will find this function much easier to implement if you use recursion. wordlist: list of words text: scambled text to try to find the words for start: where to start looking at shifts returns: list of tuples. each tuple is (position in text, amount of shift) """ ### TODO. def decrypt_fable(): """ Using the methods you created in this problem set, decrypt the fable given by the function get_fable_string(). Once you decrypt the message, be sure to include as a comment at the end of this problem set how the fable relates to your education at MIT. returns: string - fable in plain text """ ### TODO. #What is the moral of the story? # # # # #
{ "repo_name": "sheva29/Introduction_to_Computational_Thinking", "path": "caesar_cipher/ps4.py", "copies": "1", "size": "9705", "license": "mit", "hash": -742555510610359600, "line_mean": 27.049132948, "line_max": 92, "alpha_frac": 0.5988665636, "autogenerated": false, "ratio": 3.3933566433566433, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9475486486668125, "avg_score": 0.0033473440577034626, "num_lines": 346 }
# 6.00 Problem Set 4 # # Caesar Cipher Skeleton # import string import random WORDLIST_FILENAME = "/Users/macbookpro/Documents/CS/CS600/hw/ps4/words.txt" # ----------------------------------- # Helper code # (you don't need to understand this helper code) def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print("Loading word list from file...") # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # line: string line = inFile.readline() # wordlist: list of strings wordlist = line.split() print(" ", len(wordlist), "words loaded.") return wordlist wordlist = load_words() def is_word(wordlist, word): """ Determines if word is a valid word. wordlist: list of words in the dictionary. word: a possible word. returns True if word is in wordlist. Example: >>> is_word(wordlist, 'bat') returns True >>> is_word(wordlist, 'asdf') returns False """ word = word.lower() word = word.strip(" !@#$%^&*()-_+={}[]|\:;'<>?,./\"") return word in wordlist def random_word(wordlist): """ Returns a random word. wordlist: list of words returns: a word from wordlist at random """ return random.choice(wordlist) def random_string(wordlist, n): """ Returns a string containing n random words from wordlist wordlist: list of words returns: a string of random words separated by spaces. """ return " ".join([random_word(wordlist) for _ in range(n)]) def random_scrambled(wordlist, n): """ Generates a test string by generating an n-word random string and encrypting it with a sequence of random shifts. wordlist: list of words n: number of random words to generate and scamble returns: a scrambled string of n random words NOTE: This function will ONLY work once you have completed your implementation of apply_shifts! """ s = random_string(wordlist, n) + " " shifts = [(i, random.randint(0, 26)) for i in range(len(s)) if s[i-1] == ' '] return apply_shifts(s, shifts)[:-1] def get_fable_string(): """ Returns a fable in encrypted text. """ f = open("fable.txt", "r") fable = str(f.read()) f.close() return fable # (end of helper code) # ----------------------------------- # # Problem 1: Encryption # def build_coder(shift): """ Returns a dict that can apply a Caesar cipher to a letter. The cipher is defined by the shift value. Ignores non-letter characters like punctuation and numbers. shift: -27 < int < 27 returns: dict Example: >>> build_coder(3) {' ': 'c', 'A': 'D', 'C': 'F', 'B': 'E', 'E': 'H', 'D': 'G', 'G': 'J', 'F': 'I', 'I': 'L', 'H': 'K', 'K': 'N', 'J': 'M', 'M': 'P', 'L': 'O', 'O': 'R', 'N': 'Q', 'Q': 'T', 'P': 'S', 'S': 'V', 'R': 'U', 'U': 'X', 'T': 'W', 'W': 'Z', 'V': 'Y', 'Y': 'A', 'X': ' ', 'Z': 'B', 'a': 'd', 'c': 'f', 'b': 'e', 'e': 'h', 'd': 'g', 'g': 'j', 'f': 'i', 'i': 'l', 'h': 'k', 'k': 'n', 'j': 'm', 'm': 'p', 'l': 'o', 'o': 'r', 'n': 'q', 'q': 't', 'p': 's', 's': 'v', 'r': 'u', 'u': 'x', 't': 'w', 'w': 'z', 'v': 'y', 'y': 'a', 'x': ' ', 'z': 'b'} (The order of the key-value pairs may be different.) """ ### TODO. def build_encoder(shift): """ Returns a dict that can be used to encode a plain text. For example, you could encrypt the plain text by calling the following commands >>>encoder = build_encoder(shift) >>>encrypted_text = apply_coder(plain_text, encoder) The cipher is defined by the shift value. Ignores non-letter characters like punctuation and numbers. shift: 0 <= int < 27 returns: dict Example: >>> build_encoder(3) {' ': 'c', 'A': 'D', 'C': 'F', 'B': 'E', 'E': 'H', 'D': 'G', 'G': 'J', 'F': 'I', 'I': 'L', 'H': 'K', 'K': 'N', 'J': 'M', 'M': 'P', 'L': 'O', 'O': 'R', 'N': 'Q', 'Q': 'T', 'P': 'S', 'S': 'V', 'R': 'U', 'U': 'X', 'T': 'W', 'W': 'Z', 'V': 'Y', 'Y': 'A', 'X': ' ', 'Z': 'B', 'a': 'd', 'c': 'f', 'b': 'e', 'e': 'h', 'd': 'g', 'g': 'j', 'f': 'i', 'i': 'l', 'h': 'k', 'k': 'n', 'j': 'm', 'm': 'p', 'l': 'o', 'o': 'r', 'n': 'q', 'q': 't', 'p': 's', 's': 'v', 'r': 'u', 'u': 'x', 't': 'w', 'w': 'z', 'v': 'y', 'y': 'a', 'x': ' ', 'z': 'b'} (The order of the key-value pairs may be different.) HINT : Use build_coder. """ ### TODO. def build_decoder(shift): """ Returns a dict that can be used to decode an encrypted text. For example, you could decrypt an encrypted text by calling the following commands >>>encoder = build_encoder(shift) >>>encrypted_text = apply_coder(plain_text, encoder) >>>decrypted_text = apply_coder(plain_text, decoder) The cipher is defined by the shift value. Ignores non-letter characters like punctuation and numbers. shift: 0 <= int < 27 returns: dict Example: >>> build_decoder(3) {' ': 'x', 'A': 'Y', 'C': ' ', 'B': 'Z', 'E': 'B', 'D': 'A', 'G': 'D', 'F': 'C', 'I': 'F', 'H': 'E', 'K': 'H', 'J': 'G', 'M': 'J', 'L': 'I', 'O': 'L', 'N': 'K', 'Q': 'N', 'P': 'M', 'S': 'P', 'R': 'O', 'U': 'R', 'T': 'Q', 'W': 'T', 'V': 'S', 'Y': 'V', 'X': 'U', 'Z': 'W', 'a': 'y', 'c': ' ', 'b': 'z', 'e': 'b', 'd': 'a', 'g': 'd', 'f': 'c', 'i': 'f', 'h': 'e', 'k': 'h', 'j': 'g', 'm': 'j', 'l': 'i', 'o': 'l', 'n': 'k', 'q': 'n', 'p': 'm', 's': 'p', 'r': 'o', 'u': 'r', 't': 'q', 'w': 't', 'v': 's', 'y': 'v', 'x': 'u', 'z': 'w'} (The order of the key-value pairs may be different.) HINT : Use build_coder. """ ### TODO. def apply_coder(text, coder): """ Applies the coder to the text. Returns the encoded text. text: string coder: dict with mappings of characters to shifted characters returns: text after mapping coder chars to original text Example: >>> apply_coder("Hello, world!", build_encoder(3)) 'Khoor,czruog!' >>> apply_coder("Khoor,czruog!", build_decoder(3)) 'Hello, world!' """ ### TODO. def apply_shift(text, shift): """ Given a text, returns a new text Caesar shifted by the given shift offset. The empty space counts as the 27th letter of the alphabet, so spaces should be replaced by a lowercase letter as appropriate. Otherwise, lower case letters should remain lower case, upper case letters should remain upper case, and all other punctuation should stay as it is. text: string to apply the shift to shift: amount to shift the text returns: text after being shifted by specified amount. Example: >>> apply_shift('This is a test.', 8) 'Apq hq hiham a.' """ ### TODO. # # Problem 2: Codebreaking. # def find_best_shift(wordlist, text): """ Decrypts the encoded text and returns the plaintext. text: string returns: 0 <= int 27 Example: >>> s = apply_coder('Hello, world!', build_encoder(8)) >>> s 'Pmttw,hdwztl!' >>> find_best_shift(wordlist, s) returns 8 >>> apply_coder(s, build_decoder(8)) returns 'Hello, world!' """ ### TODO # # Problem 3: Multi-level encryption. # def apply_shifts(text, shifts): """ Applies a sequence of shifts to an input text. text: A string to apply the Ceasar shifts to shifts: A list of tuples containing the location each shift should begin and the shift offset. Each tuple is of the form (location, shift) The shifts are layered: each one is applied from its starting position all the way through the end of the string. returns: text after applying the shifts to the appropriate positions Example: >>> apply_shifts("Do Androids Dream of Electric Sheep?", [(0,6), (3, 18), (12, 16)]) 'JufYkaolfapxQdrnzmasmRyrpfdvpmEurrb?' """ ### TODO. # # Problem 4: Multi-level decryption. # def find_best_shifts(wordlist, text): """ Given a scrambled string, returns a shift key that will decode the text to words in wordlist, or None if there is no such key. Hint: Make use of the recursive function find_best_shifts_rec(wordlist, text, start) wordlist: list of words text: scambled text to try to find the words for returns: list of tuples. each tuple is (position in text, amount of shift) Examples: >>> s = random_scrambled(wordlist, 3) >>> s 'eqorqukvqtbmultiform wyy ion' >>> shifts = find_best_shifts(wordlist, s) >>> shifts [(0, 25), (11, 2), (21, 5)] >>> apply_shifts(s, shifts) 'compositor multiform accents' >>> s = apply_shifts("Do Androids Dream of Electric Sheep?", [(0,6), (3, 18), (12, 16)]) >>> s 'JufYkaolfapxQdrnzmasmRyrpfdvpmEurrb?' >>> shifts = find_best_shifts(wordlist, s) >>> print apply_shifts(s, shifts) Do Androids Dream of Electric Sheep? """ def find_best_shifts_rec(wordlist, text, start): """ Given a scrambled string and a starting position from which to decode, returns a shift key that will decode the text to words in wordlist, or None if there is no such key. Hint: You will find this function much easier to implement if you use recursion. wordlist: list of words text: scambled text to try to find the words for start: where to start looking at shifts returns: list of tuples. each tuple is (position in text, amount of shift) """ ### TODO. def decrypt_fable(): """ Using the methods you created in this problem set, decrypt the fable given by the function get_fable_string(). Once you decrypt the message, be sure to include as a comment at the end of this problem set how the fable relates to your education at MIT. returns: string - fable in plain text """ ### TODO. #What is the moral of the story? # # # # #
{ "repo_name": "Am3ra/CS", "path": "CS600/hw/ps4/ps4.py", "copies": "1", "size": "9986", "license": "mit", "hash": -4498530835086232000, "line_mean": 28.8089552239, "line_max": 92, "alpha_frac": 0.5634888844, "autogenerated": false, "ratio": 3.0764017252002462, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.41398906096002464, "avg_score": null, "num_lines": null }
# 6.00 Problem Set 4 # # Caesar Cipher Skeleton # import string import random WORDLIST_FILENAME = "words.txt" ALPHABET = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' '] ALPHABET_LEN = len(ALPHABET) # ----------------------------------- # Helper code # (you don't need to understand this helper code) def get_number_of_words(wordlist, text): number_valid_words = 0 words = text.split(' ') for word in words: if is_word(wordlist, word): number_valid_words += 1 else: return -1 return number_valid_words if number_valid_words == len(words) else -1 def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # line: string line = inFile.readline() # wordlist: list of strings wordlist = line.split() print " ", len(wordlist), "words loaded." return wordlist wordlist = load_words() def is_word(wordlist, word): """ Determines if word is a valid word. wordlist: list of words in the dictionary. word: a possible word. returns True if word is in wordlist. Example: >>> is_word(wordlist, 'bat') returns True >>> is_word(wordlist, 'asdf') returns False """ word = word.lower() word = word.strip(" !@#$%^&*()-_+={}[]|\:;'<>?,./\"") return word in wordlist def is_letter(letter): return letter in ALPHABET def random_word(wordlist): """ Returns a random word. wordlist: list of words returns: a word from wordlist at random """ return random.choice(wordlist) def random_string(wordlist, n): """ Returns a string containing n random words from wordlist wordlist: list of words returns: a string of random words separated by spaces. """ return " ".join([random_word(wordlist) for _ in range(n)]) def random_scrambled(wordlist, n): """ Generates a test string by generating an n-word random string and encrypting it with a sequence of random shifts. wordlist: list of words n: number of random words to generate and scamble returns: a scrambled string of n random words NOTE: This function will ONLY work once you have completed your implementation of apply_shifts! """ s = random_string(wordlist, n) + " " shifts = [(i, random.randint(0, 26)) for i in range(len(s)) if s[i-1] == ' '] return apply_shifts(s, shifts)[:-1] def get_fable_string(): """ Returns a fable in encrypted text. """ f = open("fable.txt", "r") fable = str(f.read()) f.close() return fable # (end of helper code) # ----------------------------------- # # Problem 1: Encryption # def build_coder(shift): """ Returns a dict that can apply a Caesar cipher to a letter. The cipher is defined by the shift value. Ignores non-letter characters like punctuation and numbers. shift: -27 < int < 27 returns: dict Example: >>> build_coder(3) {' ': 'c', 'A': 'D', 'C': 'F', 'B': 'E', 'E': 'H', 'D': 'G', 'G': 'J', 'F': 'I', 'I': 'L', 'H': 'K', 'K': 'N', 'J': 'M', 'M': 'P', 'L': 'O', 'O': 'R', 'N': 'Q', 'Q': 'T', 'P': 'S', 'S': 'V', 'R': 'U', 'U': 'X', 'T': 'W', 'W': 'Z', 'V': 'Y', 'Y': 'A', 'X': ' ', 'Z': 'B', 'a': 'd', 'c': 'f', 'b': 'e', 'e': 'h', 'd': 'g', 'g': 'j', 'f': 'i', 'i': 'l', 'h': 'k', 'k': 'n', 'j': 'm', 'm': 'p', 'l': 'o', 'o': 'r', 'n': 'q', 'q': 't', 'p': 's', 's': 'v', 'r': 'u', 'u': 'x', 't': 'w', 'w': 'z', 'v': 'y', 'y': 'a', 'x': ' ', 'z': 'b'} (The order of the key-value pairs may be different.) """ if shift < -27 or shift > 27: message = 'shift %d must be an integer between -27 < int < 27' % shift raise IndexError(message) coder = {} for index in range(ALPHABET_LEN): shifted_index = (index+shift) % ALPHABET_LEN coder[ALPHABET[index]] = ALPHABET[shifted_index] return coder def build_encoder(shift): """ Returns a dict that can be used to encode a plain text. For example, you could encrypt the plain text by calling the following commands >>>encoder = build_encoder(shift) >>>encrypted_text = apply_coder(plain_text, encoder) The cipher is defined by the shift value. Ignores non-letter characters like punctuation and numbers. shift: 0 <= int < 27 returns: dict Example: >>> build_encoder(3) {' ': 'c', 'A': 'D', 'C': 'F', 'B': 'E', 'E': 'H', 'D': 'G', 'G': 'J', 'F': 'I', 'I': 'L', 'H': 'K', 'K': 'N', 'J': 'M', 'M': 'P', 'L': 'O', 'O': 'R', 'N': 'Q', 'Q': 'T', 'P': 'S', 'S': 'V', 'R': 'U', 'U': 'X', 'T': 'W', 'W': 'Z', 'V': 'Y', 'Y': 'A', 'X': ' ', 'Z': 'B', 'a': 'd', 'c': 'f', 'b': 'e', 'e': 'h', 'd': 'g', 'g': 'j', 'f': 'i', 'i': 'l', 'h': 'k', 'k': 'n', 'j': 'm', 'm': 'p', 'l': 'o', 'o': 'r', 'n': 'q', 'q': 't', 'p': 's', 's': 'v', 'r': 'u', 'u': 'x', 't': 'w', 'w': 'z', 'v': 'y', 'y': 'a', 'x': ' ', 'z': 'b'} (The order of the key-value pairs may be different.) HINT : Use build_coder. """ ### TODO. if shift <= -1 or shift > 27: message = 'shift %d must be an integer between 0 < int < 27' % shift raise IndexError(message) return build_coder(shift) def build_decoder(shift): """ Returns a dict that can be used to decode an encrypted text. For example, you could decrypt an encrypted text by calling the following commands >>>encoder = build_encoder(shift) >>>encrypted_text = apply_coder(plain_text, encoder) >>>decrypted_text = apply_coder(plain_text, decoder) The cipher is defined by the shift value. Ignores non-letter characters like punctuation and numbers. shift: 0 <= int < 27 returns: dict Example: >>> build_decoder(3) {' ': 'x', 'A': 'Y', 'C': ' ', 'B': 'Z', 'E': 'B', 'D': 'A', 'G': 'D', 'F': 'C', 'I': 'F', 'H': 'E', 'K': 'H', 'J': 'G', 'M': 'J', 'L': 'I', 'O': 'L', 'N': 'K', 'Q': 'N', 'P': 'M', 'S': 'P', 'R': 'O', 'U': 'R', 'T': 'Q', 'W': 'T', 'V': 'S', 'Y': 'V', 'X': 'U', 'Z': 'W', 'a': 'y', 'c': ' ', 'b': 'z', 'e': 'b', 'd': 'a', 'g': 'd', 'f': 'c', 'i': 'f', 'h': 'e', 'k': 'h', 'j': 'g', 'm': 'j', 'l': 'i', 'o': 'l', 'n': 'k', 'q': 'n', 'p': 'm', 's': 'p', 'r': 'o', 'u': 'r', 't': 'q', 'w': 't', 'v': 's', 'y': 'v', 'x': 'u', 'z': 'w'} (The order of the key-value pairs may be different.) HINT : Use build_coder. """ if shift <= -1 or shift > 27: message = 'shift %d must be an integer between 0 <= int < 27' % shift raise IndexError(message) return build_coder(-shift) def apply_coder(text, coder): """ Applies the coder to the text. Returns the encoded text. text: string coder: dict with mappings of characters to shifted characters returns: text after mapping coder chars to original text Example: >>> apply_coder("Hello, world!", build_encoder(3)) 'Khoor,czruog!' >>> apply_coder("Khoor,czruog!", build_decoder(3)) 'Hello, world!' """ ### TODO. encoded_text = "" for letter in text: # ignores no-letter characters letter = letter.lower() if is_letter(letter): encoded_letter = coder[letter] else: encoded_letter = letter encoded_text += encoded_letter return encoded_text def apply_shift(text, shift): """ Given a text, returns a new text Caesar shifted by the given shift offset. The empty space counts as the 27th letter of the alphabet, so spaces should be replaced by a lowercase letter as appropriate. Otherwise, lower case letters should remain lower case, upper case letters should remain upper case, and all other punctuation should stay as it is. text: string to apply the shift to shift: amount to shift the text returns: text after being shifted by specified amount. Example: >>> apply_shift('This is a test.', 8) 'Apq hq hiham a.' """ ### TODO. encoder = build_coder(shift) return apply_coder(text, encoder) # # Problem 2: Codebreaking. # def find_best_shift(wordlist, text): """ Decrypts the encoded text and returns the plaintext. text: string returns: 0 <= int 27 Example: >>> s = apply_coder('Hello, world!', build_encoder(8)) >>> s 'Pmttw,hdwztl!' >>> find_best_shift(wordlist, s) returns 8 >>> apply_coder(s, build_decoder(8)) returns 'Hello, world!' """ ### TODO max_number_words = -1 shift = None for index in range(ALPHABET_LEN): decoder = build_decoder(index) decrypted_text = apply_coder(text, decoder) number_words = get_number_of_words(wordlist, decrypted_text) if number_words == -1: continue elif number_words > max_number_words: max_number_words = number_words shift = index print 'decrypted_text: ', decrypted_text, print 'shift: ', index return shift words = load_words() print find_best_shift(words, 'Pmttw,hdwztl!') # # Problem 3: Multi-level encryption. # def apply_shifts(text, shifts): """ Applies a sequence of shifts to an input text. text: A string to apply the Ceasar shifts to shifts: A list of tuples containing the location each shift should begin and the shift offset. Each tuple is of the form (location, shift) The shifts are layered: each one is applied from its starting position all the way through the end of the string. returns: text after applying the shifts to the appropriate positions Example: >>> apply_shifts("Do Androids Dream of Electric Sheep?", [(0,6), (3, 18), (12, 16)]) 'JufYkaolfapxQdrnzmasmRyrpfdvpmEurrb?' """ ### TODO. if len(shifts) == 0: return text shift = shifts.pop() shifted_text = apply_shift(text[shift[0]:], shift[1]) print 'shifted_text with shift:', shift[1], shifted_text text = text[:shift[0]] + shifted_text print 'text + shift:', text return apply_shifts(text, shifts) # # Problem 4: Multi-level decryption. # def find_best_shifts(wordlist, text): """ Given a scrambled string, returns a shift key that will decode the text to words in wordlist, or None if there is no such key. Hint: Make use of the recursive function find_best_shifts_rec(wordlist, text, start) wordlist: list of words text: scambled text to try to find the words for returns: list of tuples. each tuple is (position in text, amount of shift) Examples: >>> s = random_scrambled(wordlist, 3) >>> s 'eqorqukvqtbmultiform wyy ion' >>> shifts = find_best_shifts(wordlist, s) >>> shifts [(0, 25), (11, 2), (21, 5)] >>> apply_shifts(s, shifts) 'compositor multiform accents' >>> s = apply_shifts("Do Androids Dream of Electric Sheep?", [(0,6), (3, 18), (12, 16)]) >>> s 'JufYkaolfapxQdrnzmasmRyrpfdvpmEurrb?' >>> shifts = find_best_shifts(wordlist, s) >>> print apply_shifts(s, shifts) Do Androids Dream of Electric Sheep? """ def find_best_shifts_rec(wordlist, text, start): """ Given a scrambled string and a starting position from which to decode, returns a shift key that will decode the text to words in wordlist, or None if there is no such key. Hint: You will find this function much easier to implement if you use recursion. wordlist: list of words text: scambled text to try to find the words for start: where to start looking at shifts returns: list of tuples. each tuple is (position in text, amount of shift) """ ### TODO. def decrypt_fable(): """ Using the methods you created in this problem set, decrypt the fable given by the function get_fable_string(). Once you decrypt the message, be sure to include as a comment at the end of this problem set how the fable relates to your education at MIT. returns: string - fable in plain text """ ### TODO. #What is the moral of the story? # # # # #
{ "repo_name": "marioluan/mit-opencourseware-cs", "path": "600/unit-2/hashing-and-classes/problem-sets/problem-set/ps4.py", "copies": "1", "size": "12349", "license": "mit", "hash": 3049969271220197400, "line_mean": 28.6850961538, "line_max": 146, "alpha_frac": 0.5684670824, "autogenerated": false, "ratio": 3.131085192697769, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9169587681771842, "avg_score": 0.005992918665185306, "num_lines": 416 }
# 6.00 Problem Set 4 # # Caesar Cipher Skeleton # import string import random WORDLIST_FILENAME = "words.txt" # ----------------------------------- # Helper code # (you don't need to understand this helper code) def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # line: string line = inFile.readline() # wordlist: list of strings wordlist = line.split() print " ", len(wordlist), "words loaded." return wordlist wordlist = load_words() def is_word(wordlist, word): """ Determines if word is a valid word. wordlist: list of words in the dictionary. word: a possible word. returns True if word is in wordlist. Example: >>> is_word(wordlist, 'bat') returns True >>> is_word(wordlist, 'asdf') returns False """ word = word.lower() word = word.strip(" !@#$%^&*()-_+={}[]|\:;'<>?,./\"") return word in wordlist def random_word(wordlist): """ Returns a random word. wordlist: list of words returns: a word from wordlist at random """ return random.choice(wordlist) def random_string(wordlist, n): """ Returns a string containing n random words from wordlist wordlist: list of words returns: a string of random words separated by spaces. """ return " ".join([random_word(wordlist) for _ in range(n)]) def random_scrambled(wordlist, n): """ Generates a test string by generating an n-word random string and encrypting it with a sequence of random shifts. wordlist: list of words n: number of random words to generate and scamble returns: a scrambled string of n random words NOTE: This function will ONLY work once you have completed your implementation of apply_shifts! """ s = random_string(wordlist, n) + " " shifts = [(i, random.randint(0, 26)) for i in range(len(s)) if s[i-1] == ' '] return apply_shifts(s, shifts)[:-1] def get_fable_string(): """ Returns a fable in encrypted text. """ f = open("fable.txt", "r") fable = str(f.read()) f.close() return fable # (end of helper code) # ----------------------------------- # # Problem 1: Encryption # def build_coder(shift): """ Returns a dict that can apply a Caesar cipher to a letter. The cipher is defined by the shift value. Ignores non-letter characters like punctuation and numbers. shift: -27 < int < 27 returns: dict Example: >>> build_coder(3) {' ': 'c', 'A': 'D', 'C': 'F', 'B': 'E', 'E': 'H', 'D': 'G', 'G': 'J', 'F': 'I', 'I': 'L', 'H': 'K', 'K': 'N', 'J': 'M', 'M': 'P', 'L': 'O', 'O': 'R', 'N': 'Q', 'Q': 'T', 'P': 'S', 'S': 'V', 'R': 'U', 'U': 'X', 'T': 'W', 'W': 'Z', 'V': 'Y', 'Y': 'A', 'X': ' ', 'Z': 'B', 'a': 'd', 'c': 'f', 'b': 'e', 'e': 'h', 'd': 'g', 'g': 'j', 'f': 'i', 'i': 'l', 'h': 'k', 'k': 'n', 'j': 'm', 'm': 'p', 'l': 'o', 'o': 'r', 'n': 'q', 'q': 't', 'p': 's', 's': 'v', 'r': 'u', 'u': 'x', 't': 'w', 'w': 'z', 'v': 'y', 'y': 'a', 'x': ' ', 'z': 'b'} (The order of the key-value pairs may be different.) """ ### TODO. def build_encoder(shift): """ Returns a dict that can be used to encode a plain text. For example, you could encrypt the plain text by calling the following commands >>>encoder = build_encoder(shift) >>>encrypted_text = apply_coder(plain_text, encoder) The cipher is defined by the shift value. Ignores non-letter characters like punctuation and numbers. shift: 0 <= int < 27 returns: dict Example: >>> build_encoder(3) {' ': 'c', 'A': 'D', 'C': 'F', 'B': 'E', 'E': 'H', 'D': 'G', 'G': 'J', 'F': 'I', 'I': 'L', 'H': 'K', 'K': 'N', 'J': 'M', 'M': 'P', 'L': 'O', 'O': 'R', 'N': 'Q', 'Q': 'T', 'P': 'S', 'S': 'V', 'R': 'U', 'U': 'X', 'T': 'W', 'W': 'Z', 'V': 'Y', 'Y': 'A', 'X': ' ', 'Z': 'B', 'a': 'd', 'c': 'f', 'b': 'e', 'e': 'h', 'd': 'g', 'g': 'j', 'f': 'i', 'i': 'l', 'h': 'k', 'k': 'n', 'j': 'm', 'm': 'p', 'l': 'o', 'o': 'r', 'n': 'q', 'q': 't', 'p': 's', 's': 'v', 'r': 'u', 'u': 'x', 't': 'w', 'w': 'z', 'v': 'y', 'y': 'a', 'x': ' ', 'z': 'b'} (The order of the key-value pairs may be different.) HINT : Use build_coder. """ ### TODO. def build_decoder(shift): """ Returns a dict that can be used to decode an encrypted text. For example, you could decrypt an encrypted text by calling the following commands >>>encoder = build_encoder(shift) >>>encrypted_text = apply_coder(plain_text, encoder) >>>decrypted_text = apply_coder(plain_text, decoder) The cipher is defined by the shift value. Ignores non-letter characters like punctuation and numbers. shift: 0 <= int < 27 returns: dict Example: >>> build_decoder(3) {' ': 'x', 'A': 'Y', 'C': ' ', 'B': 'Z', 'E': 'B', 'D': 'A', 'G': 'D', 'F': 'C', 'I': 'F', 'H': 'E', 'K': 'H', 'J': 'G', 'M': 'J', 'L': 'I', 'O': 'L', 'N': 'K', 'Q': 'N', 'P': 'M', 'S': 'P', 'R': 'O', 'U': 'R', 'T': 'Q', 'W': 'T', 'V': 'S', 'Y': 'V', 'X': 'U', 'Z': 'W', 'a': 'y', 'c': ' ', 'b': 'z', 'e': 'b', 'd': 'a', 'g': 'd', 'f': 'c', 'i': 'f', 'h': 'e', 'k': 'h', 'j': 'g', 'm': 'j', 'l': 'i', 'o': 'l', 'n': 'k', 'q': 'n', 'p': 'm', 's': 'p', 'r': 'o', 'u': 'r', 't': 'q', 'w': 't', 'v': 's', 'y': 'v', 'x': 'u', 'z': 'w'} (The order of the key-value pairs may be different.) HINT : Use build_coder. """ ### TODO. def apply_coder(text, coder): """ Applies the coder to the text. Returns the encoded text. text: string coder: dict with mappings of characters to shifted characters returns: text after mapping coder chars to original text Example: >>> apply_coder("Hello, world!", build_encoder(3)) 'Khoor,czruog!' >>> apply_coder("Khoor,czruog!", build_decoder(3)) 'Hello, world!' """ ### TODO. def apply_shift(text, shift): """ Given a text, returns a new text Caesar shifted by the given shift offset. The empty space counts as the 27th letter of the alphabet, so spaces should be replaced by a lowercase letter as appropriate. Otherwise, lower case letters should remain lower case, upper case letters should remain upper case, and all other punctuation should stay as it is. text: string to apply the shift to shift: amount to shift the text returns: text after being shifted by specified amount. Example: >>> apply_shift('This is a test.', 8) 'Apq hq hiham a.' """ ### TODO. # # Problem 2: Codebreaking. # def find_best_shift(wordlist, text): """ Decrypts the encoded text and returns the plaintext. text: string returns: 0 <= int 27 Example: >>> s = apply_coder('Hello, world!', build_encoder(8)) >>> s 'Pmttw,hdwztl!' >>> find_best_shift(wordlist, s) returns 8 >>> apply_coder(s, build_decoder(8)) returns 'Hello, world!' """ ### TODO # # Problem 3: Multi-level encryption. # def apply_shifts(text, shifts): """ Applies a sequence of shifts to an input text. text: A string to apply the Ceasar shifts to shifts: A list of tuples containing the location each shift should begin and the shift offset. Each tuple is of the form (location, shift) The shifts are layered: each one is applied from its starting position all the way through the end of the string. returns: text after applying the shifts to the appropriate positions Example: >>> apply_shifts("Do Androids Dream of Electric Sheep?", [(0,6), (3, 18), (12, 16)]) 'JufYkaolfapxQdrnzmasmRyrpfdvpmEurrb?' """ ### TODO. # # Problem 4: Multi-level decryption. # def find_best_shifts(wordlist, text): """ Given a scrambled string, returns a shift key that will decode the text to words in wordlist, or None if there is no such key. Hint: Make use of the recursive function find_best_shifts_rec(wordlist, text, start) wordlist: list of words text: scambled text to try to find the words for returns: list of tuples. each tuple is (position in text, amount of shift) Examples: >>> s = random_scrambled(wordlist, 3) >>> s 'eqorqukvqtbmultiform wyy ion' >>> shifts = find_best_shifts(wordlist, s) >>> shifts [(0, 25), (11, 2), (21, 5)] >>> apply_shifts(s, shifts) 'compositor multiform accents' >>> s = apply_shifts("Do Androids Dream of Electric Sheep?", [(0,6), (3, 18), (12, 16)]) >>> s 'JufYkaolfapxQdrnzmasmRyrpfdvpmEurrb?' >>> shifts = find_best_shifts(wordlist, s) >>> print apply_shifts(s, shifts) Do Androids Dream of Electric Sheep? """ def find_best_shifts_rec(wordlist, text, start): """ Given a scrambled string and a starting position from which to decode, returns a shift key that will decode the text to words in wordlist, or None if there is no such key. Hint: You will find this function much easier to implement if you use recursion. wordlist: list of words text: scambled text to try to find the words for start: where to start looking at shifts returns: list of tuples. each tuple is (position in text, amount of shift) """ ### TODO. def decrypt_fable(): """ Using the methods you created in this problem set, decrypt the fable given by the function get_fable_string(). Once you decrypt the message, be sure to include as a comment at the end of this problem set how the fable relates to your education at MIT. returns: string - fable in plain text """ ### TODO. #What is the moral of the story? # # # # #
{ "repo_name": "jdhaines/MIT6.00", "path": "PS4/ps4.py", "copies": "2", "size": "9940", "license": "mit", "hash": -4594512356353688600, "line_mean": 28.671641791, "line_max": 92, "alpha_frac": 0.5624748491, "autogenerated": false, "ratio": 3.0793060718711276, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4641780920971127, "avg_score": null, "num_lines": null }
# 6.00 Problem Set 4 # # Caesar Cipher Skeleton # # Problem Set 4 # Name: Shouvik Roy # Collaborators: None # Time: 6 hours 30 minutes import string import random from types import * WORDLIST_FILENAME = "words.txt" # ----------------------------------- # Helper code # (you don't need to understand this helper code) def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # line: string line = inFile.readline() # wordlist: list of strings wordlist = line.split() print " ", len(wordlist), "words loaded." return wordlist wordlist = load_words() def is_word(wordlist, word): """ Determines if word is a valid word. wordlist: list of words in the dictionary. word: a possible word. returns True if word is in wordlist. Example: >>> is_word(wordlist, 'bat') returns True >>> is_word(wordlist, 'asdf') returns False """ word = word.lower() word = word.strip(" !@#$%^&*()-_+={}[]|\:;'<>?,./\"") return word in wordlist def random_word(wordlist): """ Returns a random word. wordlist: list of words returns: a word from wordlist at random """ return random.choice(wordlist) def random_string(wordlist, n): """ Returns a string containing n random words from wordlist wordlist: list of words returns: a string of random words separated by spaces. """ return " ".join([random_word(wordlist) for _ in range(n)]) def random_scrambled(wordlist, n): """ Generates a test string by generating an n-word random string and encrypting it with a sequence of random shifts. wordlist: list of words n: number of random words to generate and scamble returns: a scrambled string of n random words NOTE: This function will ONLY work once you have completed your implementation of apply_shifts! """ s = random_string(wordlist, n) + " " shifts = [(i, random.randint(0, 26)) for i in range(len(s)) if s[i-1] == ' '] return apply_shifts(s, shifts)[:-1] def get_fable_string(): """ Returns a fable in encrypted text. """ f = open("fable.txt", "r") fable = str(f.read()) f.close() return fable # (end of helper code) # ----------------------------------- # # Problem 1: Encryption # def build_coder(shift): """ Returns a dict that can apply a Caesar cipher to a letter. The cipher is defined by the shift value. Ignores non-letter characters like punctuation and numbers. shift: -27 < int < 27 returns: dict Example: >>> build_coder(3) {' ': 'c', 'A': 'D', 'C': 'F', 'B': 'E', 'E': 'H', 'D': 'G', 'G': 'J', 'F': 'I', 'I': 'L', 'H': 'K', 'K': 'N', 'J': 'M', 'M': 'P', 'L': 'O', 'O': 'R', 'N': 'Q', 'Q': 'T', 'P': 'S', 'S': 'V', 'R': 'U', 'U': 'X', 'T': 'W', 'W': 'Z', 'V': 'Y', 'Y': 'A', 'X': ' ', 'Z': 'B', 'a': 'd', 'c': 'f', 'b': 'e', 'e': 'h', 'd': 'g', 'g': 'j', 'f': 'i', 'i': 'l', 'h': 'k', 'k': 'n', 'j': 'm', 'm': 'p', 'l': 'o', 'o': 'r', 'n': 'q', 'q': 't', 'p': 's', 's': 'v', 'r': 'u', 'u': 'x', 't': 'w', 'w': 'z', 'v': 'y', 'y': 'a', 'x': ' ', 'z': 'b'} (The order of the key-value pairs may be different.) """ assert type(shift) == IntType and (shift > -27 and shift < 27) small_rotator = string.ascii_lowercase + " " cap_rotator = string.ascii_uppercase + " " #print rotator translator = {} for char in small_rotator: if not translator.has_key(char): #print rotator.index(char) + shift, rotator[(rotator.index(char) + shift) % len(rotator)] translator[char] = small_rotator[(small_rotator.index(char) + shift) % len(small_rotator)] for char in cap_rotator: if not translator.has_key(char): #print rotator.index(char) + shift, rotator[(rotator.index(char) + shift) % len(rotator)] translator[char] = cap_rotator[(cap_rotator.index(char) + shift) % len(cap_rotator)] return translator def build_encoder(shift): """ Returns a dict that can be used to encode a plain text. For example, you could encrypt the plain text by calling the following commands >>>encoder = build_encoder(shift) >>>encrypted_text = apply_coder(plain_text, encoder) The cipher is defined by the shift value. Ignores non-letter characters like punctuation and numbers. shift: 0 <= int < 27 returns: dict Example: >>> build_encoder(3) {' ': 'c', 'A': 'D', 'C': 'F', 'B': 'E', 'E': 'H', 'D': 'G', 'G': 'J', 'F': 'I', 'I': 'L', 'H': 'K', 'K': 'N', 'J': 'M', 'M': 'P', 'L': 'O', 'O': 'R', 'N': 'Q', 'Q': 'T', 'P': 'S', 'S': 'V', 'R': 'U', 'U': 'X', 'T': 'W', 'W': 'Z', 'V': 'Y', 'Y': 'A', 'X': ' ', 'Z': 'B', 'a': 'd', 'c': 'f', 'b': 'e', 'e': 'h', 'd': 'g', 'g': 'j', 'f': 'i', 'i': 'l', 'h': 'k', 'k': 'n', 'j': 'm', 'm': 'p', 'l': 'o', 'o': 'r', 'n': 'q', 'q': 't', 'p': 's', 's': 'v', 'r': 'u', 'u': 'x', 't': 'w', 'w': 'z', 'v': 'y', 'y': 'a', 'x': ' ', 'z': 'b'} (The order of the key-value pairs may be different.) HINT : Use build_coder. """ assert type(shift) == IntType and (shift >= 0 and shift < 27) return build_coder(shift) def build_decoder(shift): """ Returns a dict that can be used to decode an encrypted text. For example, you could decrypt an encrypted text by calling the following commands >>>encoder = build_encoder(shift) >>>encrypted_text = apply_coder(plain_text, encoder) >>>decrypted_text = apply_coder(plain_text, decoder) The cipher is defined by the shift value. Ignores non-letter characters like punctuation and numbers. shift: 0 <= int < 27 returns: dict Example: >>> build_decoder(3) {' ': 'x', 'A': 'Y', 'C': ' ', 'B': 'Z', 'E': 'B', 'D': 'A', 'G': 'D', 'F': 'C', 'I': 'F', 'H': 'E', 'K': 'H', 'J': 'G', 'M': 'J', 'L': 'I', 'O': 'L', 'N': 'K', 'Q': 'N', 'P': 'M', 'S': 'P', 'R': 'O', 'U': 'R', 'T': 'Q', 'W': 'T', 'V': 'S', 'Y': 'V', 'X': 'U', 'Z': 'W', 'a': 'y', 'c': ' ', 'b': 'z', 'e': 'b', 'd': 'a', 'g': 'd', 'f': 'c', 'i': 'f', 'h': 'e', 'k': 'h', 'j': 'g', 'm': 'j', 'l': 'i', 'o': 'l', 'n': 'k', 'q': 'n', 'p': 'm', 's': 'p', 'r': 'o', 'u': 'r', 't': 'q', 'w': 't', 'v': 's', 'y': 'v', 'x': 'u', 'z': 'w'} (The order of the key-value pairs may be different.) HINT : Use build_coder. """ assert type(shift) == IntType and (shift >= 0 and shift < 27) return build_coder(-shift) def apply_coder(text, coder): """ Applies the coder to the text. Returns the encoded text. text: string coder: dict with mappings of characters to shifted characters returns: text after mapping coder chars to original text Example: >>> apply_coder("Hello, world!", build_encoder(3)) 'Khoor,czruog!' >>> apply_coder("Khoor,czruog!", build_decoder(3)) 'Hello, world!' """ cipher_text = "" for char in text: if coder.has_key(char): cipher_text += coder[char] else: cipher_text += char return cipher_text def apply_shift(text, shift): """ Given a text, returns a new text Caesar shifted by the given shift offset. The empty space counts as the 27th letter of the alphabet, so spaces should be replaced by a lowercase letter as appropriate. Otherwise, lower case letters should remain lower case, upper case letters should remain upper case, and all other punctuation should stay as it is. text: string to apply the shift to shift: amount to shift the text returns: text after being shifted by specified amount. Example: >>> apply_shift('This is a test.', 8) 'Apq hq hiham a.' """ if shift > 0: encoder = build_encoder(shift) return apply_coder(text, encoder) else: decoder = build_decoder(-shift) return apply_coder(text, decoder) # # Problem 2: Codebreaking. # def find_best_shift(wordlist, text): """ Decrypts the encoded text and returns the plaintext. text: string returns: 0 <= int 27 Example: >>> s = apply_coder('Hello, world!', build_encoder(8)) >>> s 'Pmttw,hdwztl!' >>> find_best_shift(wordlist, s) returns 8 >>> apply_coder(s, build_decoder(8)) returns 'Hello, world!' """ best_shift = 0 best_count = 0 for shift_key in range(1,27): valid_count = 0 plaintext = apply_coder(text, build_decoder(shift_key)) plain_text_list = plaintext.split(" ") for word in plain_text_list: if is_word(wordlist, word): valid_count += 1 if valid_count > best_count: best_count = valid_count best_shift = shift_key return best_shift # # Problem 3: Multi-level encryption. # def apply_shifts(text, shifts): """ Applies a sequence of shifts to an input text. text: A string to apply the Ceasar shifts to shifts: A list of tuples containing the location each shift should begin and the shift offset. Each tuple is of the form (location, shift) The shifts are layered: each one is applied from its starting position all the way through the end of the string. returns: text after applying the shifts to the appropriate positions Example: >>> apply_shifts("Do Androids Dream of Electric Sheep?", [(0,6), (3, 18), (12, 16)]) 'JufYkaolfapxQdrnzmasmRyrpfdvpmEurrb?' """ cipher_text = text for shift in shifts: cipher_text = cipher_text[0:shift[0]] + apply_shift(cipher_text[shift[0]:], shift[1]) return cipher_text # # Problem 4: Multi-level decryption. # def find_best_shifts(wordlist, text): """ Given a scrambled string, returns a shift key that will decode the text to words in wordlist, or None if there is no such key. Hint: Make use of the recursive function find_best_shifts_rec(wordlist, text, start) wordlist: list of words text: scambled text to try to find the words for returns: list of tuples. each tuple is (position in text, amount of shift) Examples: >>> s = random_scrambled(wordlist, 3) >>> s 'eqorqukvqtbmultiform wyy ion' >>> shifts = find_best_shifts(wordlist, s) >>> shifts [(0, 25), (11, 2), (21, 5)] >>> apply_shifts(s, shifts) 'compositor multiform accents' >>> s = apply_shifts("Do Androids Dream of Electric Sheep?", [(0,6), (3, 18), (12, 16)]) >>> s 'JufYkaolfapxQdrnzmasmRyrpfdvpmEurrb?' >>> shifts = find_best_shifts(wordlist, s) >>> print apply_shifts(s, shifts) Do Androids Dream of Electric Sheep? """ return find_best_shifts_rec(wordlist, text, 0) def find_best_shifts_rec(wordlist, text, start): """ Given a scrambled string and a starting position from which to decode, returns a shift key that will decode the text to words in wordlist, or None if there is no such key. Hint: You will find this function much easier to implement if you use recursion. wordlist: list of words text: scambled text to try to find the words for start: where to start looking at shifts returns: list of tuples. each tuple is (position in text, amount of shift) """ if start > len(text): return [] for shift_key in range(27): decoded_text = apply_coder(text[start:], build_decoder(shift_key)) # decoded text might uncover one or more words decoded_text_list = decoded_text.split(" ") valid_words = [] for word in decoded_text_list: if is_word(wordlist, word): valid_words.append(word) #print word else: #invalid word, dont look any further break if len(valid_words) > 0: s = " ".join(valid_words) new_start = start + len(s) + 1 result = [(start, -shift_key)] print text[:start] + decoded_text, new_start try: result.extend(find_best_shifts_rec(wordlist, text[:start] + decoded_text, new_start)) return result except TypeError, e: continue # tried all shift values but found no valid word # previous shift was false positive def decrypt_fable(): """ Using the methods you created in this problem set, decrypt the fable given by the function get_fable_string(). Once you decrypt the message, be sure to include as a comment at the end of this problem set how the fable relates to your education at MIT. returns: string - fable in plain text """ fable = get_fable_string() shifts = find_best_shifts(wordlist, fable) return apply_shifts(fable, shifts) decrypt_fable() #What is the moral of the story? # #Though theoratical work is important #but successful practical implementation #based upon the theory is of utmost #importance.
{ "repo_name": "royshouvik/6.00SC", "path": "Unit 2/ps4/ps4.py", "copies": "1", "size": "13250", "license": "mit", "hash": 7224546019040608000, "line_mean": 30.8509615385, "line_max": 102, "alpha_frac": 0.5726037736, "autogenerated": false, "ratio": 3.2254138266796493, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9227644791909275, "avg_score": 0.014074561674074766, "num_lines": 416 }
# 6.00 Problem Set 4 # # Part 1 - HAIL CAESAR! # # Name : Solutions # Collaborators : <your collaborators> # Time spent : <total time> import string import random import numbers WORDLIST_FILENAME = "words.txt" # ----------------------------------- # Helper code # (you don't need to understand this helper code) def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # line: string line = inFile.readline() # wordlist: list of strings wordlist = line.split() print " ", len(wordlist), "words loaded." return wordlist wordlist = load_words() def is_word(wordlist, word): """ Determines if word is a valid word. wordlist: list of words in the dictionary. word: a possible word. returns True if word is in wordlist. Example: >>> is_word(wordlist, 'bat') returns True >>> is_word(wordlist, 'asdf') returns False """ word = word.lower() word = word.strip(" !@#$%^&*()-_+={}[]|\:;'<>?,./\"") return word in wordlist def random_word(wordlist): """ Returns a random word. wordlist: list of words returns: a word from wordlist at random """ return random.choice(wordlist) def random_string(wordlist, n): """ Returns a string containing n random words from wordlist wordlist: list of words returns: a string of random words separated by spaces. """ return " ".join([random_word(wordlist) for _ in range(n)]) def random_scrambled(wordlist, n): """ Generates a test string by generating an n-word random string and encrypting it with a sequence of random shifts. wordlist: list of words n: number of random words to generate and scamble returns: a scrambled string of n random words NOTE: This function will ONLY work once you have completed your implementation of apply_shifts! """ s = random_string(wordlist, n) + " " shifts = [(i, random.randint(0, 26)) for i in range(len(s)) if s[i-1] == ' '] return apply_shifts(s, shifts)[:-1] def get_story_string(): """ Returns a story in encrypted text. """ f = open("story.txt", "r") story = str(f.read()) f.close() return story # (end of helper code) # ----------------------------------- # # Problem 1: Encryption # def build_coder(shift): """ Returns a dict that can apply a Caesar cipher to a letter. The cipher is defined by the shift value. Ignores non-letter characters like punctuation and numbers. The empty space counts as the 27th letter of the alphabet, so spaces should be mapped to a lowercase letter as appropriate. shift: 0 <= int < 27 returns: dict Example: >>> build_coder(3) {' ': 'c', 'A': 'D', 'C': 'F', 'B': 'E', 'E': 'H', 'D': 'G', 'G': 'J', 'F': 'I', 'I': 'L', 'H': 'K', 'K': 'N', 'J': 'M', 'M': 'P', 'L': 'O', 'O': 'R', 'N': 'Q', 'Q': 'T', 'P': 'S', 'S': 'V', 'R': 'U', 'U': 'X', 'T': 'W', 'W': 'Z', 'V': 'Y', 'Y': 'A', 'X': ' ', 'Z': 'B', 'a': 'd', 'c': 'f', 'b': 'e', 'e': 'h', 'd': 'g', 'g': 'j', 'f': 'i', 'i': 'l', 'h': 'k', 'k': 'n', 'j': 'm', 'm': 'p', 'l': 'o', 'o': 'r', 'n': 'q', 'q': 't', 'p': 's', 's': 'v', 'r': 'u', 'u': 'x', 't': 'w', 'w': 'z', 'v': 'y', 'y': 'a', 'x': ' ', 'z': 'b'} (The order of the key-value pairs may be different.) """ assert shift >= 0 and shift < 27, 'shift %s is not between 0 and 27' % shift #numbers.Integral used in case of long integers assert isinstance(shift, numbers.Integral), 'shift is not an integer' coder = {} lowercase_and_space = string.ascii_lowercase + ' ' uppercase_and_space = string.ascii_uppercase + ' ' # Shift letters over shift places shifted_lowercase_and_space = lowercase_and_space[shift:] + lowercase_and_space[:shift] shifted_uppercase_and_space = uppercase_and_space[shift:] + uppercase_and_space[:shift] # Construct Caesar cipher dictionary # Add uppercase letters first so ' ' will be overwritten to point to lowercase letter for i in range(len(uppercase_and_space)): coder[uppercase_and_space[i]] = shifted_uppercase_and_space[i] for i in range(len(lowercase_and_space)): coder[lowercase_and_space[i]] = shifted_lowercase_and_space[i] return coder def apply_coder(text, coder): """ Applies the coder to the text. Returns the encoded text. text: string coder: dict with mappings of characters to shifted characters returns: text after mapping coder chars to original text Example: >>> apply_coder("Hello, world!", build_coder(3)) 'Khoor,czruog!' >>> apply_coder("Khoor,czruog!", build_coder(24)) 'Hello, world!' """ encoded_text = '' #For each letter added encoded value for letter in text: if letter in coder: encoded_text += coder[letter] #Not a letter or space. e.g. ',' so use the character as is. else: encoded_text += letter return encoded_text def apply_shift(text, shift): """ Given a text, returns a new text Caesar shifted by the given shift offset. The empty space counts as the 27th letter of the alphabet, so spaces should be replaced by a lowercase letter as appropriate. Otherwise, lower case letters should remain lower case, upper case letters should remain upper case, and all other punctuation should stay as it is. text: string to apply the shift to shift: amount to shift the text (0 <= int < 27) returns: text after being shifted by specified amount. Example: >>> apply_shift('This is a test.', 8) 'Apq hq hiham a.' >>> apply_shift('Apq hq hiham a.', 19) 'This is a test.' """ assert shift >= 0 and shift < 27, 'shift %s is not between 0 and 27' % shift return apply_coder(text, build_coder(shift)) # # Problem 2: Decryption # def find_best_shift(wordlist, text): """ Finds a shift key that can decrypt the encoded text. text: string returns: 0 <= int < 27 Example: >>> s = apply_shift('Hello, world!', 8) >>> s 'Pmttw,hdwztl!' >>> find_best_shift(wordlist, s) 19 >>> apply_shift(s, 19) 'Hello, world!' """ max_num_real_words = 0 best_shift = 0 # Try all possible shifts for shift in range(27): # Try shifting with current shift shifted_text = apply_shift(text, shift) # Split text into potential words potential_words = shifted_text.split() num_real_words = 0 # Count number of actual words for word in potential_words: if is_word(wordlist, word): num_real_words += 1 # Best shift is determined by most number of valid words produced if num_real_words > max_num_real_words: max_num_real_words = num_real_words best_shift = shift return best_shift def decrypt_story(): """ Using the methods you created in this problem set, decrypt the story given by the function get_story_string(). Once you decrypt the message, be sure to include as a comment at the end of this problem set your decryption of the story. returns: string - story in plain text """ story = get_story_string() best_shift = find_best_shift(wordlist, story) return apply_shift(story, best_shift) #What is the decrypted story? # ##Jack Florey is a mythical character created on the spur of a moment ##to help cover an insufficiently planned hack. He has been registered ##for classes at MIT twice before, but has reportedly never passed a ##class. It has been the tradition of the residents of East Campus to ##become Jack Florey for a few nights each year to educate incoming ##students in the ways, means, and ethics of hacking.
{ "repo_name": "jdhaines/MIT6.00", "path": "PS4/ps4_sol/ps4_encryption_sol.py", "copies": "2", "size": "8078", "license": "mit", "hash": 7343710550057314000, "line_mean": 29.3684210526, "line_max": 91, "alpha_frac": 0.6073285467, "autogenerated": false, "ratio": 3.4924340683095547, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.008243495867469523, "num_lines": 266 }
# 6.00 Problem Set 4 # # Part 2 - RECURSION # # Name : Solutions # Collaborators : <your collaborators> # Time spent : <total time> # # Problem 3: Recursive String Reversal # def reverse_string(string): """ Given a string, recursively returns a reversed copy of the string. For example, if the string is 'abc', the function returns 'cba'. The only string operations you are allowed to use are indexing, slicing, and concatenation. string: a string returns: a reversed string """ if string == "": return "" else: return string[-1] + reverse_string(string[:-1]) # # Problem 4: Srinian # def x_ian(x, word): """ Given a string x, returns True if all the letters in x are contained in word in the same order as they appear in x. >>> x_ian('srini', 'histrionic') True >>> x_ian('john', 'mahjong') False >>> x_ian('dina', 'dinosaur') True >>> x_ian('pangus', 'angus') False x: a string word: a string returns: True if word is x_ian, False otherwise """ if len(x) == 0: return True elif len(word) == 0: return False elif x[0] == word[0]: return x_ian(x[1:], word[1:]) else: return x_ian(x, word[1:]) # # Problem 5: Typewriter # def insert_newlines(text, line_length): """ Given text and a desired line length, wrap the text as a typewriter would. Insert a newline character ("\n") after each word that reaches or exceeds the desired line length. text: a string containing the text to wrap. line_length: the number of characters to include on a line before wrapping the next word. returns: a string, with newline characters inserted appropriately. """ return insert_newlines_rec(text, line_length, line_length-1) def insert_newlines_rec(text, line_length, rem_length): if text == '': return '' elif text[0] == ' ' and rem_length <= 0: return '\n' + insert_newlines_rec(text[1:], line_length, line_length-1) else: return text[0] + insert_newlines_rec(text[1:], line_length, rem_length-1)
{ "repo_name": "marioluan/mit-opencourseware-cs", "path": "600/unit-2/hashing-and-classes/problem-sets/solutions/recursion.py", "copies": "2", "size": "2155", "license": "mit", "hash": -2916928078220328000, "line_mean": 25.2804878049, "line_max": 81, "alpha_frac": 0.6153132251, "autogenerated": false, "ratio": 3.556105610561056, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5171418835661057, "avg_score": null, "num_lines": null }
# 6.00 Problem Set 6 # # The 6.00 Word Game # import random import string import time VOWELS = 'aeiou' CONSONANTS = 'bcdfghjklmnpqrstvwxyz' HAND_SIZE = 7 # TIME_LIMIT = 8 SCRABBLE_LETTER_VALUES = { 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10 } # ----------------------------------- # Helper code # (you don't need to understand this helper code) WORDLIST_FILENAME = "words.txt" def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # wordlist: list of strings wordlist = [] for line in inFile: wordlist.append(line.strip().lower()) print " ", len(wordlist), "words loaded." return wordlist def get_frequency_dict(sequence): """ Returns a dictionary where the keys are elements of the sequence and the values are integer counts, for the number of times that an element is repeated in the sequence. sequence: string or list return: dictionary """ # freqs: dictionary (element_type -> int) freq = {} for x in sequence: freq[x] = freq.get(x,0) + 1 return freq # (end of helper code) # ----------------------------------- # # Problem #1: Scoring a word # def get_word_score(word, n): """ Returns the score for a word. Assumes the word is a valid word. The score for a word is the sum of the points for letters in the word, plus 50 points if all n letters are used on the first go. Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is worth 3, D is worth 2, E is worth 1, and so on. word: string (lowercase letters) returns: int >= 0 """ score = 0 for letter in word: score += SCRABBLE_LETTER_VALUES[letter.lower()] if len(word) == n: score += 50 return score # # Make sure you understand how this function works and what it does! # def display_hand(hand): """ Displays the letters currently in the hand. For example: display_hand({'a':1, 'x':2, 'l':3, 'e':1}) Should print out something like: a x x l l l e The order of the letters is unimportant. hand: dictionary (string -> int) """ for letter in hand.keys(): for j in range(hand[letter]): print letter, # print all on the same line print # print an empty line # # Make sure you understand how this function works and what it does! # def deal_hand(n): """ Returns a random hand containing n lowercase letters. At least n/3 the letters in the hand should be VOWELS. Hands are represented as dictionaries. The keys are letters and the values are the number of times the particular letter is repeated in that hand. n: int >= 0 returns: dictionary (string -> int) """ hand={} num_vowels = n / 3 for i in range(num_vowels): x = VOWELS[random.randrange(0,len(VOWELS))] hand[x] = hand.get(x, 0) + 1 for i in range(num_vowels, n): x = CONSONANTS[random.randrange(0,len(CONSONANTS))] hand[x] = hand.get(x, 0) + 1 return hand # # Problem #2: Update a hand by removing letters # def update_hand(hand, word): """ Assumes that 'hand' has all the letters in word. In other words, this assumes that however many times a letter appears in 'word', 'hand' has at least as many of that letter in it. Updates the hand: uses up the letters in the given word and returns the new hand, without those letters in it. word: string hand: dictionary (string -> int) returns: dictionary (string -> int) """ freq = get_frequency_dict(word) newhand = {} for char in hand: newhand[char] = hand[char]-freq.get(char,0) return newhand #return dict( ( c, hand[c] - freq.get(c,0) ) for c in hand ) # # Problem #3: Test word validity # def is_valid_word(word, hand, points_dict): """ Returns True if word is in the word_list and is entirely composed of letters in the hand. Otherwise, returns False. Does not mutate hand or word_list. word: string hand: dictionary (string -> int) word_list: list of lowercase strings """ freq = get_frequency_dict(word) for letter in word: if freq[letter] > hand.get(letter, 0): return False return word in points_dict def get_words_to_points(word_list): """ Return a dict that maps every word in word_list to its point value. """ points_dict = {} for word in word_list: points_dict[word] = get_word_score(word, HAND_SIZE) return points_dict def pick_best_word(hand, points_dict): """ Return the highest scoring word from points_dict that can be made with the given hand. Return '.' if no words can be made with the given hand. """ score_so_far = 0 best_so_far = '.' for word,score in points_dict.items(): if is_valid_word(word, hand, points_dict): if score > score_so_far: best_so_far = word score_so_far = score return best_so_far def get_time_limit(points_dict, k): """ Return the time limit for the computer player as a function of the multiplier k. points_dict should be the same dictionary that is created by get_words_to_points. """ start_time = time.time() # Do some computation. The only purpose of the computation is so we can # figure out how long your computer takes to perform a known task. for word in points_dict: get_frequency_dict(word) get_word_score(word, HAND_SIZE) end_time = time.time() return (end_time - start_time) * k def get_word_rearrangements(word_list): d = {} for word in word_list: d[''.join(sorted(word))] = word return d # def get_subset(all_letters,n): # subset = [] def get_all_subset(hand): all_letters = '' for letter in hand.keys(): for j in range(hand[letter]): all_letters += letter def pick_best_word_faster(hand,rearrange_dict): pass # # Problem #4: Playing a hand # def play_hand(hand, word_list): """ Allows the user to play the given hand, as follows: * The hand is displayed. * The user may input a word. * An invalid word is rejected, and a message is displayed asking the user to choose another word. * When a valid word is entered, it uses up letters from the hand. * After every valid word: the score for that word is displayed, the remaining letters in the hand are displayed, and the user is asked to input another word. * The sum of the word scores is displayed when the hand finishes. * The hand finishes when there are no more unused letters. The user can also finish playing the hand by inputing a single period (the string '.') instead of a word. hand: dictionary (string -> int) word_list: list of lowercase strings """ # time_limit = float(raw_input("Enter time limit, in seconds, for players:")) total = 0 total_time = 0 initial_handlen = sum(hand.values()) while sum(hand.values()) > 0: print 'Current Hand:', display_hand(hand) start_time = time.time() userWord = pick_best_word(hand, points_dict) end_time = time.time() input_time = end_time - start_time total_time += input_time left_time = time_limit - total_time if userWord == '.': break else: isValid = is_valid_word(userWord, hand, word_list) if not isValid: print 'Invalid word, please try again.' else: points = get_word_score(userWord, initial_handlen)/max(input_time,0.001) print 'It took {:.2f} seconds to provide an answer.'.format(input_time) if left_time >= 0: total += points print '%s earned %.2f points. Total: %.2f points' % (userWord, points, total) hand = update_hand(hand, userWord) else: print 'Total time exceeds %1.0f seconds. You scored %.2f points.' \ % (time_limit, total) break print 'Total score: %.2f points.' % total # # Problem #5: Playing a game # Make sure you understand how this code works! # def play_game(word_list): """ Allow the user to play an arbitrary number of hands. * Asks the user to input 'n' or 'r' or 'e'. * If the user inputs 'n', let the user play a new (random) hand. When done playing the hand, ask the 'n' or 'e' question again. * If the user inputs 'r', let the user play the last hand again. * If the user inputs 'e', exit the game. * If the user inputs anything else, ask them again. """ hand = deal_hand(HAND_SIZE) # random init while True: cmd = raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ') if cmd == 'n': hand = deal_hand(HAND_SIZE) play_hand(hand.copy(), word_list) print elif cmd == 'r': play_hand(hand.copy(), word_list) print elif cmd == 'e': break else: print "Invalid command." # # Build data structures used for entire session and play game # if __name__ == '__main__': # global points_dict word_list = load_words() hand = deal_hand(8) print get_subset(hand) # points_dict = get_words_to_points(word_list) # time_limit = get_time_limit(points_dict, 0.5) # play_game(word_list)
{ "repo_name": "wnduan/IntroToComSci", "path": "ps6.py", "copies": "2", "size": "10053", "license": "mit", "hash": -3340011112650332700, "line_mean": 28.1391304348, "line_max": 212, "alpha_frac": 0.5944494181, "autogenerated": false, "ratio": 3.6187904967602593, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.007097626196869886, "num_lines": 345 }
# 6.00 Problem Set 6 # # The 6.00 Word Game # import random import string VOWELS = 'aeiou' CONSONANTS = 'bcdfghjklmnpqrstvwxyz' HAND_SIZE = 7 SCRABBLE_LETTER_VALUES = { 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10 } # ----------------------------------- # Helper code # (you don't need to understand this helper code) WORDLIST_FILENAME = "words.txt" def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # wordlist: list of strings wordlist = [] for line in inFile: wordlist.append(line.strip().lower()) print " ", len(wordlist), "words loaded." return wordlist def get_frequency_dict(sequence): """ Returns a dictionary where the keys are elements of the sequence and the values are integer counts, for the number of times that an element is repeated in the sequence. sequence: string or list return: dictionary """ # freqs: dictionary (element_type -> int) freq = {} for x in sequence: freq[x] = freq.get(x,0) + 1 return freq # (end of helper code) # ----------------------------------- # # Problem #1: Scoring a word # def get_word_score(word, n): """ Returns the score for a word. Assumes the word is a valid word. The score for a word is the sum of the points for letters in the word, plus 50 points if all n letters are used on the first go. Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is worth 3, D is worth 2, E is worth 1, and so on. word: string (lowercase letters) returns: int >= 0 """ score = 0 for letter in word: score += SCRABBLE_LETTER_VALUES[letter.lower()] if len(word) == n: score += 50 return score # # Make sure you understand how this function works and what it does! # def display_hand(hand): """ Displays the letters currently in the hand. For example: display_hand({'a':1, 'x':2, 'l':3, 'e':1}) Should print out something like: a x x l l l e The order of the letters is unimportant. hand: dictionary (string -> int) """ for letter in hand.keys(): for j in range(hand[letter]): print letter, # print all on the same line print # print an empty line # # Make sure you understand how this function works and what it does! # def deal_hand(n): """ Returns a random hand containing n lowercase letters. At least n/3 the letters in the hand should be VOWELS. Hands are represented as dictionaries. The keys are letters and the values are the number of times the particular letter is repeated in that hand. n: int >= 0 returns: dictionary (string -> int) """ hand={} num_vowels = n / 3 for i in range(num_vowels): x = VOWELS[random.randrange(0,len(VOWELS))] hand[x] = hand.get(x, 0) + 1 for i in range(num_vowels, n): x = CONSONANTS[random.randrange(0,len(CONSONANTS))] hand[x] = hand.get(x, 0) + 1 return hand # # Problem #2: Update a hand by removing letters # def update_hand(hand, word): """ Assumes that 'hand' has all the letters in word. In other words, this assumes that however many times a letter appears in 'word', 'hand' has at least as many of that letter in it. Updates the hand: uses up the letters in the given word and returns the new hand, without those letters in it. word: string hand: dictionary (string -> int) returns: dictionary (string -> int) """ freq = get_frequency_dict(word) newhand = {} for char in hand: newhand[char] = hand[char]-freq.get(char,0) return newhand #return dict( ( c, hand[c] - freq.get(c,0) ) for c in hand ) # # Problem #3: Test word validity # def is_valid_word(word, hand, word_list): """ Returns True if word is in the word_list and is entirely composed of letters in the hand. Otherwise, returns False. Does not mutate hand or word_list. word: string hand: dictionary (string -> int) word_list: list of lowercase strings """ freq = get_frequency_dict(word) for letter in word: if freq[letter] > hand.get(letter, 0): return False return word in word_list # # Problem #4: Playing a hand # def play_hand(hand, word_list): """ Allows the user to play the given hand, as follows: * The hand is displayed. * The user may input a word. * An invalid word is rejected, and a message is displayed asking the user to choose another word. * When a valid word is entered, it uses up letters from the hand. * After every valid word: the score for that word is displayed, the remaining letters in the hand are displayed, and the user is asked to input another word. * The sum of the word scores is displayed when the hand finishes. * The hand finishes when there are no more unused letters. The user can also finish playing the hand by inputing a single period (the string '.') instead of a word. hand: dictionary (string -> int) word_list: list of lowercase strings """ total = 0 initial_handlen = sum(hand.values()) while sum(hand.values()) > 0: print 'Current Hand:', display_hand(hand) userWord = raw_input('Enter word, or a . to indicate that you are finished: ') if userWord == '.': break else: isValid = is_valid_word(userWord, hand, word_list) if not isValid: print 'Invalid word, please try again.' else: points = get_word_score(userWord, initial_handlen) total += points print '%s earned %d points. Total: %d points' % (userWord, points, total) hand = update_hand(hand, userWord) print 'Total score: %d points.' % total # # Problem #5: Playing a game # Make sure you understand how this code works! # def play_game(word_list): """ Allow the user to play an arbitrary number of hands. * Asks the user to input 'n' or 'r' or 'e'. * If the user inputs 'n', let the user play a new (random) hand. When done playing the hand, ask the 'n' or 'e' question again. * If the user inputs 'r', let the user play the last hand again. * If the user inputs 'e', exit the game. * If the user inputs anything else, ask them again. """ hand = deal_hand(HAND_SIZE) # random init while True: cmd = raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ') if cmd == 'n': hand = deal_hand(HAND_SIZE) play_hand(hand.copy(), word_list) print elif cmd == 'r': play_hand(hand.copy(), word_list) print elif cmd == 'e': break else: print "Invalid command." # # Build data structures used for entire session and play game # if __name__ == '__main__': word_list = load_words() play_game(word_list)
{ "repo_name": "feliposz/learning-stuff", "path": "python/ps6_download.py", "copies": "1", "size": "7545", "license": "mit", "hash": 8077040483754716000, "line_mean": 27.4716981132, "line_max": 212, "alpha_frac": 0.5945659377, "autogenerated": false, "ratio": 3.6414092664092665, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9692747779115887, "avg_score": 0.008645484998675904, "num_lines": 265 }
# 6.00 Problem Set 8 # # Intelligent Course Advisor # # Name: Felipo Soranz # Time: # 18:18 started # 18:24 problem 1 # 19:00 problem 2 # 19:17 problem 3 import time SUBJECT_FILENAME = "subjects.txt" VALUE, WORK = 0, 1 # # Problem 1: Building A Subject Dictionary # def loadSubjects(filename): """ Returns a dictionary mapping subject name to (value, work), where the name is a string and the value and work are integers. The subject information is read from the file named by the string filename. Each line of the file contains a string of the form "name,value,work". returns: dictionary mapping subject name to (value, work) """ subjects = {} inputFile = open(filename) for line in inputFile: course, value, word = line.strip().split(',') subjects[course] = (int(value), int(word)) return subjects # TODO: Instead of printing each line, modify the above to parse the name, # value, and work of each subject and create a dictionary mapping the name # to the (value, work). def printSubjects(subjects): """ Prints a string containing name, value, and work of each subject in the dictionary of subjects and total value and work of all subjects """ totalVal, totalWork = 0,0 if len(subjects) == 0: return 'Empty SubjectList' res = 'Course\tValue\tWork\n======\t====\t=====\n' subNames = list(subjects.keys()) subNames.sort() for s in subNames: val = subjects[s][VALUE] work = subjects[s][WORK] res = res + s + '\t' + str(val) + '\t' + str(work) + '\n' totalVal += val totalWork += work res = res + '\nTotal Value:\t' + str(totalVal) +'\n' res = res + 'Total Work:\t' + str(totalWork) + '\n' print(res) def cmpValue(subInfo1, subInfo2): """ Returns True if value in (value, work) tuple subInfo1 is GREATER than value in (value, work) tuple in subInfo2 """ val1 = subInfo1[VALUE] val2 = subInfo2[VALUE] return val1 > val2 def cmpWork(subInfo1, subInfo2): """ Returns True if work in (value, work) tuple subInfo1 is LESS than than work in (value, work) tuple in subInfo2 """ work1 = subInfo1[WORK] work2 = subInfo2[WORK] return work1 < work2 def cmpRatio(subInfo1, subInfo2): """ Returns True if value/work in (value, work) tuple subInfo1 is GREATER than value/work in (value, work) tuple in subInfo2 """ val1 = subInfo1[VALUE] val2 = subInfo2[VALUE] work1 = subInfo1[WORK] work2 = subInfo2[WORK] return float(val1) / work1 > float(val2) / work2 # # Problem 2: Subject Selection By Greedy Optimization # def greedyAdvisor(subjects, maxWork, comparator): """ Returns a dictionary mapping subject name to (value, work) which includes subjects selected by the algorithm, such that the total work of subjects in the dictionary is not greater than maxWork. The subjects are chosen using a greedy algorithm. The subjects dictionary should not be mutated. subjects: dictionary mapping subject name to (value, work) maxWork: int >= 0 comparator: function taking two tuples and returning a bool returns: dictionary mapping subject name to (value, work) """ selected = {} changed = True while changed: changed = False best = None for key in subjects.keys(): #print("key =", key) #print("best =", best) if key in selected: continue elif subjects[key][WORK] <= maxWork and (best == None or comparator(subjects[key], subjects[best])): best = key changed = True #print("found better: ", best, subjects[best]) if changed: maxWork -= subjects[best][WORK] selected[best] = subjects[best] return selected # Tests ##smallCatalog = {'6.00': (16, 8), '1.00': (7, 7), '6.01': (5, 3), '15.01': (9, 6)} ##print("cmpValue") ##printSubjects(greedyAdvisor(smallCatalog, 15, cmpValue)) ##print("cmpWork") ##printSubjects(greedyAdvisor(smallCatalog, 15, cmpWork)) ##print("cmpRatio") ##printSubjects(greedyAdvisor(smallCatalog, 15, cmpRatio)) ## ##subjects = loadSubjects(SUBJECT_FILENAME) ##print("cmpValue") ##printSubjects(greedyAdvisor(subjects, 15, cmpValue)) ##print("cmpWork") ##printSubjects(greedyAdvisor(subjects, 15, cmpWork)) ##print("cmpRatio") ##printSubjects(greedyAdvisor(subjects, 15, cmpRatio)) def bruteForceAdvisor(subjects, maxWork): """ Returns a dictionary mapping subject name to (value, work), which represents the globally optimal selection of subjects using a brute force algorithm. subjects: dictionary mapping subject name to (value, work) maxWork: int >= 0 returns: dictionary mapping subject name to (value, work) """ nameList = list(subjects.keys()) tupleList = list(subjects.values()) bestSubset, bestSubsetValue = \ bruteForceAdvisorHelper(tupleList, maxWork, 0, None, None, [], 0, 0) outputSubjects = {} for i in bestSubset: outputSubjects[nameList[i]] = tupleList[i] return outputSubjects def bruteForceAdvisorHelper(subjects, maxWork, i, bestSubset, bestSubsetValue, subset, subsetValue, subsetWork): global num_calls num_calls += 1 # Hit the end of the list. if i >= len(subjects): if bestSubset == None or subsetValue > bestSubsetValue: # Found a new best. return subset[:], subsetValue else: # Keep the current best. return bestSubset, bestSubsetValue else: s = subjects[i] # Try including subjects[i] in the current working subset. if subsetWork + s[WORK] <= maxWork: subset.append(i) bestSubset, bestSubsetValue = bruteForceAdvisorHelper(subjects, maxWork, i+1, bestSubset, bestSubsetValue, subset, subsetValue + s[VALUE], subsetWork + s[WORK]) subset.pop() bestSubset, bestSubsetValue = bruteForceAdvisorHelper(subjects, maxWork, i+1, bestSubset, bestSubsetValue, subset, subsetValue, subsetWork) return bestSubset, bestSubsetValue # # Problem 3: Subject Selection By Brute Force # def bruteForceTime(): """ Runs tests on bruteForceAdvisor and measures the time required to compute an answer. """ subjects = loadSubjects(SUBJECT_FILENAME) for work in range(1, 10): start = time.time() bruteForceAdvisor(subjects, work) elapsed = time.time() - start print("Elapsed time for work =", work, " was =", elapsed, "seconds") # Problem 3 Observations # ====================== # # TODO: write here your observations regarding bruteForceTime's performance #bruteForceTime() ##Elapsed time for work = 1 was = 0.016000032424926758 seconds ##Elapsed time for work = 2 was = 0.03099989891052246 seconds ##Elapsed time for work = 3 was = 0.12400007247924805 seconds ##Elapsed time for work = 4 was = 0.42100000381469727 seconds ##Elapsed time for work = 5 was = 1.2639999389648438 seconds ##Elapsed time for work = 6 was = 3.5879998207092285 seconds ##Elapsed time for work = 7 was = 12.869999885559082 seconds ##Elapsed time for work = 8 was = 34.37399983406067 seconds ##Elapsed time for work = 9 was = 92.40900015830994 seconds # # Problem 4: Subject Selection By Dynamic Programming # def dpAdvisor(subjects, maxWork): """ Returns a dictionary mapping subject name to (value, work) that contains a set of subjects that provides the maximum value without exceeding maxWork. subjects: dictionary mapping subject name to (value, work) maxWork: int >= 0 returns: dictionary mapping subject name to (value, work) """ courses = [] works = [] values = [] for key in subjects.keys(): courses.append(key) works.append(subjects[key][0]) values.append(subjects[key][1]) memo = {} winners = dpAdvisorHelper(works, values, len(values) - 1, maxWork, memo) results = {} for i in winners: results[courses[i]] = (values[i], works[i]) return results # TODO: This implementation is incomplete # The result is not optimal def dpAdvisorHelper(works, values, i, available_work, memo): global num_calls num_calls += 1 try: return memo[(i, available_work)] except KeyError: pass if i == 0: if works[i] <= available_work: memo[(i, available_work)] = [i] return [i] else: return [] without_i = dpAdvisorHelper(works, values, i - 1, available_work, memo) if works[i] > available_work: memo[(i, available_work)] = without_i return without_i else: with_i = [i] + dpAdvisorHelper(works, values, i - 1, available_work - works[i], memo) if branch_value(with_i, values) >= branch_value(without_i, values): winners = with_i else: winners = without_i memo[(i, available_work)] = winners return winners def branch_value(branch, value): total = 0 for i in branch: total += value[i] return total ##subjects = {'a1': (16, 8), 'b1': (7, 7), 'c1': (5, 3), 'd1': (9, 6)} ##work = 20 ##subjects = loadSubjects(SUBJECT_FILENAME) ##work = 5 ##print("\n>>> dpAdvisor <<< \n") ##num_calls = 0 ##printSubjects(dpAdvisor(subjects, work)) ##print("number of calls =", num_calls) ## ##print("\n>>> bruteForceAdvisor <<< \n") ##num_calls = 0 ##printSubjects(bruteForceAdvisor(subjects, work)) ##print("number of calls =", num_calls) num_calls = 0 # # Problem 5: Performance Comparison # def dpTime(): """ Runs tests on dpAdvisor and measures the time required to compute an answer. """ global num_calls subjects = loadSubjects(SUBJECT_FILENAME) for work in range(5, 100, 10): start = time.time() num_calls = 0 result = dpAdvisor(subjects, work) #printSubjects(result) elapsed = time.time() - start print("Elapsed time for work =", work, " was =", elapsed, "seconds") # Problem 5 Observations # ====================== # # TODO: write here your observations regarding dpAdvisor's performance and # how its performance compares to that of bruteForceAdvisor. ##dpTime() ####Elapsed time for work = 5 was = 0.019999980926513672 seconds ####Elapsed time for work = 15 was = 0.08999991416931152 seconds ####Elapsed time for work = 25 was = 0.15999984741210938 seconds ####Elapsed time for work = 35 was = 0.25999999046325684 seconds ####Elapsed time for work = 45 was = 0.3710000514984131 seconds ####Elapsed time for work = 55 was = 0.49899983406066895 seconds ####Elapsed time for work = 65 was = 0.35899996757507324 seconds ####Elapsed time for work = 75 was = 0.7799999713897705 seconds ####Elapsed time for work = 85 was = 0.9200000762939453 seconds ####Elapsed time for work = 95 was = 1.1349999904632568 seconds
{ "repo_name": "feliposz/learning-stuff", "path": "python/ps8.py", "copies": "1", "size": "11093", "license": "mit", "hash": -1832485670571378200, "line_mean": 31.1536231884, "line_max": 112, "alpha_frac": 0.6405841522, "autogenerated": false, "ratio": 3.6063068920676202, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.474689104426762, "avg_score": null, "num_lines": null }
# 6.00 Problem Set 9 import numpy import random import pylab #from ps8b import * from ps8b_precompiled_27 import * # # PROBLEM 1 # def simulationDelayedTreatment(numTrials): """ Runs simulations and make histograms for problem 1. Runs numTrials simulations to show the relationship between delayed treatment and patient outcome using a histogram. Histograms of final total virus populations are displayed for delays of 300, 150, 75, 0 timesteps (followed by an additional 150 timesteps of simulation). numTrials: number of simulation runs to execute (an integer) """ def do_plot(delays, final_pops): for i in range(len(delays)): pylab.subplot(len(delays), 1, i + 1) pylab.hist(final_pops[i]) pylab.xlabel('Final Virus Population') pylab.ylabel('No. of trials') final_steps = 150 numViruses = 100 maxPop = 1000 maxBirthProb = 0.1 clearProb = 0.05 resistances = {'guttagonol': False} mutProb = 0.005 drug_list = resistances.keys() delays = [300, 150, 75, 0] final_pops = [] for delay in delays: tot_pop = [] for _i in range(numTrials): viruses = [ResistantVirus(maxBirthProb, clearProb, resistances, mutProb) for _i in range(numViruses)] patient = TreatedPatient(viruses, maxPop) for _i in range(delay + final_steps): if _i == delay: for drug in drug_list: patient.addPrescription(drug) patient.update() tot_pop.append(patient.getTotalPop()) final_pops.append(tot_pop) do_plot(delays, final_pops) pylab.show() #simulationDelayedTreatment(100) # # PROBLEM 2 # def simulationTwoDrugsDelayedTreatment(numTrials): """ Runs simulations and make histograms for problem 2. Runs numTrials simulations to show the relationship between administration of multiple drugs and patient outcome. Histograms of final total virus populations are displayed for lag times of 300, 150, 75, 0 timesteps between adding drugs (followed by an additional 150 timesteps of simulation). numTrials: number of simulation runs to execute (an integer) """ def do_plot(delays, final_pops): for i in range(len(delays)): pylab.subplot(len(delays), 1, i + 1) pylab.hist(final_pops[i]) pylab.xlabel('Final Virus Population') pylab.ylabel('No. of trials') const_steps = 150 numViruses = 100 maxPop = 1000 maxBirthProb = 0.1 clearProb = 0.05 resistances = {'guttagonol': False, 'grimpex': False} mutProb = 0.005 delays = [300, 150, 75, 0] final_pops = [] for delay in delays: tot_pop = [] for _i in range(numTrials): viruses = [ResistantVirus(maxBirthProb, clearProb, resistances, mutProb) for _i in range(numViruses)] patient = TreatedPatient(viruses, maxPop) for _i in range(const_steps + delay + const_steps): if _i == const_steps: patient.addPrescription('guttagonol') if _i == const_steps + delay: patient.addPrescription('grimpex') patient.update() tot_pop.append(patient.getTotalPop()) final_pops.append(tot_pop) do_plot(delays, final_pops) pylab.show() simulationTwoDrugsDelayedTreatment(200)
{ "repo_name": "fossilet/6.00x", "path": "week9/problemset9/ps9.py", "copies": "1", "size": "3754", "license": "mit", "hash": -8648047929270670000, "line_mean": 30.2833333333, "line_max": 80, "alpha_frac": 0.5788492275, "autogenerated": false, "ratio": 3.799595141700405, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4878444369200405, "avg_score": null, "num_lines": null }
# 6.00x Problem Set 10 # Graph optimization # # A set of data structures to represent graphs # class Node(object): def __init__(self, name): self.name = str(name) def getName(self): return self.name def __str__(self): return self.name def __repr__(self): return self.name def __eq__(self, other): return self.name == other.name def __ne__(self, other): return not self.__eq__(other) class Edge(object): def __init__(self, src, dest): self.src = src self.dest = dest def getSource(self): return self.src def getDestination(self): return self.dest def __str__(self): return '{0}->{1}'.format(self.src, self.dest) class Digraph(object): """ A directed graph """ def __init__(self): # A Python Set is basically a list that doesn't allow duplicates. # Entries into a set must be hashable (where have we seen this before?) # Because it is backed by a hashtable, lookups are O(1) as opposed to the O(n) of a list (nifty!) # See http://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset self.nodes = set([]) self.edges = {} def addNode(self, node): if node in self.nodes: # Even though self.nodes is a Set, we want to do this to make sure we # don't add a duplicate entry for the same node in the self.edges list. raise ValueError('Duplicate node') else: self.nodes.add(node) self.edges[node] = [] def addEdge(self, edge): src = edge.getSource() dest = edge.getDestination() if not(src in self.nodes and dest in self.nodes): raise ValueError('Node not in graph') self.edges[src].append(dest) def childrenOf(self, node): return self.edges[node] def hasNode(self, node): return node in self.nodes def __str__(self): res = '' for k in self.edges: for d in self.edges[str(k)]: res = '{0}{1}->{2}\n'.format(res, k, d) return res[:-1]
{ "repo_name": "fossilet/6.00x", "path": "week10/problemset10/graph.py", "copies": "1", "size": "2137", "license": "mit", "hash": 8372579474059721000, "line_mean": 31.3787878788, "line_max": 105, "alpha_frac": 0.5699578849, "autogenerated": false, "ratio": 3.736013986013986, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.975814204898567, "avg_score": 0.009565964385663026, "num_lines": 66 }
# 6.00x Problem Set 10 # Graph optimization # # A set of data structures to represent graphs # class Node(object): def __init__(self, name): self.name = str(name) def getName(self): return self.name def __str__(self): return self.name def __repr__(self): return self.name def __eq__(self, other): return self.name == other.name def __ne__(self, other): return not self.__eq__(other) def __hash__(self): # Override the default hash method # Think: Why would we want to do this? return self.name.__hash__() class Edge(object): def __init__(self, src, dest): self.src = src self.dest = dest def getSource(self): return self.src def getDestination(self): return self.dest def __str__(self): return '{0}->{1}'.format(self.src, self.dest) class Digraph(object): """ A directed graph """ def __init__(self): # A Python Set is basically a list that doesn't allow duplicates. # Entries into a set must be hashable (where have we seen this before?) # Because it is backed by a hashtable, lookups are O(1) as opposed to the O(n) of a list (nifty!) # See http://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset self.nodes = set([]) self.edges = {} def addNode(self, node): if node in self.nodes: # Even though self.nodes is a Set, we want to do this to make sure we # don't add a duplicate entry for the same node in the self.edges list. raise ValueError('Duplicate node') else: self.nodes.add(node) self.edges[node] = [] def addEdge(self, edge): src = edge.getSource() dest = edge.getDestination() if not(src in self.nodes and dest in self.nodes): raise ValueError('Node not in graph') self.edges[src].append(dest) def childrenOf(self, node): return self.edges[node] def hasNode(self, node): return node in self.nodes def __str__(self): res = '' for k in self.edges: for d in self.edges[k]: res = '{0}{1}->{2}\n'.format(res, k, d) return res[:-1] # class WeightedEdge(Edge): # # def __init__(self, src, dest, total_distance, distance_outdoors): # super(WeightedEdge, self).__init__(src, dest) # self.total_distance = total_distance # self.distance_outdoors = distance_outdoors # self.weights = (self.total_distance, self.distance_outdoors) # # def getWeights(self): # return self.weights # # def getTotalDistance(self): # return self.total_distance # # def getOutdoorDistance(self): # return self.distance_outdoors # # def __str__(self): # return '{0}->{1} ({2}, {3})'.format(self.src, self.dest, self.total_distance, self.distance_outdoors) # # class WeightedDigraph(Digraph): # def __init__(self): # self.nodes = set([]) # self.children = {} # self.edges = {} # # def addNode(self, node): # if node in self.nodes: # raise ValueError('Duplicate node') # else: # self.nodes.add(node) # self.children[node] = [] # # def addEdge(self, edge): # src = edge.getSource() # dest = edge.getDestination() # weights = edge.getWeights() # if not(src in self.nodes and dest in self.nodes): # raise ValueError('Node not in graph') # self.children[src].append(dest) # self.edges[(src, dest)] = weights # # def childrenOf(self, node): # return self.children[node] # # def __str__(self): # res = '' # for k in self.edges: # #for d in self.edges[k]: # res = res + str(k) + ': ' + str(self.edges[k]) + '\n' # return res[:-1] # def addEdge(self, edge): # src = edge.getSource() # dest= edge.getDestination() # total_distance = edge.getTotalDistance() # outdoor_distance = edge.getOutdoorDistance() # if not (src in self.nodes and dest in self.nodes): # raise ValueError('Node not in graph') # self.edges[src].append(dest) # def __str__(self): # res = '' # for k in self.edges: # for d in self.edges[k]: # res = '{0}{1}->{2} ({3}, {4})\n'.format(res, k, d, getTotalDistance(), getOutdoorDistance()) # return res[:-1] def floatify(tup): return str((float(tup[0]), float(tup[1]))) class WeightedDigraph(Digraph): # def addEdge(self, edge): # src = edge.getSource() # dest = edge.getDestination() # if not(src in self.nodes and dest in self.nodes): # raise ValueError('Node not in graph') # self.edges[src].append(edge) def __init__(self): self.nodes = set([]) self.children = {} self.edges = {} def addNode(self, node): if node in self.nodes: raise ValueError('Duplicate node') else: self.nodes.add(node) self.children[node] = [] def addEdge(self, edge): src = edge.getSource() dest = edge.getDestination() weights = edge.getWeights() if not(src in self.nodes and dest in self.nodes): raise ValueError('Node not in graph') # if (src, dest) not in self.edges.keys(): # raise ValueError('Node not in graph') # elif (src, dest) in self.edges.keys() and self.edges[(src, dest)] == weights: # raise ValueError('Node not in graph') self.children[src].append(dest) self.edges[(src, dest)] = weights def childrenOf(self, node): return self.children[node] def edgesFrom(self,node): '''Not implemented''' return [e for e in self.edges if e[0] == node] def __str__(self): res = '' for k,v in self.edges.iteritems(): res = '{0}{1[0]}->{1[1]} {2}'.format(res, k, floatify(v)) + '\n' return res[:-1] class WeightedEdge(Edge): # def __init__(self, src, dest, total_distance, outdoors_distance): # super(WeightedEdge, self).__init__(src, dest) # self.total_distance = total_distance # self.outdoors_distance = outdoors_distance def __init__(self, src, dest, total_distance, outdoor_distance): Edge.__init__(self, src, dest) self.total_distance = total_distance self.outdoor_distance = outdoor_distance self.weights = (total_distance, outdoor_distance) def getTotalDistance(self): return self.weights[0] def getOutdoorDistance(self): return self.weights[1] def getWeights(self): return self.weights def __str__(self): return '{0}->{1} {2}'.format(self.src, self.dest, str(self.weights)) nx = Node('x') ny = Node('y') nz = Node('z') e1 = WeightedEdge(nx, ny, 18, 8) e2 = WeightedEdge(ny, nz, 20, 1) e3 = WeightedEdge(nz, nx, 7, 6) g = WeightedDigraph() g.addNode(nx) g.addNode(ny) g.addNode(nz) g.addEdge(e1) g.addEdge(e2) g.addEdge(e3) print g nj = Node('j') nk = Node('k') nm = Node('m') ng = Node('g') g = WeightedDigraph() g.addNode(nj) g.addNode(nk) g.addNode(nm) g.addNode(ng) randomEdge = WeightedEdge(nm, ng, 13, 9) g.addEdge(randomEdge) randomEdge = WeightedEdge(ng, nj, 19, 8) g.addEdge(randomEdge) randomEdge = WeightedEdge(nm, nk, 69, 30) g.addEdge(randomEdge) randomEdge = WeightedEdge(nk, ng, 81, 80) g.addEdge(randomEdge) randomEdge = WeightedEdge(nj, ng, 26, 9) g.addEdge(randomEdge) randomEdge = WeightedEdge(ng, nk, 60, 13) g.addEdge(randomEdge) randomEdge = WeightedEdge(nk, nm, 52, 21) g.addEdge(randomEdge) randomEdge = WeightedEdge(nm, nk, 45, 31) g.addEdge(randomEdge) print g
{ "repo_name": "b3ngmann/python-pastime", "path": "ps10/graph.py", "copies": "1", "size": "8029", "license": "mit", "hash": 4716473312965881000, "line_mean": 28.9626865672, "line_max": 111, "alpha_frac": 0.5648275003, "autogenerated": false, "ratio": 3.3454166666666665, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4410244166966666, "avg_score": null, "num_lines": null }
# 6.00x Problem Set 3 # # Successive Approximation: Newton's Method # # Problem 1: Polynomials def evaluatePoly(poly, x): ''' Computes the value of a polynomial function at given value x. Returns that value as a float. poly: list of numbers, length > 0 x: number returns: float ''' s = 0 for i in xrange(len(poly)): s += poly[i]*(x**i) return float(s) # Problem 2: Derivatives def computeDeriv(poly): ''' Computes and returns the derivative of a polynomial function as a list of floats. If the derivative is 0, returns [0.0]. poly: list of numbers, length &gt; 0 returns: list of numbers (floats) ''' if len(poly) == 1: return [0.0] d = [] for i in xrange(1, len(poly)): d.append(float(poly[i]*i)) return d # Problem 3: Newton's Method def computeRoot(poly, x_0, epsilon): ''' Uses Newton's method to find and return a root of a polynomial function. Returns a list containing the root and the number of iterations required to get to the root. poly: list of numbers, length > 1. Represents a polynomial function containing at least one real root. The derivative of this polynomial function at x_0 is not 0. x_0: float epsilon: float > 0 returns: list [float, int] ''' it = 0 while True: if abs(evaluatePoly(poly, x_0)) <= epsilon: return [x_0, it] it += 1 x_1 = x_0 - evaluatePoly(poly, x_0)/evaluatePoly(computeDeriv(poly), x_0) x_0 = x_1
{ "repo_name": "juampi/6.00x", "path": "ProblemSet03/ps3_newton.py", "copies": "1", "size": "1557", "license": "mit", "hash": 4112787284032387600, "line_mean": 26.3333333333, "line_max": 81, "alpha_frac": 0.6133590238, "autogenerated": false, "ratio": 3.562929061784897, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46762880855848976, "avg_score": null, "num_lines": null }
# 6.00x Problem Set 4A Template # # The 6.00 Word Game # Created by: Kevin Luu <luuk> and Jenna Wiens <jwiens> # Modified by: Sarina Canelake <sarina> # import random from duplicity._librsync import librsyncError VOWELS = 'aeiou' CONSONANTS = 'bcdfghjklmnpqrstvwxyz' HAND_SIZE = 7 SCRABBLE_LETTER_VALUES = { 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10 } # ----------------------------------- # Helper code # (you don't need to understand this helper code) WORDLIST_FILENAME = "words.txt" def loadWords(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # wordList: list of strings wordList = [] for line in inFile: wordList.append(line.strip().lower()) print " ", len(wordList), "words loaded." return wordList def getFrequencyDict(sequence): """ Returns a dictionary where the keys are elements of the sequence and the values are integer counts, for the number of times that an element is repeated in the sequence. sequence: string or list return: dictionary """ # freqs: dictionary (element_type -> int) freq = {} for x in sequence: freq[x] = freq.get(x, 0) + 1 return freq # (end of helper code) # ----------------------------------- # # Problem #1: Scoring a word # def getWordScore(word, n): """ Returns the score for a word. Assumes the word is a valid word. The score for a word is the sum of the points for letters in the word, multiplied by the length of the word, PLUS 50 points if all n letters are used on the first turn. Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is worth 3, D is worth 2, E is worth 1, and so on (see SCRABBLE_LETTER_VALUES) word: string (lowercase letters) n: integer (HAND_SIZE; i.e., hand size required for additional points) returns: int >= 0 """ score = 0 for char in word: score += SCRABBLE_LETTER_VALUES[char] score *= len(word) if len(word) >= n: score += 50 return score # # Problem #2: Make sure you understand how this function works and what it does! # def displayHand(hand): """ Displays the letters currently in the hand. For example: >>> displayHand({'a':1, 'x':2, 'l':3, 'e':1}) Should print out something like: a x x l l l e The order of the letters is unimportant. hand: dictionary (string -> int) """ for letter in hand.keys(): for j in range(hand[letter]): print letter, # print all on the same line print # print an empty line # # Problem #2: Make sure you understand how this function works and what it does! # def dealHand(n): """ Returns a random hand containing n lowercase letters. At least n/3 the letters in the hand should be VOWELS. Hands are represented as dictionaries. The keys are letters and the values are the number of times the particular letter is repeated in that hand. n: int >= 0 returns: dictionary (string -> int) """ hand = {} numVowels = n / 3 for i in range(numVowels): x = VOWELS[random.randrange(0, len(VOWELS))] hand[x] = hand.get(x, 0) + 1 for i in range(numVowels, n): x = CONSONANTS[random.randrange(0, len(CONSONANTS))] hand[x] = hand.get(x, 0) + 1 return hand # # Problem #2: Update a hand by removing letters # def updateHand(hand, word): """ Assumes that 'hand' has all the letters in word. In other words, this assumes that however many times a letter appears in 'word', 'hand' has at least as many of that letter in it. Updates the hand: uses up the letters in the given word and returns the new hand, without those letters in it. Has no side effects: does not modify hand. word: string hand: dictionary (string -> int) returns: dictionary (string -> int) """ current_hand = hand.copy() for char in word: current_hand[char] -= 1 return current_hand # # Problem #3: Test word validity # def isValidWord(word, hand, wordList): """ Returns True if word is in the wordList and is entirely composed of letters in the hand. Otherwise, returns False. Does not mutate hand or wordList. word: string hand: dictionary (string -> int) wordList: list of lowercase strings """ if not word in wordList: return False word_letters = getFrequencyDict(word) for c in word_letters.keys(): if not c in hand.keys() or word_letters[c] > hand[c]: return False return True # # Problem #4: Playing a hand # def calculateHandlen(hand): """ Returns the length (number of letters) in the current hand. hand: dictionary (string-> int) returns: integer """ count = 0 for c in hand: count += hand[c] return count def playHand(hand, wordList, n): """ Allows the user to play the given hand, as follows: * The hand is displayed. * The user may input a word or a single period (the string ".") to indicate they're done playing * Invalid words are rejected, and a message is displayed asking the user to choose another word until they enter a valid word or "." * When a valid word is entered, it uses up letters from the hand. * After every valid word: the score for that word is displayed, the remaining letters in the hand are displayed, and the user is asked to input another word. * The sum of the word scores is displayed when the hand finishes. * The hand finishes when there are no more unused letters or the user inputs a "." hand: dictionary (string -> int) wordList: list of lowercase strings n: integer (HAND_SIZE; i.e., hand size required for additional points) """ total_score = 0 while calculateHandlen(hand) > 0: print "Current hand: ", displayHand(hand) player_input = raw_input('Enter word, or a "." to indicate that you are finished: ') if player_input == '.': break else: if not isValidWord(player_input, hand, wordList): print "Invalid word, please try again." print else: score = getWordScore(player_input, n) total_score += score print '"' + player_input + '" earned ' + str(score) + ' points. Total: ' + str(total_score) + ' points.' print hand = updateHand(hand, player_input) if calculateHandlen(hand) == 0: print "Run out of letters. Total score: " + str(total_score) + " points." else: print "Goodbye! Total score: " + str(total_score) + " points." # # Problem #5: Playing a game # def playGame(wordList): """ Allow the user to play an arbitrary number of hands. 1) Asks the user to input 'n' or 'r' or 'e'. * If the user inputs 'n', let the user play a new (random) hand. * If the user inputs 'r', let the user play the last hand again. * If the user inputs 'e', exit the game. * If the user inputs anything else, tell them their input was invalid. 2) When done playing the hand, repeat from step 1 """ last_hand = None while True: player_input = raw_input("Enter n to deal a new hand, r to replay the last hand, or e to end game: ") if player_input == 'r': if last_hand is None: print "You have not played a hand yet. Please play a new hand first!" else: playHand(last_hand, wordList, HAND_SIZE) print elif player_input == 'n': last_hand = dealHand(HAND_SIZE) playHand(last_hand, wordList, HAND_SIZE) print elif player_input == 'e': break else: print "Invalid command." # # Build data structures used for entire session and play game # if __name__ == '__main__': wordList = loadWords() playGame(wordList)
{ "repo_name": "FylmTM/edX-code", "path": "MITx_6.00.1x/problem_set_4/ps4a.py", "copies": "1", "size": "8443", "license": "mit", "hash": -4228921071101049300, "line_mean": 28.1137931034, "line_max": 120, "alpha_frac": 0.6057088713, "autogenerated": false, "ratio": 3.6901223776223775, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47958312489223776, "avg_score": null, "num_lines": null }
# 6.00x Problem Set 4A Template # # The 6.00 Word Game # Created by: Kevin Luu <luuk> and Jenna Wiens <jwiens> # Modified by: Sarina Canelake <sarina> # import random import string from operator import indexOf VOWELS = 'aeiou' CONSONANTS = 'bcdfghjklmnpqrstvwxyz' HAND_SIZE = 7 SCRABBLE_LETTER_VALUES = { 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10 } # ----------------------------------- # Helper code # (you don't need to understand this helper code) WORDLIST_FILENAME = "words.txt" def loadWords(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # wordList: list of strings wordList = [] for line in inFile: wordList.append(line.strip().lower()) print " ", len(wordList), "words loaded." return wordList def getFrequencyDict(sequence): """ Returns a dictionary where the keys are elements of the sequence and the values are integer counts, for the number of times that an element is repeated in the sequence. sequence: string or list return: dictionary """ # freqs: dictionary (element_type -> int) freq = {} for x in sequence: freq[x] = freq.get(x,0) + 1 return freq # (end of helper code) # ----------------------------------- # # Problem #1: Scoring a word # def getWordScore(word, n): """ Returns the score for a word. Assumes the word is a valid word. The score for a word is the sum of the points for letters in the word, multiplied by the length of the word, PLUS 50 points if all n letters are used on the first turn. Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is worth 3, D is worth 2, E is worth 1, and so on (see SCRABBLE_LETTER_VALUES) word: string (lowercase letters) n: integer (HAND_SIZE; i.e., hand size required for additional points) returns: int >= 0 """ if word == "": return 0 else: z = 0 for i in word: if i in SCRABBLE_LETTER_VALUES: z = z + SCRABBLE_LETTER_VALUES[i] else: continue if len(word) == n: return (len(word)*z) + 50 else: return len(word)*z # # Problem #2: Make sure you understand how this function works and what it does! # def displayHand(hand): """ Displays the letters currently in the hand. For example: >>> displayHand({'a':1, 'x':2, 'l':3, 'e':1}) Should print out something like: a x x l l l e The order of the letters is unimportant. hand: dictionary (string -> int) """ for letter in hand.keys(): for j in range(hand[letter]): print letter, # print all on the same line print "" return # # Problem #2: Make sure you understand how this function works and what it does! # def dealHand(n): """ Returns a random hand containing n lowercase letters. At least n/3 the letters in the hand should be VOWELS. Hands are represented as dictionaries. The keys are letters and the values are the number of times the particular letter is repeated in that hand. n: int >= 0 returns: dictionary (string -> int) """ hand={} numVowels = n / 3 for i in range(numVowels): x = VOWELS[random.randrange(0,len(VOWELS))] hand[x] = hand.get(x, 0) + 1 for i in range(numVowels, n): x = CONSONANTS[random.randrange(0,len(CONSONANTS))] hand[x] = hand.get(x, 0) + 1 return hand # # Problem #2: Update a hand by removing letters # def updateHand(hand, word): """ Assumes that 'hand' has all the letters in word. In other words, this assumes that however many times a letter appears in 'word', 'hand' has at least as many of that letter in it. Updates the hand: uses up the letters in the given word and returns the new hand, without those letters in it. Has no side effects: does not modify hand. word: string hand: dictionary (string -> int) returns: dictionary (string -> int) """ uhand = hand.copy() for i in word: if i in hand.keys(): uhand[i] = uhand[i] - 1 return uhand # # Problem #3: Test word validity # def isValidWord(word, hand, wordList): """ Returns True if word is in the wordList and is entirely composed of letters in the hand. Otherwise, returns False. Does not mutate hand or wordList. word: string hand: dictionary (string -> int) wordList: list of lowercase strings """ phand = hand.copy() jhand = updateHand(hand, word) if word in wordList: for i in word: if i in phand.keys(): if jhand[i] < 0: return False else: continue else: return False return True else: return False # # Problem #4: Playing a hand # def calculateHandlen(hand): """ Returns the length (number of letters) in the current hand. hand: dictionary (string-> int) returns: integer """ a = 0 for i in hand: a = a + hand[i] return a def playHand(hand, wordList, n): """ Allows the user to play the given hand, as follows: * The hand is displayed. * The user may input a word or a single period (the string ".") to indicate they're done playing * Invalid words are rejected, and a message is displayed asking the user to choose another word until they enter a valid word or "." * When a valid word is entered, it uses up letters from the hand. * After every valid word: the score for that word is displayed, the remaining letters in the hand are displayed, and the user is asked to input another word. * The sum of the word scores is displayed when the hand finishes. * The hand finishes when there are no more unused letters or the user inputs a "." hand: dictionary (string -> int) wordList: list of lowercase strings n: integer (HAND_SIZE; i.e., hand size required for additional points) """ # BEGIN PSEUDOCODE <-- Remove this comment when you code this function; do your coding within the pseudocode (leaving those comments in-place!) # Keep track of the total score # As long as there are still letters left in the hand: # Display the hand s = 0 # Ask user for input while (True): print "\n" print 'Current Hand', displayHand(hand) word = raw_input('Enter word, or a "." to indicate that you are finished: ') # If the input is a single period: if word == ".": print "Goodbye! Total score:",s, "points. " break # End the game (break out of the loop) else: if not isValidWord(word, hand, wordList): print "Invalid word, please try again." continue else: s = s + getWordScore(word, n) print word,"earned", getWordScore(word, n), "points. Total:", s, "points" hand = updateHand(hand, word) if (calculateHandlen(hand) == 0): print "\nRun out of letters. Total score:",s,"points." break else: continue # Otherwise (the input is not a single period): # If the word is not valid: # Reject invalid word (print a message followed by a blank line) # Otherwise (the word is valid): # Tell the user how many points the word earned, and the updated total score, in one line followed by a blank line # Update the hand # Game is over (user entered a '.' or ran out of letters), so tell user the total score # # Problem #5: Playing a game # def playGame(wordList): """ Allow the user to play an arbitrary number of hands. 1) Asks the user to input 'n' or 'r' or 'e'. * If the user inputs 'n', let the user play a new (random) hand. * If the user inputs 'r', let the user play the last hand again. * If the user inputs 'e', exit the game. * If the user inputs anything else, tell them their input was invalid. 2) When done playing the hand, repeat from step 1 """ q = 0 n = False while (True): i = raw_input("Enter n to deal a new hand, r to replay the last hand, or e to end game: ") if (i == "r") and (n == False): print "You have not played a hand yet. Please play a new hand first!\n" q = q + 1 continue elif (n == True) and (i == "r"): playHand(hand, wordList, HAND_SIZE) continue elif (i == "n"): n = True hand = dealHand(HAND_SIZE) playHand(hand, wordList, HAND_SIZE) print "\n";continue elif (i == "e"): break else: print "Invalid command." continue # # Build data structures used for entire session and play game # if __name__ == '__main__': wordList = loadWords() playGame(wordList) # wordList = loadWords() # playHand({'n':1, 'e':1, 't':1, 'a':1, 'r':1, 'i':2}, wordList, 7)
{ "repo_name": "ahmedraza007/6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python", "path": "source/ProblemSet4/ps4a.py", "copies": "1", "size": "9897", "license": "mit", "hash": 4209749235697940500, "line_mean": 27.7703488372, "line_max": 212, "alpha_frac": 0.5683540467, "autogenerated": false, "ratio": 3.840512223515716, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9792334321494611, "avg_score": 0.0233063897442209, "num_lines": 344 }
# 6.00x Problem Set 4A Template # # The 6.00 Word Game # Created by: Kevin Luu <luuk> and Jenna Wiens <jwiens> # Modified by: Sarina Canelake <sarina> # import random import string #import test_ps4a VOWELS = 'aeiou' CONSONANTS = 'bcdfghjklmnpqrstvwxyz' HAND_SIZE = 7 SCRABBLE_LETTER_VALUES = { 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10 } # ----------------------------------- # Helper code # (you don't need to understand this helper code) WORDLIST_FILENAME = "words.txt" def loadWords(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # wordList: list of strings wordList = [] for line in inFile: wordList.append(line.strip().lower()) print " ", len(wordList), "words loaded." return wordList def getFrequencyDict(sequence): """ Returns a dictionary where the keys are elements of the sequence and the values are integer counts, for the number of times that an element is repeated in the sequence. sequence: string or list return: dictionary """ # freqs: dictionary (element_type -> int) freq = {} for x in sequence: freq[x] = freq.get(x,0) + 1 return freq # # Problem #1: Scoring a word # def getWordScore(word, n): """ Returns the score for a word. Assumes the word is a valid word. The score for a word is the sum of the points for letters in the word, multiplied by the length of the word, PLUS 50 points if all n letters are used on the first turn. Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is worth 3, D is worth 2, E is worth 1, and so on (see SCRABBLE_LETTER_VALUES) word: string (lowercase letters) n: integer (HAND_SIZE; i.e., hand size required for additional points) returns: int >= 0 """ if word == '': return 0 score = 0 for ch in word: score += SCRABBLE_LETTER_VALUES[ch] score = score * len(word) if len(word) == n: score += 50 return score # # Problem #2: Make sure you understand how this function works and what it does! # def displayHand(hand): """ Displays the letters currently in the hand. For example: >>> displayHand({'a':1, 'x':2, 'l':3, 'e':1}) Should print out something like: a x x l l l e The order of the letters is unimportant. hand: dictionary (string -> int) """ for letter in hand.keys(): for j in range(hand[letter]): print letter, # print all on the same line print # print an empty line # # Problem #2: Make sure you understand how this function works and what it does! # def dealHand(n): """ Returns a random hand containing n lowercase letters. At least n/3 the letters in the hand should be VOWELS. Hands are represented as dictionaries. The keys are letters and the values are the number of times the particular letter is repeated in that hand. n: int >= 0 returns: dictionary (string -> int) """ hand={} numVowels = n / 3 for i in range(numVowels): x = VOWELS[random.randrange(0,len(VOWELS))] hand[x] = hand.get(x, 0) + 1 for i in range(numVowels, n): x = CONSONANTS[random.randrange(0,len(CONSONANTS))] hand[x] = hand.get(x, 0) + 1 return hand # # Problem #2: Update a hand by removing letters # def updateHand(hand, word): """ Assumes that 'hand' has all the letters in word. In other words, this assumes that however many times a letter appears in 'word', 'hand' has at least as many of that letter in it. Updates the hand: uses up the letters in the given word and returns the new hand, without those letters in it. Has no side effects: does not modify hand. word: string hand: dictionary (string -> int) returns: dictionary (string -> int) """ new_hand = hand.copy() for j in word: new_hand[j] = new_hand.get(j,0) - 1 return new_hand hand = {'a': 1, 'e': 3, 'h': 1, 'l': 1, 't': 2, 'y': 1, 'x': 1} hand = updateHand(hand, 'teeth') print hand print displayHand(hand) # # Problem #3: Test word validity # def isValidWord(word, hand, wordList): """ Returns True if word is in the wordList and is entirely composed of letters in the hand. Otherwise, returns False. Does not mutate hand or wordList. word: string hand: dictionary (string -> int) wordList: list of lowercase strings """ ###Copy of the hand new_hand = dict(hand) for wordd in wordList: if wordd == '': return False if word not in wordList: return False for char in word: if char in new_hand: if new_hand[char] > 0: new_hand[char] -= 1 elif new_hand[char] == 0: new_hand.pop(char) if char not in new_hand: return False return True # # Problem #4: Playing a hand # def calculateHandlen(hand): """ Returns the length (number of letters) in the current hand. hand: dictionary (string-> int) returns: integer """ length = 0 for char in hand: length += hand[char] return length def playHand(hand, wordList, n): """ Allows the user to play the given hand, as follows: * The hand is displayed. * The user may input a word or a single period (the string ".") to indicate they're done playing * Invalid words are rejected, and a message is displayed asking the user to choose another word until they enter a valid word or "." * When a valid word is entered, it uses up letters from the hand. * After every valid word: the score for that word is displayed, the remaining letters in the hand are displayed, and the user is asked to input another word. * The sum of the word scores is displayed when the hand finishes. * The hand finishes when there are no more unused letters or the user inputs a "." hand: dictionary (string -> int) wordList: list of lowercase strings n: integer (HAND_SIZE; i.e., hand size required for additional points) """ # Keep track of the total score total = 0 # As long as there are still letters left in the hand: end_reason = 'Run out of letters.' while calculateHandlen(hand) > 0: # Display the hand print 'Current Hand: ', displayHand(hand) # Ask user for input user_inp = raw_input('Enter word, or a "." to indicate that you are finished:') #print 'Enter word, or a "." to indicate that you are finished:' + user_inp # If the input is a single period: if user_inp == '.': # End the game (break out of the loop) end_reason = 'Goodbye!.' break # Otherwise (the input is not a single period): else: # If the word is not valid: if isValidWord(user_inp, hand, wordList) == False: # Reject invalid word (print a message followed by a blank line) print 'Invalid word, please try again.' print '' # Otherwise (the word is valid): else: # Tell the user how many points the word earned, and the updated total score, in one line followed by a blank line erned_points = getWordScore(user_inp, n) total += erned_points print '"%s" erned %s points. Total: %s points' %(user_inp,erned_points, total ) # Update the hand hand = updateHand(hand, user_inp) # Game is over (user entered a '.' or ran out of letters), so tell user the total score return '%s Total score: %s points.' %(end_reason,total) # # Problem #5: Playing a game # def playGame(wordList): """ Allow the user to play an arbitrary number of hands. 1) Asks the user to input 'n' or 'r' or 'e'. * If the user inputs 'n', let the user play a new (random) hand. * If the user inputs 'r', let the user play the last hand again. * If the user inputs 'e', exit the game. * If the user inputs anything else, tell them their input was invalid. 2) When done playing the hand, repeat from step 1 """ game = True hand = None while game: user_inp = raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: r') if user_inp == 'n': hand = dealHand(HAND_SIZE) playHand(hand, wordList, HAND_SIZE) elif user_inp == 'r': if hand == None: print 'You have not played a hand yet. Please play a new hand first!' elif hand: playHand(hand, wordList, HAND_SIZE) elif user_inp == 'e': game = False else: print 'Invalid command.' return # # Build data structures used for entire session and play game # if __name__ == '__main__': wordList = loadWords() playGame(wordList)
{ "repo_name": "maistrovas/My-Courses-Solutions", "path": "MITx-6.00.1x/ProblemSet4/ps4a.py", "copies": "1", "size": "9495", "license": "mit", "hash": -2527031644311416300, "line_mean": 29.0474683544, "line_max": 212, "alpha_frac": 0.5948393892, "autogenerated": false, "ratio": 3.7060889929742387, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4800928382174239, "avg_score": null, "num_lines": null }
# 6.00x Problem Set 4A Template # # The 6.00 Word Game # Created by: Kevin Luu <luuk> and Jenna Wiens <jwiens> # Modified by: Sarina Canelake <sarina> # import random import string VOWELS = 'aeiou' CONSONANTS = 'bcdfghjklmnpqrstvwxyz' HAND_SIZE = 7 BONUS = 50 SCRABBLE_LETTER_VALUES = { 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10 } # ----------------------------------- # Helper code # (you don't need to understand this helper code) WORDLIST_FILENAME = "/home/paco/workspace/MIT_6001/600_wordgame/words.txt" def loadWords(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # wordList: list of strings wordList = [] for line in inFile: wordList.append(line.strip().lower()) print " ", len(wordList), "words loaded." return wordList def getFrequencyDict(sequence): """ Returns a dictionary where the keys are elements of the sequence and the values are integer counts, for the number of times that an element is repeated in the sequence. sequence: string or list return: dictionary """ # freqs: dictionary (element_type -> int) freq = {} for x in sequence: freq[x] = freq.get(x,0) + 1 return freq # (end of helper code) # ----------------------------------- # # Problem #1: Scoring a word # def getWordScore(word, n): """ Returns the score for a word. Assumes the word is a valid word. The score for a word is the sum of the points for letters in the word, multiplied by the length of the word, PLUS 50 points if all n letters are used on the first turn. Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is worth 3, D is worth 2, E is worth 1, and so on (see SCRABBLE_LETTER_VALUES) word: string (lowercase letters) n: integer (HAND_SIZE; i.e., hand size required for additional points) returns: int >= 0 """ points = 0 wordLen = len(word) lowerWord = word.lower() letterPoints = SCRABBLE_LETTER_VALUES for letter in lowerWord: if letter in letterPoints: points += letterPoints[letter] totalPoints = points * wordLen if wordLen >= n: totalPoints += 50 return totalPoints # # Problem #2: Make sure you understand how this function works and what it does! # def displayHand(hand): """ Displays the letters currently in the hand. For example: >>> displayHand({'a':1, 'x':2, 'l':3, 'e':1}) Should print out something like: a x x l l l e The order of the letters is unimportant. hand: dictionary (string -> int) """ handString = "" for letter in hand.keys(): for j in range(hand[letter]): handString += letter + " " # print all on the same line return handString # print an empty line # # Problem #2: Make sure you understand how this function works and what it does! # def dealHand(n): """ Returns a random hand containing n lowercase letters. At least n/3 the letters in the hand should be VOWELS. Hands are represented as dictionaries. The keys are letters and the values are the number of times the particular letter is repeated in that hand. n: int >= 0 returns: dictionary (string -> int) """ hand={} numVowels = n / 3 for i in range(numVowels): x = VOWELS[random.randrange(0,len(VOWELS))] hand[x] = hand.get(x, 0) + 1 for i in range(numVowels, n): x = CONSONANTS[random.randrange(0,len(CONSONANTS))] hand[x] = hand.get(x, 0) + 1 return hand # # Problem #2: Update a hand by removing letters # def updateHand(hand, word): """ Assumes that 'hand' has all the letters in word. In other words, this assumes that however many times a letter appears in 'word', 'hand' has at least as many of that letter in it. Updates the hand: uses up the letters in the given word and returns the new hand, without those letters in it. Has no side effects: does not modify hand. word: string hand: dictionary (string -> int) returns: dictionary (string -> int) """ resultHand = {} handCopy = hand.copy() for letter in word: if handCopy.has_key(letter): handCopy[letter] -= 1 for key in handCopy: if handCopy[key] != 0: value = handCopy[key] resultHand[key] = value return resultHand # # Problem #3: Test word validity # def isValidWord(word, hand, wordList): """ Returns True if word is in the wordList and is entirely composed of letters in the hand. Otherwise, returns False. Does not mutate hand or wordList. word: string hand: dictionary (string -> int) wordList: list of lowercase strings """ handCopy = hand.copy() if word in wordList: isValidWord = True for letter in word: if handCopy.has_key(letter) and handCopy[letter] > 0: handCopy[letter] -= 1 else: isValidWord = False break else: isValidWord = False return isValidWord # # Problem #4: Playing a hand # def calculateHandlen(hand): """ Returns the length (number of letters) in the current hand. hand: dictionary (string-> int) returns: integer """ numLetters = 0 for key in hand: numLetters += hand[key] return numLetters def playHand(hand, wordList, n): """ Allows the user to play the given hand, as follows: * The hand is displayed. * The user may input a word or a single period (the string ".") to indicate they're done playing * Invalid words are rejected, and a message is displayed asking the user to choose another word until they enter a valid word or "." * When a valid word is entered, it uses up letters from the hand. * After every valid word: the score for that word is displayed, the remaining letters in the hand are displayed, and the user is asked to input another word. * The sum of the word scores is displayed when the hand finishes. * The hand finishes when there are no more unused letters or the user inputs a "." hand: dictionary (string -> int) wordList: list of lowercase strings n: integer (HAND_SIZE; i.e., hand size required for additional points) """ handLen = calculateHandlen(hand) playerInput = '' totalHandScore = 0 while handLen > 0 or playerInput == ".": print 'Current Hand:', displayHand(hand) playerInput = raw_input('Enter word, or a "." to indicate that you are finished:') if playerInput != ".": if isValidWord(playerInput, hand, wordList): guessScore = getWordScore(playerInput, n) totalHandScore += guessScore hand = updateHand(hand, playerInput) handLen = calculateHandlen(hand) if handLen == 0: print 'Run out of letters.' break print str(playerInput), 'earned', str(guessScore), 'points. Total:', str(totalHandScore), 'points' else: print 'Invalid word, please try again.' else: break print 'Goodbye! Total score:', str(totalHandScore), 'points.' def playGame(wordList): """ Allow the user to play an arbitrary number of hands. 1) Asks the user to input 'n' or 'r' or 'e'. * If the user inputs 'n', let the user play a new (random) hand. * If the user inputs 'r', let the user play the last hand again. * If the user inputs 'e', exit the game. * If the user inputs anything else, tell them their input was invalid. 2) When done playing the hand, repeat from step 1 """ hand = {} while True: userInput = raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game:') if userInput == 'n': hand = dealHand(HAND_SIZE) playHand(hand, wordList, HAND_SIZE) elif userInput == 'r': if len(hand) != 0: playHand(hand, wordList, HAND_SIZE) else: print 'You have not played a hand yet. Please play a new hand first!' elif userInput == 'e': break else: print 'Invalid command.' # # Build data structures used for entire session and play game # if __name__ == '__main__': wordList = loadWords() playHand(dealHand(HAND_SIZE), wordList, HAND_SIZE)
{ "repo_name": "cosmopod/MIT_6001", "path": "600_wordgame/ps4a.py", "copies": "1", "size": "8895", "license": "mit", "hash": -6852339220092170000, "line_mean": 28.2598684211, "line_max": 212, "alpha_frac": 0.6098931984, "autogenerated": false, "ratio": 3.73582528349433, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9821125125642893, "avg_score": 0.0049186712502872825, "num_lines": 304 }
# 6.00x Problem Set 5 # # Part 1 - HAIL CAESAR! import string import random #import cgitb #cgitb.enable() WORDLIST_FILENAME = "words.txt" # ----------------------------------- # Helper code # (you don't need to understand this helper code) def loadWords(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." inFile = open(WORDLIST_FILENAME, 'r') wordList = inFile.read().split() print " ", len(wordList), "words loaded." return wordList def isWord(wordList, word): """ Determines if word is a valid word. wordList: list of words in the dictionary. word: a possible word. returns True if word is in wordList. Example: >>> isWord(wordList, 'bat') returns True >>> isWord(wordList, 'asdf') returns False """ word = word.lower() word = word.strip(" !@#$%^&*()-_+={}[]|\\:;'<>?,./\"") return word in wordList def randomWord(wordList): """ Returns a random word. wordList: list of words returns: a word from wordList at random """ return random.choice(wordList) def randomString(wordList, n): """ Returns a string containing n random words from wordList wordList: list of words returns: a string of random words separated by spaces. """ return " ".join([randomWord(wordList) for _ in range(n)]) def randomScrambled(wordList, n): """ Generates a test string by generating an n-word random string and encrypting it with a sequence of random shifts. wordList: list of words n: number of random words to generate and scamble returns: a scrambled string of n random words NOTE: This function will ONLY work once you have completed your implementation of applyShifts! """ s = randomString(wordList, n) + " " shifts = [(i, random.randint(0, 25)) for i in range(len(s)) if s[i-1] == ' '] return applyShifts(s, shifts)[:-1] def getStoryString(): """ Returns a story in encrypted text. """ return open("story.txt", "r").read() # (end of helper code) # ----------------------------------- # # Problem 1: Encryption # def buildCoder(shift): """ Returns a dict that can apply a Caesar cipher to a letter. The cipher is defined by the shift value. Ignores non-letter characters like punctuation, numbers and spaces. shift: 0 <= int < 26 returns: dict """ ### TODO. def shift_vals(c, last): '''Shift values considering rotating ''' total = 26 new_ord = ord(c) + shift if new_ord <= ord(last): new = chr(new_ord) else: new = chr(new_ord - total) return new d = {} for c in string.ascii_letters: if c in string.ascii_lowercase: d[c] = shift_vals(c, 'z') else: d[c] = shift_vals(c, 'Z') return d def applyCoder(text, coder): """ Applies the coder to the text. Returns the encoded text. text: string coder: dict with mappings of characters to shifted characters returns: text after mapping coder chars to original text """ ### TODO. def chargen(text, coder): new = [] for c in text: if c in string.ascii_letters: yield coder[c] else: yield c return ''.join(chargen(text, coder)) def applyShift(text, shift): """ Given a text, returns a new text Caesar shifted by the given shift offset. Lower case letters should remain lower case, upper case letters should remain upper case, and all other punctuation should stay as it is. text: string to apply the shift to shift: amount to shift the text (0 <= int < 26) returns: text after being shifted by specified amount. """ ### TODO. ### HINT: This is a wrapper function. return applyCoder(text, buildCoder(shift)) # # Problem 2: Decryption # def findBestShift(wordList, text): """ Finds a shift key that can decrypt the encoded text. text: string returns: 0 <= int < 26 """ ### TODO ''' Psuedo code ''' def text_score(wordList, text): '''Determine one text's goodness. ''' #We give the text a score, whose initial vaule is 0. score = 0 #We split the text into words words = text.split() #For each word for word in words: #If the word is a valid word, we add one to the score if isWord(wordList, word): score += 1 #After this we return the score. return score # There are 27 possible shift keys keys = range(1, 27) # We bookkeeping the decryption key, and the maximum score, whose initial # value is 0. max_key = 0 max_score = 0 #For each possible shift key for key in keys: # For each shift key, the decryption key is 26 - k decrypt_key = 26 - key # Apply its decryption key, then we get the decrypted text decrypt_text = applyShift(text, decrypt_key) # The text may be crap. We have to determine the decypted text's # probability of being real English text. And find the most probable # text. score = text_score(wordList, decrypt_text) # If the current text's score is larger than the maximum score if score > max_score: # We let the maximum be the current text's score. max_score = score max_key = decrypt_key # Then return the respective key. return max_key def decryptStory(): """ Using the methods you created in this problem set, decrypt the story given by the function getStoryString(). Use the functions getStoryString and loadWords to get the raw data you need. returns: string - story in plain text """ ### TODO. wordList = loadWords() crypt_msg = getStoryString() orig_msg = applyShift(crypt_msg, findBestShift(wordList, crypt_msg)) return orig_msg # # Build data structures used for entire session and run encryption # if __name__ == '__main__': #from ipdb import launch_ipdb_on_exception #with launch_ipdb_on_exception(): # To test findBestShift: #wordList = loadWords() #s = applyShift('Hello, world!', 8) #bestShift = findBestShift(wordList, s) #assert applyShift(s, bestShift) == 'Hello, world!' # To test decryptStory, comment the above four lines and uncomment this line: print decryptStory()
{ "repo_name": "fossilet/6.00x", "path": "week5/problemset5/ps5_encryption.py", "copies": "1", "size": "6674", "license": "mit", "hash": -8735668022999925000, "line_mean": 26.5785123967, "line_max": 81, "alpha_frac": 0.609080012, "autogenerated": false, "ratio": 3.87122969837587, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.498030971037587, "avg_score": null, "num_lines": null }
# 6.00x Problem Set 5 # # Part 1 - HAIL CAESAR! import string import random WORDLIST_FILENAME = "words.txt" # ----------------------------------- # Helper code # (you don't need to understand this helper code) def loadWords(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." inFile = open(WORDLIST_FILENAME, 'r') wordList = inFile.read().split() print " ", len(wordList), "words loaded." return wordList def isWord(wordList, word): """ Determines if word is a valid word. wordList: list of words in the dictionary. word: a possible word. returns True if word is in wordList. Example: >>> isWord(wordList, 'bat') returns True >>> isWord(wordList, 'asdf') returns False """ word = word.lower() word = word.strip(" !@#$%^&*()-_+={}[]|\\:;'<>?,./\"") return word in wordList def randomWord(wordList): """ Returns a random word. wordList: list of words returns: a word from wordList at random """ return random.choice(wordList) def randomString(wordList, n): """ Returns a string containing n random words from wordList wordList: list of words returns: a string of random words separated by spaces. """ return " ".join([randomWord(wordList) for _ in range(n)]) def randomScrambled(wordList, n): """ Generates a test string by generating an n-word random string and encrypting it with a sequence of random shifts. wordList: list of words n: number of random words to generate and scamble returns: a scrambled string of n random words NOTE: This function will ONLY work once you have completed your implementation of applyShifts! """ s = randomString(wordList, n) + " " shifts = [(i, random.randint(0, 25)) for i in range(len(s)) if s[i-1] == ' '] #return applyShifts(s, shifts)[:-1] def getStoryString(): """ Returns a story in encrypted text. """ return open("story.txt", "r").read() # (end of helper code) # ----------------------------------- # # Problem 1: Encryption # def buildCoder(shift): """ Returns a dict that can apply a Caesar cipher to a letter. The cipher is defined by the shift value. Ignores non-letter characters like punctuation, numbers and spaces. shift: 0 <= int < 26 returns: dict """ dict_shift = {} lower_flip_count = 0 upper_flip_count = 0 lower_letters = string.ascii_lowercase upper_letters = string.ascii_uppercase letters = string.ascii_letters for i in range(len(letters)): if letters[i] in lower_letters: if lower_letters[-1] not in dict_shift.values(): dict_shift[letters[i]] = lower_letters[lower_letters.find(letters[i]) + shift] else: dict_shift[letters[i]] = lower_letters[lower_flip_count] lower_flip_count += 1 else: if upper_letters[-1] not in dict_shift.values(): dict_shift[letters[i]] = upper_letters[upper_letters.find(letters[i]) + shift] else: dict_shift[letters[i]] = upper_letters[upper_flip_count] upper_flip_count += 1 return dict_shift print buildCoder(9) def applyCoder(text, coder): """ Applies the coder to the text. Returns the encoded text. text: string coder: dict with mappings of characters to shifted characters returns: text after mapping coder chars to original text """ coded_text = '' for l in text: if l not in string.ascii_letters: coded_text += l else: coded_text += coder[l] return coded_text #print applyCoder("Hello, world!", buildCoder(3)) #print applyCoder("Khoor, zruog!", buildCoder(23)) def applyShift(text, shift): """ Given a text, returns a new text Caesar shifted by the given shift offset. Lower case letters should remain lower case, upper case letters should remain upper case, and all other punctuation should stay as it is. text: string to apply the shift to shift: amount to shift the text (0 <= int < 26) returns: text after being shifted by specified amount. """ coder = buildCoder(shift) return applyCoder(text, coder) #print applyShift('Bpqa qa i bmab.', 18) # # Problem 2: Decryption # def findBestShift(wordList, text): """ Finds a shift key that can decrypt the encoded text. text: string returns: 0 <= int < 26 """ code_shift = 0 count_valid_words = 0 list_valid_words_count = [] for i in range(0, 26): shifted_text = applyShift(text, i) shifted_text_words = shifted_text.split() for word in shifted_text_words: if isWord(wordList, word) == True: count_valid_words += 1 else: code_shift += 1 list_valid_words_count.append(count_valid_words) best_shift = max(list_valid_words_count) return list_valid_words_count.index(best_shift) # max_valid_word_count = 0 # num_valid_words = 0 # best_shift = 0 # for i in range(0, 26): # shifted_text = applyShift(text, i) # shifted_text_words = shifted_text.split() # if shifted_text_words in wordList: # num_valid_words += 1 # if num_valid_words > max_valid_word_count: # best_shift = # return best_shift ''' initial ''' #code_shift = 0 # count_valid_words = 0 # # while True: # shifted_text = applyShift(text, code_shift) # shifted_text_words = shifted_text.split() # for word in shifted_text_words: # if isWord(wordList, word) == True: # count_valid_words += 1 # else: # code_shift += 1 # if count_valid_words == len(shifted_text_words): # return code_shift # break print findBestShift(loadWords(), 'Aol xbpg pz... ohyk!') #print applyShift('Aol xbpg pz... ohyk!', y) def decryptStory(): """ Using the methods you created in this problem set, decrypt the story given by the function getStoryString(). Use the functions getStoryString and loadWords to get the raw data you need. returns: string - story in plain text """ wordList = loadWords() text = getStoryString() coder_shift = findBestShift(wordList, text) applyShift(text, coder_shift) # # Build data structures used for entire session and run encryption # if __name__ == '__main__': # To test findBestShift: wordList = loadWords() s = applyShift('Hello, world!', 8) bestShift = findBestShift(wordList, s) assert applyShift(s, bestShift) == 'Hello, world!' # To test decryptStory, comment the above four lines and uncomment this line: # decryptStory()
{ "repo_name": "b3ngmann/python-pastime", "path": "ps5/ps5_encryption.py", "copies": "1", "size": "6980", "license": "mit", "hash": -7065860199740942000, "line_mean": 27.7242798354, "line_max": 94, "alpha_frac": 0.6143266476, "autogenerated": false, "ratio": 3.643006263048017, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47573329106480167, "avg_score": null, "num_lines": null }
# 6.00x Problem Set 5 # # Part 2 - RECURSION # # Problem 3: Recursive String Reversal # def reverseString(aStr): """ Given a string, recursively returns a reversed copy of the string. For example, if the string is 'abc', the function returns 'cba'. The only string operations you are allowed to use are indexing, slicing, and concatenation. aStr: a string returns: a reversed string """ if aStr == "": return "" else: return reverseString(aStr[1:]) + aStr[0] # # Problem 4: Erician # def x_ian(x, word): """ Given a string x, returns True if all the letters in x are contained in word in the same order as they appear in x. x: a string word: a string returns: True if word is x_ian, False otherwise """ if x == "": return True elif word == "": return False elif x[0] == word[0]: return x_ian(x[1:], word[1:]) else: return x_ian(x, word[1:]) # # Problem 5: Typewriter # def getWords(text): words = text.split(' ') return words def insertNewlinesRec(words, lineLength, currentLineLength, formattedText): if words == []: return formattedText word = words[0] wordLength = len(word) if currentLineLength < lineLength: formattedText += word+' ' return insertNewlinesRec(words[1:], lineLength, currentLineLength+wordLength+1, formattedText) else: formattedText += '\n' return insertNewlinesRec(words, lineLength, 0,formattedText) def insertNewlines(text, lineLength): """ Given text and a desired line length, wrap the text as a typewriter would. Insert a newline character ("\n") after each word that reaches or exceeds the desired line length. text: a string containing the text to wrap. lineLength: the number of characters to include on a line before wrapping the next word. returns: a string, with newline characters inserted appropriately. """ return insertNewlinesRec(getWords(text), lineLength, 0, "")
{ "repo_name": "juampi/6.00x", "path": "ProblemSet05/ps5_recursion.py", "copies": "1", "size": "2063", "license": "mit", "hash": 4454095761086967000, "line_mean": 26.8918918919, "line_max": 102, "alpha_frac": 0.6461463888, "autogenerated": false, "ratio": 3.8851224105461393, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9991171699315078, "avg_score": 0.008019420006212124, "num_lines": 74 }
# 6.00x Problem Set 5 # # Part 2 - RECURSION # # Problem 3: Recursive String Reversal # def reverseString(aStr): """ Given a string, recursively returns a reversed copy of the string. For example, if the string is 'abc', the function returns 'cba'. The only string operations you are allowed to use are indexing, slicing, and concatenation. aStr: a string returns: a reversed string """ # Pseudo code if len(aStr) in (0, 1): return aStr else: return aStr[-1] + reverseString(aStr[:-1]) # # Problem 4: X-ian # def x_ian(x, word): """ Given a string x, returns True if all the letters in x are contained in word in the same order as they appear in x. >>> x_ian('eric', 'meritocracy') True >>> x_ian('eric', 'cerium') False >>> x_ian('john', 'mahjong') False x: a string word: a string returns: True if word is x_ian, False otherwise """ # Pseudo code first if len(x) == 0: return True if len(x) == 1: return x[0] in word else: ind = word.find(x[0]) if ind != -1: return x_ian(x[1:], word[(ind + 1):]) return False # # Problem 5: Typewriter # def insertNewlines(text, lineLength): """ Given text and a desired line length, wrap the text as a typewriter would. Insert a newline character ("\n") after each word that reaches or exceeds the desired line length. text: a string containing the text to wrap. line_length: the number of characters to include on a line before wrapping the next word. returns: a string, with newline characters inserted appropriately. """ ### TODO. if len(text) <= lineLength: return text else: # Returns the first part of the text whose length is lineLength plus # the rest inserted of new lines. new_text = '' char = text[lineLength - 1] # Insert newline character after the next space # Index in the slice after char space_sub_ind = text[(lineLength-1):].find(' ') if space_sub_ind == -1: return text else: # Index in the text space_ind = space_sub_ind + lineLength - 1 new_text += text[:(space_ind + 1)] + '\n' new_text += insertNewlines(text[(space_ind + 1):], lineLength) return new_text
{ "repo_name": "fossilet/6.00x", "path": "week5/problemset5/ps5_recursion.py", "copies": "1", "size": "2417", "license": "mit", "hash": -1111604706721512400, "line_mean": 26.7816091954, "line_max": 78, "alpha_frac": 0.5899875879, "autogenerated": false, "ratio": 3.764797507788162, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48547850956881616, "avg_score": null, "num_lines": null }
# 6.00x Problem Set 6 # # Part 1 - HAIL CAESAR! import string import random WORDLIST_FILENAME = "./courseraSpecialization/git_repos/PlayingWithPython/computationAndProgrammingUsingPython/src/problemSet06/code_ProblemSet6/words.txt" # ----------------------------------- # Helper code # (you don't need to understand this helper code) def loadWords(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." inFile = open(WORDLIST_FILENAME, 'r') wordList = inFile.read().split() print " ", len(wordList), "words loaded." return wordList def isWord(wordList, word): """ Determines if word is a valid word. wordList: list of words in the dictionary. word: a possible word. returns True if word is in wordList. Example: >>> isWord(wordList, 'bat') returns True >>> isWord(wordList, 'asdf') returns False """ word = word.lower() word = word.strip(" !@#$%^&*()-_+={}[]|\\:;'<>?,./\"") return word in wordList def randomWord(wordList): """ Returns a random word. wordList: list of words returns: a word from wordList at random """ return random.choice(wordList) def randomString(wordList, n): """ Returns a string containing n random words from wordList wordList: list of words returns: a string of random words separated by spaces. """ return " ".join([randomWord(wordList) for _ in range(n)]) def randomScrambled(wordList, n): """ Generates a test string by generating an n-word random string and encrypting it with a sequence of random shifts. wordList: list of words n: number of random words to generate and scamble returns: a scrambled string of n random words NOTE: This function will ONLY work once you have completed your implementation of applyShifts! """ s = randomString(wordList, n) + " " shifts = [(i, random.randint(0, 25)) for i in range(len(s)) if s[i-1] == ' '] return applyShifts(s, shifts)[:-1] def getStoryString(): """ Returns a story in encrypted text. """ return open("./courseraSpecialization/git_repos/PlayingWithPython/computationAndProgrammingUsingPython/src/problemSet06/code_ProblemSet6/story.txt", "r").read() # (end of helper code) # ----------------------------------- # # Problem 1: Encryption # def buildCoder(shift): """ Returns a dict that can apply a Caesar cipher to a letter. The cipher is defined by the shift value. Ignores non-letter characters like punctuation, numbers and spaces. shift: 0 <= int < 26 returns: dict """ # Check constrain on shift assert shift in range(0,26) mapping = {} # Mapping letter (plainText) -> letter (cipherText) upperCaseLetterRotator = string.ascii_uppercase + string.ascii_uppercase lowerCaseLetterRotator = string.ascii_lowercase + string.ascii_lowercase for idx, letter in enumerate(upperCaseLetterRotator[:26]): mapping[letter] = upperCaseLetterRotator[idx + shift] for idx, letter in enumerate(lowerCaseLetterRotator[:26]): mapping[letter] = lowerCaseLetterRotator[idx + shift] return mapping def applyCoder(text, coder): """ Applies the coder to the text. Returns the encoded text. text: string coder: dict with mappings of characters to shifted characters returns: text after mapping coder chars to original text """ cipherTestAsList = [] for letter in text: if letter in coder: cipherTestAsList.append(coder[letter]) else: cipherTestAsList.append(letter) return "".join(cipherTestAsList) def applyShift(text, shift): """ Given a text, returns a new text Caesar shifted by the given shift offset. Lower case letters should remain lower case, upper case letters should remain upper case, and all other punctuation should stay as it is. text: string to apply the shift to shift: amount to shift the text (0 <= int < 26) returns: text after being shifted by specified amount. """ return applyCoder(text, buildCoder(shift)) # # Problem 2: Decryption # def findBestShift(wordList, text): """ Finds a shift key that can decrypt the encoded text. text: string returns: 0 <= int < 26 """ noOfMeaningfullWords = 0 meanigfullWords_max = 0 shiftKey_max =0 decodedMessage = "" for guess in range(0, 26): if guess != 0: guess = 26 - guess decodedMessage = applyShift(text, guess).split(" ") #print "shift key: %d, decoded msg: %s" % (guess, decodedMessage) for decodedWord in decodedMessage: #Check if the decoded word contains "strange" character #Assumption check is performed on first and last characters if decodedWord[0].lower() not in string.ascii_lowercase: decodedWord = decodedWord[1:] if decodedWord[-1].lower() not in string.ascii_lowercase: decodedWord = decodedWord[:-1] if isWord(wordList, decodedWord): noOfMeaningfullWords += 1 if noOfMeaningfullWords > meanigfullWords_max: meanigfullWords_max = noOfMeaningfullWords shiftKey_max = guess noOfMeaningfullWords = 0 return shiftKey_max def decryptStory(): """ Using the methods you created in this problem set, decrypt the story given by the function getStoryString(). Use the functions getStoryString and loadWords to get the raw data you need. returns: string - story in plain text """ wordList = loadWords() text = getStoryString() bestShift = findBestShift(wordList, text) """Jack Florey is a mythical character created on the spur of a moment to help cover an insufficiently planned hack. He has been registered for classes at MIT twice before, but has reportedly never passed a class. It has been the tradition of the residents of East Campus to become Jack Florey for a few nights each year to educate incoming students in the ways, means, and ethics of hacking.""" return applyShift(text, bestShift) # # Build data structures used for entire session and run encryption # if __name__ == '__main__': # To test findBestShift: wordList = loadWords() s = applyShift('Hello, world!', 8) bestShift = findBestShift(wordList, s) assert applyShift(s, bestShift) == 'Hello, world!' # To test decryptStory, comment the above four lines and uncomment this line: print decryptStory()
{ "repo_name": "pparacch/PlayingWithPython", "path": "computationAndProgrammingUsingPython/src/problemSet06/code_ProblemSet6/ps6_encryption.py", "copies": "1", "size": "6832", "license": "mit", "hash": 3414396510692623000, "line_mean": 30.3394495413, "line_max": 399, "alpha_frac": 0.6520784543, "autogenerated": false, "ratio": 4.002343292325718, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.015115404993503242, "num_lines": 218 }
# 6.00x Problem Set 6 # # Part 1 - HAIL CAESAR! import string import random WORDLIST_FILENAME = "/home/xala/workarea/Introduction-to-Computer-Science-and-Programming-with-python/week6/Problems/words.txt" # ----------------------------------- # Helper code # (you don't need to understand this helper code) def loadWords(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." inFile = open(WORDLIST_FILENAME, 'r') wordList = inFile.read().split() print " ", len(wordList), "words loaded." return wordList def isWord(wordList, word): """ Determines if word is a valid word. wordList: list of words in the dictionary. word: a possible word. returns True if word is in wordList. Example: >>> isWord(wordList, 'bat') returns True >>> isWord(wordList, 'asdf') returns False """ word = word.lower() word = word.strip(" !@#$%^&*()-_+={}[]|\\:;'<>?,./\"") return word in wordList def randomWord(wordList): """ Returns a random word. wordList: list of words returns: a word from wordList at random """ return random.choice(wordList) def randomString(wordList, n): """ Returns a string containing n random words from wordList wordList: list of words returns: a string of random words separated by spaces. """ return " ".join([randomWord(wordList) for _ in range(n)]) def randomScrambled(wordList, n): """ Generates a test string by generating an n-word random string and encrypting it with a sequence of random shifts. wordList: list of words n: number of random words to generate and scamble returns: a scrambled string of n random words NOTE: This function will ONLY work once you have completed your implementation of applyShifts! """ s = randomString(wordList, n) + " " shifts = [(i, random.randint(0, 25)) for i in range(len(s)) if s[i-1] == ' '] return applyShifts(s, shifts)[:-1] def getStoryString(): """ Returns a story in encrypted text. """ return open("/home/xala/workarea/Introduction-to-Computer-Science-and-Programming-with-python/week6/Problems/story.txt", "r").read() # (end of helper code) # ----------------------------------- # # Problem 1: Encryption # def buildCoder(shift): """ Returns a dict that can apply a Caesar cipher to a letter. The cipher is defined by the shift value. Ignores non-letter characters like punctuation, numbers and spaces. shift: 0 <= int < 26 returns: dict """ upper_dict = {} lower_dict = {} offset = shift for letter in string.ascii_uppercase: upper_dict[letter] = string.ascii_uppercase[offset%26] offset += 1 offset = shift for letter in string.ascii_lowercase: lower_dict[letter] = string.ascii_lowercase[offset%26] offset += 1 return dict(upper_dict.items() + lower_dict.items()) def applyCoder(text, coder): """ Applies the coder to the text. Returns the encoded text. text: string coder: dict with mappings of characters to shifted characters returns: text after mapping coder chars to original text """ text_coded = '' for index in range(0, len(text)): text_coded += str(coder.get(text[index], text[index])) return text_coded def applyShift(text, shift): """ Given a text, returns a new text Caesar shifted by the given shift offset. Lower case letters should remain lower case, upper case letters should remain upper case, and all other punctuation should stay as it is. text: string to apply the shift to shift: amount to shift the text (0 <= int < 26) returns: text after being shifted by specified amount. """ return applyCoder(text, buildCoder(shift)) # # Problem 2: Decryption # def findBestShift(wordList, text): """ Finds a shift key that can decrypt the encoded text. text: string returns: 0 <= int < 26 """ max_real_words = 0 best_shift = 0 for i in range(0, 26): coded_text = applyShift(text, i) list_coded_words = coded_text.split(' ') n_valid_words = 0 for word in list_coded_words: if isWord(wordList, word): n_valid_words += 1 if n_valid_words > max_real_words: max_real_words = n_valid_words best_shift = i return best_shift def decryptStory(): """ Using the methods you created in this problem set, decrypt the story given by the function getStoryString(). Use the functions getStoryString and loadWords to get the raw data you need. returns: string - story in plain text """ wordList = loadWords() story = getStoryString() bestShift = findBestShift(wordList, story) return applyShift(story, bestShift) # # Build data structures used for entire session and run encryption # if __name__ == '__main__': # To test findBestShift: wordList = loadWords() s = applyShift('Hello, world!', 8) bestShift = findBestShift(wordList, s) assert applyShift(s, bestShift) == 'Hello, world!' # To test decryptStory, comment the above four lines and uncomment this line: # decryptStory()
{ "repo_name": "xala3pa/Introduction-to-Computer-Science-and-Programming-with-python", "path": "week6/Problems/ps6_encryption.py", "copies": "1", "size": "5477", "license": "mit", "hash": -5221291587378261000, "line_mean": 26.943877551, "line_max": 136, "alpha_frac": 0.6326456089, "autogenerated": false, "ratio": 3.792936288088643, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9877842970082658, "avg_score": 0.009547785381197186, "num_lines": 196 }
# 6.00x Problem Set 6 # # Part 1 - HAIL CAESAR! import string import random WORDLIST_FILENAME = "/Users/bolo/githubRepo/python_6.00.1x/PSet6/words.txt" # ----------------------------------- # Helper code # (you don't need to understand this helper code) def loadWords(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." inFile = open(WORDLIST_FILENAME, 'r') wordList = inFile.read().split() print " ", len(wordList), "words loaded." return wordList def isWord(wordList, word): """ Determines if word is a valid word. wordList: list of words in the dictionary. word: a possible word. returns True if word is in wordList. Example: >>> isWord(wordList, 'bat') returns True >>> isWord(wordList, 'asdf') returns False """ word = word.lower() word = word.strip(" !@#$%^&*()-_+={}[]|\\:;'<>?,./\"") return word in wordList def randomWord(wordList): """ Returns a random word. wordList: list of words returns: a word from wordList at random """ return random.choice(wordList) def randomString(wordList, n): """ Returns a string containing n random words from wordList wordList: list of words returns: a string of random words separated by spaces. """ return " ".join([randomWord(wordList) for _ in range(n)]) def randomScrambled(wordList, n): """ Generates a test string by generating an n-word random string and encrypting it with a sequence of random shifts. wordList: list of words n: number of random words to generate and scramble returns: a scrambled string of n random words NOTE: This function will ONLY work once you have completed your implementation of applyShift! """ s = randomString(wordList, n) + " " shifts = [(i, random.randint(0, 25)) for i in range(len(s)) if s[i-1] == ' '] return applyShift(s, shifts)[:-1] def getStoryString(): """ Returns a story in encrypted text. """ return open("/Users/bolo/githubRepo/python_6.00.1x/PSet6/story.txt", "r").read() # (end of helper code) # ----------------------------------- # # Problem 1: Encryption # def buildCoder(shift): """ Returns a dict that can apply a Caesar cipher to a letter. The cipher is defined by the shift value. Ignores non-letter characters like punctuation, numbers and spaces. shift: 0 <= int < 26 returns: dict """ dic = {} alphaUpper = string.ascii_uppercase alphaLower = string.ascii_lowercase for i in range(26): dic[alphaUpper[i]] = alphaUpper[(i + shift) % 26] dic[alphaLower[i]] = alphaLower[(i + shift) % 26] return dic def applyCoder(text, coder): """ Applies the coder to the text. Returns the encoded text. text: string coder: dict with mappings of characters to shifted characters returns: text after mapping coder chars to original text """ textNew = '' for i in text: if not i in string.ascii_uppercase and not i in string.ascii_lowercase: textNew += i else: textNew += coder[i] return textNew def applyShift(text, shift): """ Given a text, returns a new text Caesar shifted by the given shift offset. Lower case letters should remain lower case, upper case letters should remain upper case, and all other punctuation should stay as it is. text: string to apply the shift to shift: amount to shift the text (0 <= int < 26) returns: text after being shifted by specified amount. HINT: This is a wrapper function. """ return applyCoder(text, buildCoder(shift)) # # Problem 2: Decryption # def findBestShift(wordList, text): """ Finds a shift key that can decrypt the encoded text. text: string returns: 0 <= int < 26 HINT: notice the 'best' """ # initialize bestshift to 0 bestShift = 0 # initialize max number of valid words to 0 maxValidWord = 0 # for each possible shift from 1 to 25 for i in range(25): currentShift = i # convert story.txt by current shift value newStory = applyShift(text, currentShift) # split new-converted story.txt into a list of individual words newStoryList = newStory.split(' ') # initialize the number of valid words to 0 validNum = 0 # for each word in the word list, check validity and count valid words for i in newStoryList: if isWord(wordList, i): validNum += 1 # if the number of valid words under this shift is greater than one under last shift if validNum > maxValidWord: # update the number of valid words maxValidWord = validNum # update bestshift bestShift = currentShift # else, current shift plus 1 else: currentShift += 1 # return bestshift return bestShift def decryptStory(): """ Using the methods you created in this problem set, decrypt the story given by the function getStoryString(). Use the functions getStoryString and loadWords to get the raw data you need. returns: string - story in plain text """ storytxt = getStoryString() bestShift = findBestShift(wordList, storytxt) return applyShift(storytxt, bestShift) # # Build data structures used for entire session and run encryption # if __name__ == '__main__': wordList = loadWords() # To test findBestShift, uncomment the following three lines: # s = applyShift('Hello, world!', 8) # bestShift = findBestShift(wordList, s) # assert applyShift(s, bestShift) == 'Hello, world!' # To test decryptStory, comment the above four lines and uncomment this line: # decryptStory()
{ "repo_name": "medifle/python_6.00.1x", "path": "PSet6/ps6_encryption.py", "copies": "1", "size": "5971", "license": "mit", "hash": 7292666313861401000, "line_mean": 28.1268292683, "line_max": 92, "alpha_frac": 0.6369117401, "autogenerated": false, "ratio": 3.9282894736842104, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.005450920401971507, "num_lines": 205 }
# 6.00x Problem Set 6 # # Part 1 - HAIL CAESAR! import string import random WORDLIST_FILENAME = "/Users/yulianzhou/Desktop/course/python/6001x/ProblemSet6/words.txt" # ----------------------------------- # Helper code # (you don't need to understand this helper code) def loadWords(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." inFile = open(WORDLIST_FILENAME, 'r') wordList = inFile.read().split() print " ", len(wordList), "words loaded." return wordList def isWord(wordList, word): """ Determines if word is a valid word. wordList: list of words in the dictionary. word: a possible word. returns True if word is in wordList. Example: >>> isWord(wordList, 'bat') returns True >>> isWord(wordList, 'asdf') returns False """ word = word.lower() word = word.strip(" !@#$%^&*()-_+={}[]|\\:;'<>?,./\"") return word in wordList def randomWord(wordList): """ Returns a random word. wordList: list of words returns: a word from wordList at random """ return random.choice(wordList) def randomString(wordList, n): """ Returns a string containing n random words from wordList wordList: list of words returns: a string of random words separated by spaces. """ return " ".join([randomWord(wordList) for _ in range(n)]) def randomScrambled(wordList, n): """ Generates a test string by generating an n-word random string and encrypting it with a sequence of random shifts. wordList: list of words n: number of random words to generate and scamble returns: a scrambled string of n random words NOTE: This function will ONLY work once you have completed your implementation of applyShifts! """ s = randomString(wordList, n) + " " shifts = [(i, random.randint(0, 25)) for i in range(len(s)) if s[i-1] == ' '] return applyShifts(s, shifts)[:-1] def getStoryString(): """ Returns a story in encrypted text. """ return open("/Users/yulianzhou/Desktop/Course/python/6001x/ProblemSet6/story.txt", "r").read() # (end of helper code) # ----------------------------------- # # Problem 1: Encryption # def buildCoder(shift): """ Returns a dict that can apply a Caesar cipher to a letter. The cipher is defined by the shift value. Ignores non-letter characters like punctuation, numbers and spaces. shift: 0 <= int < 26 returns: dict """ coder = {} lst1 = [] lst2 = [] for letter in string.ascii_lowercase: lst1.append(letter) lst2.append(letter.upper()) for i in range(26): coder[lst1[i]] = lst1[(i + shift) % 26] coder[lst2[i]] = lst2[(i + shift) % 26] return coder def applyCoder(text, coder): """ Applies the coder to the text. Returns the encoded text. text: string coder: dict with mappings of characters to shifted characters returns: text after mapping coder chars to original text """ codetext = "" for l in text: if l in coder: codetext += coder[l] else: codetext += l return codetext def applyShift(text, shift): """ Given a text, returns a new text Caesar shifted by the given shift offset. Lower case letters should remain lower case, upper case letters should remain upper case, and all other punctuation should stay as it is. text: string to apply the shift to shift: amount to shift the text (0 <= int < 26) returns: text after being shifted by specified amount. """ ### HINT: This is a wrapper function. return applyCoder(text, buildCoder(shift)) # # Problem 2: Decryption # def findBestShift(wordList, text): """ Finds a shift key that can decrypt the encoded text. text: string returns: 0 <= int < 26 """ shift = 0 score = 0 for i in range(26): count = 0 s = applyCoder(text, buildCoder(i)) for word in s.split(" "): if isWord(wordList, word): count += 1 if count > score: shift = i score = count return shift def decryptStory(): """ Using the methods you created in this problem set, decrypt the story given by the function getStoryString(). Use the functions getStoryString and loadWords to get the raw data you need. returns: string - story in plain text """ wordList = loadWords() text = getStoryString() shift = findBestShift(wordList, text) return applyShift(text, shift) # # Build data structures used for entire session and run encryption # if __name__ == '__main__': # To test findBestShift: #wordList = loadWords() #s = applyShift('Hello, world!', 8) #bestShift = findBestShift(wordList, s) #assert applyShift(s, bestShift) == 'Hello, world!' # To test decryptStory, comment the above four lines and uncomment this line: print decryptStory()
{ "repo_name": "zhouyulian17/Course", "path": "Python/6.00.1x Introduction to Computer Science and Programming Using Python/ProblemSet6/ps6_encryption.py", "copies": "1", "size": "5154", "license": "mit", "hash": 6206161764396643000, "line_mean": 25.7046632124, "line_max": 98, "alpha_frac": 0.625145518, "autogenerated": false, "ratio": 3.778592375366569, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4903737893366569, "avg_score": null, "num_lines": null }
# 6.00x Problem Set 6 # # Part 1 - HAIL CAESAR! import string import random WORDLIST_FILENAME = "words.txt" # ----------------------------------- # Helper code def loadWords(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." inFile = open(WORDLIST_FILENAME, 'r') wordList = inFile.read().split() print " ", len(wordList), "words loaded." return wordList def isWord(wordList, word): """ Determines if word is a valid word. wordList: list of words in the dictionary. word: a possible word. returns True if word is in wordList. Example: >>> isWord(wordList, 'bat') returns True >>> isWord(wordList, 'asdf') returns False """ word = word.lower() word = word.strip(" !@#$%^&*()-_+={}[]|\\:;'<>?,./\"") return word in wordList def randomWord(wordList): """ Returns a random word. wordList: list of words returns: a word from wordList at random """ return random.choice(wordList) def randomString(wordList, n): """ Returns a string containing n random words from wordList wordList: list of words returns: a string of random words separated by spaces. """ return " ".join([randomWord(wordList) for _ in range(n)]) def randomScrambled(wordList, n): """ Generates a test string by generating an n-word random string and encrypting it with a sequence of random shifts. wordList: list of words n: number of random words to generate and scamble returns: a scrambled string of n random words NOTE: This function will ONLY work once you have completed your implementation of applyShifts! """ s = randomString(wordList, n) + " " shifts = [(i, random.randint(0, 25)) for i in range(len(s)) if s[i-1] == ' '] return applyShift(s, shifts)[:-1] def getStoryString(): """ Returns a story in encrypted text. """ return open("story.txt", "r").read() # (end of helper code) # Problem 1: Encryption def buildCoder(shift): """ Returns a dict that can apply a Caesar cipher to a letter. The cipher is defined by the shift value. Ignores non-letter characters like punctuation, numbers and spaces. shift: 0 <= int < 26 returns: dict """ cipher = {} for letter in string.ascii_uppercase: if ord(letter) + shift > ord('Z'): cipher[letter] = chr(ord('A') + shift - (ord('Z') - ord(letter) + 1)) else: cipher[letter] = chr(ord(letter) + shift) for letter in string.ascii_lowercase: if ord(letter) + shift > ord('z'): cipher[letter] = chr(ord('a') + shift - (ord('z') - ord(letter) + 1)) else: cipher[letter] = chr(ord(letter) + shift) return cipher def applyCoder(text, coder): """ Applies the coder to the text. Returns the encoded text. text: string coder: dict with mappings of characters to shifted characters returns: text after mapping coder chars to original text """ cipherText = '' for char in text: if char in string.ascii_letters: cipherText += coder[char] else: cipherText += char return cipherText def applyShift(text, shift): """ Given a text, returns a new text Caesar shifted by the given shift offset. Lower case letters should remain lower case, upper case letters should remain upper case, and all other punctuation should stay as it is. text: string to apply the shift to shift: amount to shift the text (0 <= int < 26) returns: text after being shifted by specified amount. """ return applyCoder(text, buildCoder(shift)) # Problem 2: Decryption def findBestShift(wordList, text): """ Finds a shift key that can decrypt the encoded text. text: string returns: 0 <= int < 26 """ bestShift = 0 bestShiftWords = 0 for shift in range(26): plainText = applyCoder(text, buildCoder(shift)) words = plainText.split(' ') currentShiftWords = 0 for word in words: cleanWord = '' for char in word: if char in string.ascii_letters: cleanWord += char if cleanWord in wordList: currentShiftWords += 1 if currentShiftWords > bestShiftWords: bestShift = shift bestShiftWords = currentShiftWords return bestShift def decryptStory(): """ Using the methods you created in this problem set, decrypt the story given by the function getStoryString(). Use the functions getStoryString and loadWords to get the raw data you need. returns: string - story in plain text """ wordList = loadWords() story = getStoryString() shift = findBestShift(wordList, story) return applyCoder(story, buildCoder(shift)) # Build data structures used for entire session and run encryption if __name__ == '__main__': # To test findBestShift: #wordList = loadWords() #s = applyShift('Hello, world!', 8) #bestShift = findBestShift(wordList, "Pq, dwV vjgtg Ku C VC pcOgf CNXkp!") #print(bestShift) #assert applyShift(s, bestShift) == 'Hello, world!' # To test decryptStory, comment the above four lines and uncomment this line: print decryptStory() #coder = buildCoder(4) #cipherText = applyCoder('Hullabaloo->', coder) #print(cipherText)
{ "repo_name": "nicola88/edx", "path": "MITx/6.00.1x/Week-6/Problem-Set-6/ps6_encryption.py", "copies": "1", "size": "5594", "license": "mit", "hash": 8681619399060628000, "line_mean": 28.140625, "line_max": 81, "alpha_frac": 0.6271004648, "autogenerated": false, "ratio": 3.863259668508287, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4990360133308287, "avg_score": null, "num_lines": null }
# 6.00x Problem Set 6 # # Part 1 - HAIL CAESAR! import string import random WORDLIST_FILENAME = "words.txt" # ----------------------------------- # Helper code # (you don't need to understand this helper code) def loadWords(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." inFile = open(WORDLIST_FILENAME, 'r') wordList = inFile.read().split() print " ", len(wordList), "words loaded." return wordList def isWord(wordList, word): """ Determines if word is a valid word. wordList: list of words in the dictionary. word: a possible word. returns True if word is in wordList. Example: >>> isWord(wordList, 'bat') returns True >>> isWord(wordList, 'asdf') returns False """ word = word.lower() word = word.strip(" !@#$%^&*()-_+={}[]|\\:;'<>?,./\"") return word in wordList def randomWord(wordList): """ Returns a random word. wordList: list of words returns: a word from wordList at random """ return random.choice(wordList) def randomString(wordList, n): """ Returns a string containing n random words from wordList wordList: list of words returns: a string of random words separated by spaces. """ return " ".join([randomWord(wordList) for _ in range(n)]) def randomScrambled(wordList, n): """ Generates a test string by generating an n-word random string and encrypting it with a sequence of random shifts. wordList: list of words n: number of random words to generate and scamble returns: a scrambled string of n random words NOTE: This function will ONLY work once you have completed your implementation of applyShifts! """ s = randomString(wordList, n) + " " shifts = [(i, random.randint(0, 25)) for i in range(len(s)) if s[i-1] == ' '] return applyShift(s, shifts)[:-1] def getStoryString(): """ Returns a story in encrypted text. """ return open("story.txt", "r").read() def getStorydecrypt(): """ Returns a story in decrypted texr """ return open("story2.txt", "r").read() # (end of helper code) # ----------------------------------- # # Problem 1: Encryption # def string_todict(lc, shift): """ returns a circular string of characters converted to dicts with a certian shift provided as the input shift: 0 <= int < 26 returns: dict """ d = dict() for i in range(len(lc)): try: d[lc[i]] = lc[i+shift] except IndexError: if (i + shift) >= 25: j = (i + shift) - 25 d[lc[i]] = lc[j - 1] continue return d def mergedicts(d, f): """ merges two dictionaries to give output as one dict """ return dict(d.items() + f.items()) def buildCoder(shift): """ Returns a dict that can apply a Caesar cipher to a letter. The cipher is defined by the shift value. Ignores non-letter characters like punctuation, numbers and spaces. shift: 0 <= int < 26 returns: dict """ lc = string.ascii_lowercase uc = string.ascii_uppercase d = string_todict(lc, shift) f = string_todict(uc, shift) q = mergedicts(d,f) return q def applyCoder(text, coder): """ Applies the coder to the text. Returns the encoded text. text: string coder: dict with mappings of characters to shifted characters returns: text after mapping coder chars to original text """ result = '' for i in text: if i in string.punctuation or i == ' ' or i.isdigit() or i == '\n': result += i else: result += coder[i] return result def applyShift(text, shift): """ Given a text, returns a new text Caesar shifted by the given shift offset. Lower case letters should remain lower case, upper case letters should remain upper case, and all other punctuation should stay as it is. text: string to apply the shift to shift: amount to shift the text (0 <= int < 26) returns: text after being shifted by specified amount. """ coder = buildCoder(shift) return applyCoder(text, coder) # # Problem 2: Decryption # def parser1(text): count = 0 word = '' z = [] words = text.split(" ") for word in words: for i in word: if i in string.punctuation or i == ' ' or i.isdigit(): z.append(word.replace(i, "")) if z == []: return words else: return z def findBestShift(wordList, text): """ Finds a shift key that can decrypt the encoded text. text: string returns: 0 <= int < 26 """ max_best = 0 best_shift = 0 words = parser1(text) for i in range(26): validwords = 0 for word in words: ret = applyShift(word, i) if isWord(wordList, ret): validwords += 1 if validwords > max_best: max_best = validwords best_shift = i return best_shift def decryptStory(): """ Using the methods you created in this problem set, decrypt the story given by the function getStoryString(). Use the functions getStoryString and loadWords to get the raw data you need. returns: string - story in plain text """ text = getStoryString() wordList = loadWords() r = findBestShift(wordList, text) return applyShift(text, r) def encryptStory(key): """ to encrypt the story, according to our key. key: is the key value for encryption """ text = getStorydecrypt() return applyShift(text, key) # # Build data structures used for entire session and run encryption # if __name__ == '__main__': # To test findBestShift: # wordList = loadWords() # s = applyShift('Hello, world!', 8) # bestShift = findBestShift(wordList, s) # assert applyShift(s, bestShift) == 'Hello, world!' # To test decryptStory, comment the above four lines and uncomment this line: text = decryptStory() print text print encryptStory(8)
{ "repo_name": "ahmedraza007/6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python", "path": "source/ProblemSet6/ps6_encryption.py", "copies": "1", "size": "6326", "license": "mit", "hash": -804341283839104100, "line_mean": 24.0079051383, "line_max": 83, "alpha_frac": 0.5975339867, "autogenerated": false, "ratio": 3.8432563791008505, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49407903658008506, "avg_score": null, "num_lines": null }
# 6.00x Problem Set 6 # # Part 2 - RECURSION # # Problem 3: Recursive String Reversal # def reverseString(aStr): """ Given a string, recursively returns a reversed copy of the string. For example, if the string is 'abc', the function returns 'cba'. The only string operations you are allowed to use are indexing, slicing, and concatenation. aStr: a string returns: a reversed string """ # base case if len(aStr) == 1: return aStr # recursion block return aStr[-1] + reverseString(aStr[:-1]) # # Problem 4: X-ian # def x_ian(x, word): """ Given a string x, returns True if all the letters in x are contained in word in the same order as they appear in x. >>> x_ian('eric', 'meritocracy') True >>> x_ian('eric', 'cerium') False >>> x_ian('john', 'mahjong') False x: a string word: a string returns: True if word is x_ian, False otherwise """ # base case if len(x) == 2: return word.index(x[0]) < word.index(x[1]) # recursion block if word.index(x[0]) < word.index(x[1]): return x_ian(x[1:], word) else: return False # --iteration implementation of x_ian START-- # index = -1 # for i in x: # if i in word and word.index(i) > index: # index = word.index(i) # else: # return False # return True # --iteration implementation of x_ian END-- # # Problem 5: Typewriter # def insertNewlines(text, lineLength): """ Given text and a desired line length, wrap the text as a typewriter would. Insert a newline character ("\n") after each word that reaches or exceeds the desired line length. text: a string containing the text to wrap. line_length: the number of characters to include on a line before wrapping the next word. returns: a string, with newline characters inserted appropriately. """ # base case if len(text) < lineLength: return text # recursion block return text[:lineLength] + '\n' + insertNewlines(text[lineLength:], lineLength)
{ "repo_name": "medifle/python_6.00.1x", "path": "PSet6/ps6_recursion.py", "copies": "1", "size": "2124", "license": "mit", "hash": 5823978072950275000, "line_mean": 25.8987341772, "line_max": 83, "alpha_frac": 0.6148775895, "autogenerated": false, "ratio": 3.6557659208261617, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4770643510326162, "avg_score": null, "num_lines": null }
# 6.00x Problem Set 6 # RSS Feed Filter import feedparser import string import time from project_util import translate_html from Tkinter import * import traceback #----------------------------------------------------------------------- # # Problem Set 6 #====================== # Code for retrieving and parsing RSS feeds # Do not change this code #====================== def process(url): """ Fetches news items from the rss url and parses them. Returns a list of NewsStory-s. """ feed = feedparser.parse(url) entries = feed.entries ret = [] for entry in entries: guid = entry.guid title = translate_html(entry.title) link = entry.link summary = translate_html(entry.summary) try: subject = translate_html(entry.tags[0]['term']) except AttributeError: subject = "" newsStory = NewsStory(guid, title, subject, summary, link) ret.append(newsStory) return ret #====================== #====================== # Part 1 # Data structure design #====================== # Problem 1 class NewsStory: def __init__(self, guid, title, subject, summary, link): self.guid = guid self.title = title self.subject = subject self.summary = summary self.link = link def getGuid(self): return self.guid def getTitle(self): return self.title def getSubject(self): return self.subject def getSummary(self): return self.summary def getLink(self): return self.link #====================== # Part 2 # Triggers #====================== class Trigger(object): def evaluate(self, story): """ Returns True if an alert should be generated for the given news item, or False otherwise. """ raise NotImplementedError # Whole Word Triggers # Problems 2-5 class WordTrigger(Trigger): def __init__(self, word): self.word = word.lower() def isWordIn(self, text): n_text = ''.join(' ' if c in string.punctuation else c.lower() for c in text) return self.word in n_text.split() class TitleTrigger(WordTrigger): def evaluate(self, story): return self.isWordIn(story.getTitle()) class SubjectTrigger(WordTrigger): def evaluate(self, story): return self.isWordIn(story.getSubject()) class SummaryTrigger(WordTrigger): def evaluate(self, story): return self.isWordIn(story.getSummary()) # Composite Triggers # Problems 6-8 class NotTrigger(Trigger): def __init__(self, trigger): self.trigger = trigger def evaluate(self, story): return not self.trigger.evaluate(story) class AndTrigger(Trigger): def __init__(self, trigger1, trigger2): self.trigger1 = trigger1 self.trigger2 = trigger2 def evaluate(self, story): return self.trigger1.evaluate(story) and self.trigger2.evaluate(story) class OrTrigger(Trigger): def __init__(self, trigger1, trigger2): self.trigger1 = trigger1 self.trigger2 = trigger2 def evaluate(self, story): return self.trigger1.evaluate(story) or self.trigger2.evaluate(story) # Phrase Trigger # Question 9 class PhraseTrigger(Trigger): def __init__(self, phrase): self.phrase = phrase def evaluate(self, story): return (self.phrase in story.getSubject() or self.phrase in story.getTitle() or self.phrase in story.getSummary()) #====================== # Part 3 # Filtering #====================== def filterStories(stories, triggerlist): """ Takes in a list of NewsStory instances. Returns: a list of only the stories for which a trigger in triggerlist fires. """ # This is a placeholder (we're just returning all the stories, with no filtering) return [story for story in stories if any( trigger.evaluate(story) for trigger in triggerlist )] #====================== # Part 4 # User-Specified Triggers #====================== def makeTrigger(triggerMap, triggerType, params, name): """ Takes in a map of names to trigger instance, the type of trigger to make, and the list of parameters to the constructor, and adds a new trigger to the trigger map dictionary. triggerMap: dictionary with names as keys (strings) and triggers as values triggerType: string indicating the type of trigger to make (ex: "TITLE") params: list of strings with the inputs to the trigger constructor (ex: ["world"]) name: a string representing the name of the new trigger (ex: "t1") Modifies triggerMap, adding a new key-value pair for this trigger. Returns a new instance of a trigger (ex: TitleTrigger, AndTrigger). """ type_trigger_map = {'TITLE': TitleTrigger, 'SUBJECT': SubjectTrigger, 'SUMMARY': SummaryTrigger, 'NOT': NotTrigger, 'AND': AndTrigger, 'OR': OrTrigger, 'PHRASE': PhraseTrigger} if triggerType == 'PHRASE': n_params = ' '.join(params) trigger = type_trigger_map[triggerType](n_params) elif triggerType in ('NOT', 'AND', 'OR'): n_params = [triggerMap[param] for param in params] trigger = type_trigger_map[triggerType](*n_params) else: trigger = type_trigger_map[triggerType](*params) triggerMap[name] = trigger return trigger def readTriggerConfig(filename): """ Returns a list of trigger objects that correspond to the rules set in the file filename """ # Here's some code that we give you # to read in the file and eliminate # blank lines and comments triggerfile = open(filename, "r") all = [ line.rstrip() for line in triggerfile.readlines() ] lines = [] for line in all: if len(line) == 0 or line[0] == '#': continue lines.append(line) triggers = [] triggerMap = {} # Be sure you understand this code - we've written it for you, # but it's code you should be able to write yourself for line in lines: linesplit = line.split(" ") # Making a new trigger if linesplit[0] != "ADD": trigger = makeTrigger(triggerMap, linesplit[1], linesplit[2:], linesplit[0]) # Add the triggers to the list else: for name in linesplit[1:]: triggers.append(triggerMap[name]) return triggers import thread SLEEPTIME = 60 #seconds -- how often we poll def main_thread(master): # A sample trigger list - you'll replace # this with something more configurable in Problem 11 try: # These will probably generate a few hits... t1 = TitleTrigger("on") t2 = SubjectTrigger("Romney") t3 = PhraseTrigger("Election") t4 = OrTrigger(t2, t3) triggerlist = [t1, t4] triggerlist = [t1] # After implementing makeTrigger, uncomment the line below: triggerlist = readTriggerConfig("triggers.txt") # **** from here down is about drawing **** frame = Frame(master) frame.pack(side=BOTTOM) scrollbar = Scrollbar(master) scrollbar.pack(side=RIGHT,fill=Y) t = "Google & Yahoo Top News" title = StringVar() title.set(t) ttl = Label(master, textvariable=title, font=("Helvetica", 18)) ttl.pack(side=TOP) cont = Text(master, font=("Helvetica",14), yscrollcommand=scrollbar.set) cont.pack(side=BOTTOM) cont.tag_config("title", justify='center') button = Button(frame, text="Exit", command=root.destroy) button.pack(side=BOTTOM) # Gather stories guidShown = [] def get_cont(newstory): if newstory.getGuid() not in guidShown: cont.insert(END, newstory.getTitle()+"\n", "title") cont.insert(END, "\n---------------------------------------------------------------\n", "title") cont.insert(END, newstory.getSummary()) cont.insert(END, "\n*********************************************************************\n", "title") guidShown.append(newstory.getGuid()) while True: print "Polling . . .", # Get stories from Google's Top Stories RSS news feed stories = process("http://news.google.com/?output=rss") # Get stories from Yahoo's Top Stories RSS news feed stories.extend(process("http://rss.news.yahoo.com/rss/topstories")) # Process the stories stories = filterStories(stories, triggerlist) map(get_cont, stories) scrollbar.config(command=cont.yview) print "Sleeping..." time.sleep(SLEEPTIME) except Exception as e: traceback.print_exc() #print e if __name__ == '__main__': root = Tk() root.title("Some RSS parser") thread.start_new_thread(main_thread, (root,)) root.mainloop()
{ "repo_name": "fossilet/6.00x", "path": "week6/problemset6/ps6.py", "copies": "1", "size": "9149", "license": "mit", "hash": 2318594821080466400, "line_mean": 27.0644171779, "line_max": 118, "alpha_frac": 0.5822494262, "autogenerated": false, "ratio": 4.102690582959641, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5184940009159642, "avg_score": null, "num_lines": null }
# 6.00x Problem Set 6 # RSS Feed Filter import feedparser import string import time from project_util import translate_html from Tkinter import * #----------------------------------------------------------------------- # # Problem Set 6 #====================== # Code for retrieving and parsing RSS feeds # Do not change this code #====================== def process(url): """ Fetches news items from the rss url and parses them. Returns a list of NewsStory-s. """ feed = feedparser.parse(url) entries = feed.entries ret = [] for entry in entries: guid = entry.guid title = translate_html(entry.title) link = entry.link summary = translate_html(entry.summary) try: subject = translate_html(entry.tags[0]['term']) except AttributeError: subject = "" newsStory = NewsStory(guid, title, subject, summary, link) ret.append(newsStory) return ret #====================== #====================== # Part 1 # Data structure design #====================== # Problem 1 class NewsStory: def __init__(self, guid, title, subject, summary, link): self.guid = guid self.title = title self.subject = subject self.summary = summary self.link = link def getGuid(self): return self.guid def getTitle(self): return self.title def getSubject(self): return self.subject def getSummary(self): return self.summary def getLink(self): return self.link #====================== # Part 2 # Triggers #====================== class Trigger(object): def evaluate(self, story): """ Returns True if an alert should be generated for the given news item, or False otherwise. """ raise NotImplementedError # Whole Word Triggers # Problems 2-5 class WordTrigger(Trigger): def __init__(self, word): self.word = word.lower() def isWordIn(self, text): for char in string.punctuation: text = text.replace(char,' ') text = text.split(' ') text = map(lambda s: s.lower(), text) # make every word in text lowercase return self.word in text class TitleTrigger(WordTrigger): def evaluate(self, story): return self.isWordIn(story.getTitle()) class SubjectTrigger(WordTrigger): def evaluate(self, story): return self.isWordIn(story.getSubject()) class SummaryTrigger(WordTrigger): def evaluate(self, story): return self.isWordIn(story.getSummary()) # Composite Triggers # Problems 6-8 class NotTrigger(Trigger): def __init__(self, T): self.T = T def evaluate(self, x): return not self.T.evaluate(x) class AndTrigger(Trigger): def __init__(self, T1, T2): self.T1 = T1 self.T2 = T2 def evaluate(self, x): return self.T1.evaluate(x) and self.T2.evaluate(x) class OrTrigger(Trigger): def __init__(self, T1, T2): self.T1 = T1 self.T2 = T2 def evaluate(self, x): return self.T1.evaluate(x) or self.T2.evaluate(x) # Phrase Trigger # Question 9 class PhraseTrigger(Trigger): def __init__(self, phrase): self.phrase = phrase def evaluate(self, story): return self.phrase in story.getSubject()+story.getTitle()+story.getSummary() #====================== # Part 3 # Filtering #====================== def filterStories(stories, triggerlist): """ Takes in a list of NewsStory instances. Returns: a list of only the stories for which a trigger in triggerlist fires. """ triggeredStories = [] for story in stories: for trigger in triggerlist: if trigger.evaluate(story): triggeredStories.append(story) return triggeredStories #====================== # Part 4 # User-Specified Triggers #====================== def makeTrigger(triggerMap, triggerType, params, name): """ Takes in a map of names to trigger instance, the type of trigger to make, and the list of parameters to the constructor, and adds a new trigger to the trigger map dictionary. triggerMap: dictionary with names as keys (strings) and triggers as values triggerType: string indicating the type of trigger to make (ex: "TITLE") params: list of strings with the inputs to the trigger constructor (ex: ["world"]) name: a string representing the name of the new trigger (ex: "t1") Modifies triggerMap, adding a new key-value pair for this trigger. Returns: None """ sParams = "" if triggerType in ["TITLE", "SUBJECT", "SUMMARY", "PHRASE"]: sParams += '"' for param in params: sParams += param+" " sParams = sParams[:-1] sParams += '"' elif triggerType in ["NOT", "AND", "OR"]: for param in params: sParams += "triggerMap['"+param+"']," sParams = sParams[:-1] evalString = triggerType.capitalize()+"Trigger("+sParams+")" triggerMap[name] = eval(evalString) return triggerMap[name] def readTriggerConfig(filename): """ Returns a list of trigger objects that correspond to the rules set in the file filename """ # Here's some code that we give you # to read in the file and eliminate # blank lines and comments triggerfile = open(filename, "r") all = [ line.rstrip() for line in triggerfile.readlines() ] lines = [] for line in all: if len(line) == 0 or line[0] == '#': continue lines.append(line) triggers = [] triggerMap = {} # Be sure you understand this code - we've written it for you, # but it's code you should be able to write yourself for line in lines: linesplit = line.split(" ") # Making a new trigger if linesplit[0] != "ADD": trigger = makeTrigger(triggerMap, linesplit[1], linesplit[2:], linesplit[0]) # Add the triggers to the list else: for name in linesplit[1:]: triggers.append(triggerMap[name]) return triggers import thread SLEEPTIME = 60 #seconds -- how often we poll def main_thread(master): # A sample trigger list - you'll replace # this with something more configurable in Problem 11 try: triggerlist = readTriggerConfig("triggers.txt") # from here is about drawing frame = Frame(master) frame.pack(side=BOTTOM) scrollbar = Scrollbar(master) scrollbar.pack(side=RIGHT,fill=Y) t = "Google & Yahoo Top News" title = StringVar() title.set(t) ttl = Label(master, textvariable=title, font=("Helvetica", 18)) ttl.pack(side=TOP) cont = Text(master, font=("Helvetica",14), yscrollcommand=scrollbar.set) cont.pack(side=BOTTOM) cont.tag_config("title", justify='center') button = Button(frame, text="Exit", command=root.destroy) button.pack(side=BOTTOM) guidShown = [] def get_cont(newstory): if newstory.get_guid() not in guidShown: cont.insert(END, newstory.get_title()+"\n", "title") cont.insert(END, "\n---------------------------------------------------------------\n", "title") cont.insert(END, newstory.get_summary()) cont.insert(END, "\n*********************************************************************\n", "title") guidShown.append(newstory.get_guid()) while True: print "Polling . . .", # Get stories from Google's Top Stories RSS news feed stories = process("http://news.google.com/?output=rss") # Get stories from Yahoo's Top Stories RSS news feed stories.extend(process("http://rss.news.yahoo.com/rss/topstories")) stories = filterStories(stories, triggerlist) map(get_cont, stories) scrollbar.config(command=cont.yview) print "Sleeping..." time.sleep(SLEEPTIME) except Exception as e: print e if __name__ == '__main__': root = Tk() root.title("Some RSS parser") thread.start_new_thread(main_thread, (root,)) root.mainloop()
{ "repo_name": "juampi/6.00x", "path": "ProblemSet06/ps6.py", "copies": "1", "size": "8313", "license": "mit", "hash": 6278079950951329000, "line_mean": 27.1796610169, "line_max": 118, "alpha_frac": 0.575845062, "autogenerated": false, "ratio": 4.019825918762089, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5095670980762088, "avg_score": null, "num_lines": null }
# 6.00x Problem Set 7: Simulating robots import math import random import ps7_visualize #from ps7_visualize import * import pylab # For Python 2.7: from ps7_verify_movement27 import * # If you get a "Bad magic number" ImportError, comment out what's above and # uncomment this line (for Python 2.6): # from ps7_verify_movement26 import testRobotMovement # === Provided class Position class Position(object): """ A Position represents a location in a two-dimensional room. """ def __init__(self, x, y): """ Initializes a position with coordinates (x, y). """ self.x = x self.y = y def getX(self): return self.x def getY(self): return self.y def getNewPosition(self, angle, speed): """ Computes and returns the new Position after a single clock-tick has passed, with this object as the current position, and with the specified angle and speed. Does NOT test whether the returned position fits inside the room. angle: number representing angle in degrees, 0 <= angle < 360 speed: positive float representing speed Returns: a Position object representing the new position. """ old_x, old_y = self.getX(), self.getY() angle = float(angle) # Compute the change in position delta_y = speed * math.cos(math.radians(angle)) delta_x = speed * math.sin(math.radians(angle)) # Add that to the existing position new_x = old_x + delta_x new_y = old_y + delta_y return Position(new_x, new_y) def __str__(self): return "(%0.2f, %0.2f)" % (self.x, self.y) # === Problem 1 class RectangularRoom(object): """ A RectangularRoom represents a rectangular region containing clean or dirty tiles. A room has a width and a height and contains (width * height) tiles. At any particular time, each of these tiles is either clean or dirty. """ def __init__(self, width, height): """ Initializes a rectangular room with the specified width and height. Initially, no tiles in the room have been cleaned. width: an integer > 0 height: an integer > 0 """ self.width = width self.height = height self.cleaned_tiles = [] def cleanTileAtPosition(self, pos): """ Mark the tile under the position POS as cleaned. Assumes that POS represents a valid position inside this room. pos: a Position """ x = math.floor(pos.getX()) y = math.floor(pos.getY()) if (x,y) not in self.cleaned_tiles: self.cleaned_tiles.append((x,y)) def isTileCleaned(self, m, n): """ Return True if the tile (m, n) has been cleaned. Assumes that (m, n) represents a valid tile inside the room. m: an integer n: an integer returns: True if (m, n) is cleaned, False otherwise """ return (m,n) in self.cleaned_tiles def getNumTiles(self): """ Return the total number of tiles in the room. returns: an integer """ return self.width * self.height def getNumCleanedTiles(self): """ Return the total number of clean tiles in the room. returns: an integer """ # return len(self.cleaned_tiles) cleanTiles = 0 for i in range(self.width): for j in range(self.height): if self.isTileCleaned(i, j): cleanTiles += 1 return cleanTiles def getRandomPosition(self): """ Return a random position inside the room. returns: a Position object. """ # x = random.choice(range(self.width)) # y = random.choice(range(self.height)) # # pos = Position(x,y) # return pos return Position(random.randint(0,self.width-1), random.randint(0,self.height-1)) def isPositionInRoom(self, pos): """ Return True if pos is inside the room. pos: a Position object. returns: True if pos is in the room, False otherwise. """ # return (0 <= pos.getX() < self.width) and (0 <= pos.getY < self.height) if (0 <= pos.getX() < self.width) and (0 <= pos.getY() < self.height): return True else: return False class Robot(object): """ Represents a robot cleaning a particular room. At all times the robot has a particular position and direction in the room. The robot also has a fixed speed. Subclasses of Robot should provide movement strategies by implementing updatePositionAndClean(), which simulates a single time-step. """ def __init__(self, room, speed): """ Initializes a Robot with the given speed in the specified room. The robot initially has a random direction and a random position in the room. The robot cleans the tile it is on. room: a RectangularRoom object. speed: a float (speed > 0) """ self.room = room self.direction = int(360 * random.random()) self.pos = self.room.getRandomPosition()#Position(room.width * random.random(), room.height * random.random()) self.room.cleanTileAtPosition(self.pos) if speed > 0: self.speed = speed else: raise ValueError('Speed input must be greater than zero(0)') # self.pos = getNewPosition(self.direction, self.speed) def getRobotPosition(self): """ Return the position of the robot. returns: a Position object giving the robot's position. """ return self.pos def getRobotDirection(self): """ Return the direction of the robot. returns: an integer d giving the direction of the robot as an angle in degrees, 0 <= d < 360. """ return self.direction def setRobotPosition(self, position): """ Set the position of the robot to POSITION. position: a Position object. """ if self.room.isPositionInRoom(position): self.pos = position else: raise ValueError('Position input is not in the room') def setRobotDirection(self, direction): """ Set the direction of the robot to DIRECTION. direction: integer representing an angle in degrees """ self.direction = direction def updatePositionAndClean(self): """ Simulate the raise passage of a single time-step. Move the robot to a new position and mark the tile it is on as having been cleaned. """ raise NotImplementedError # don't change this! # === Problem 2 class StandardRobot(Robot): """ A StandardRobot is a Robot with the standard movement strategy. At each time-step, a StandardRobot attempts to move in its current direction; when it would hit a wall, it *instead* chooses a new direction randomly. """ def updatePositionAndClean(self): """ Simulate the raise passage of a single time-step. Move the robot to a new position and mark the tile it is on as having been cleaned. """ new_pos = self.pos.getNewPosition(self.direction, self.speed) if self.room.isPositionInRoom(new_pos): self.setRobotPosition(new_pos) self.room.cleanTileAtPosition(self.pos) else: self.setRobotDirection(int(360 * random.random())) self.updatePositionAndClean() # Uncomment this line to see your implementation of StandardRobot in action! ##testRobotMovement(StandardRobot, RectangularRoom) # === Problem 3 def runSimulation(num_robots, speed, width, height, min_coverage, num_trials, robot_type): """ Runs NUM_TRIALS trials of the simulation and returns the mean number of time-steps needed to clean the fraction MIN_COVERAGE of the room. The simulation is run with NUM_ROBOTS robots of type ROBOT_TYPE, each with speed SPEED, in a room of dimensions WIDTH x HEIGHT. num_robots: an int (num_robots > 0) speed: a float (speed > 0) width: an int (width > 0) height: an int (height > 0) min_coverage: a float (0 <= min_coverage <= 1.0) num_trials: an int (num_trials > 0) robot_type: class of robot to be instantiated (e.g. StandardRobot or RandomWalkRobot) """ mean_time_taken = 0 robots = [] for num in range(num_trials): '''optional visualization''' anim = ps7_visualize.RobotVisualization(num_robots, width, height) room = RectangularRoom(width, height) for robot in xrange(num_robots): robots.append(robot_type(room, speed)) while room.getNumCleanedTiles() < (min_coverage * room.getNumTiles()): for robot in robots: robot.updatePositionAndClean() mean_time_taken += 1 anim.update(room, robots) anim.done() return float(mean_time_taken/ num_trials) runSimulation(10, 1.0, 30, 30, 0.8, 10, StandardRobot) # === Problem 4 class RandomWalkRobot(Robot): """ A RandomWalkRobot is a robot with the "random walk" movement strategy: it chooses a new direction at random at the end of each time-step. """ def updatePositionAndClean(self): """ Simulate the passage of a single time-step. Move the robot to a new position and mark the tile it is on as having been cleaned. """ new_pos = self.pos.getNewPosition(self.direction, self.speed) if self.room.isPositionInRoom(new_pos): self.setRobotPosition(new_pos) self.room.cleanTileAtPosition(self.pos) self.setRobotDirection(int(360 * random.random())) else: self.setRobotDirection(int(360 * random.random())) self.updatePositionAndClean() #runSimulation(10, 1.0, 15, 20, 0.8, 30, RandomWalkRobot) def showPlot1(title, x_label, y_label): """ What information does the plot produced by this function tell you? """ num_robot_range = range(1, 11) times1 = [] times2 = [] for num_robots in num_robot_range: print "Plotting", num_robots, "robots..." times1.append(runSimulation(num_robots, 1.0, 2, 2, 0.8, 10, StandardRobot)) times2.append(runSimulation(num_robots, 1.0, 2, 2, 0.8, 10, RandomWalkRobot)) pylab.plot(num_robot_range, times1) pylab.plot(num_robot_range, times2) pylab.title(title) pylab.legend(('StandardRobot', 'RandomWalkRobot')) pylab.xlabel(x_label) pylab.ylabel(y_label) pylab.show() def showPlot2(title, x_label, y_label): """ What information does the plot produced by this function tell you? """ aspect_ratios = [] times1 = [] times2 = [] for width in [10, 20, 25, 10]: height = 300/width print "Plotting cleaning time for a room of width:", width, "by height:", height aspect_ratios.append(float(width) / height) times1.append(runSimulation(2, 1.0, width, height, 0.8, 200, StandardRobot)) times2.append(runSimulation(2, 1.0, width, height, 0.8, 200, RandomWalkRobot)) pylab.plot(aspect_ratios, times1) pylab.plot(aspect_ratios, times2) pylab.title(title) pylab.legend(('StandardRobot', 'RandomWalkRobot')) pylab.xlabel(x_label) pylab.ylabel(y_label) pylab.show() # === Problem 5 # # 1) Write a function call to showPlot1 that generates an appropriately-labeled # plot. # # (... your call here ...) # #showPlot1("Plotting number robots...", 'x', 'y') #showPlot2("Plotting number robots...", 'x', 'y') # # 2) Write a function call to showPlot2 that generates an appropriately-labeled # plot. # # (... your call here ...) #
{ "repo_name": "b3ngmann/python-pastime", "path": "ps7/ps7.py", "copies": "1", "size": "12084", "license": "mit", "hash": -7892459734396978000, "line_mean": 30.5509138381, "line_max": 124, "alpha_frac": 0.6097318769, "autogenerated": false, "ratio": 3.938722294654498, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5048454171554498, "avg_score": null, "num_lines": null }
# 6.00x Problem Set 7: Simulating robots import math import random import ps7_visualize import pylab # For Python 2.7: from ps7_verify_movement27 import testRobotMovement # If you get a "Bad magic number" ImportError, comment out what's above and # uncomment this line (for Python 2.6): # from ps7_verify_movement26 import testRobotMovement # === Provided class Position class Position(object): """ A Position represents a location in a two-dimensional room. """ def __init__(self, x, y): """ Initializes a position with coordinates (x, y). """ self.x = x self.y = y def getX(self): return self.x def getY(self): return self.y def getNewPosition(self, angle, speed): """ Computes and returns the new Position after a single clock-tick has passed, with this object as the current position, and with the specified angle and speed. Does NOT test whether the returned position fits inside the room. angle: float representing angle in degrees, 0 <= angle < 360 speed: positive float representing speed Returns: a Position object representing the new position. """ old_x, old_y = self.getX(), self.getY() # Compute the change in position delta_y = speed * math.cos(math.radians(angle)) delta_x = speed * math.sin(math.radians(angle)) # Add that to the existing position new_x = old_x + delta_x new_y = old_y + delta_y return Position(new_x, new_y) def __str__(self): return "(%0.2f, %0.2f)" % (self.x, self.y) # === Problem 1 class RectangularRoom(object): """ A RectangularRoom represents a rectangular region containing clean or dirty tiles. A room has a width and a height and contains (width * height) tiles. At any particular time, each of these tiles is either clean or dirty. """ def __init__(self, width, height): """ Initializes a rectangular room with the specified width and height. Initially, no tiles in the room have been cleaned. width: an integer > 0 height: an integer > 0 """ self.width = width self.height = height self.cleanTiles = set() def cleanTileAtPosition(self, pos): """ Mark the tile under the position POS as cleaned. Assumes that POS represents a valid position inside this room. pos: a Position """ self.cleanTiles.add((int(pos.getX()),int(pos.getY()))) def isTileCleaned(self, m, n): """ Return True if the tile (m, n) has been cleaned. Assumes that (m, n) represents a valid tile inside the room. m: an integer n: an integer returns: True if (m, n) is cleaned, False otherwise """ pos = (int(m),int(n)) return pos in self.cleanTiles def getNumTiles(self): """ Return the total number of tiles in the room. returns: an integer """ return self.width*self.height def getNumCleanedTiles(self): """ Return the total number of clean tiles in the room. returns: an integer """ return len(self.cleanTiles) def getRandomPosition(self): """ Return a random position inside the room. returns: a Position object. """ return Position(random.randrange(self.width),random.randrange(self.height)) def isPositionInRoom(self, pos): """ Return True if pos is inside the room. pos: a Position object. returns: True if pos is in the room, False otherwise. """ return pos.getX() < self.width and pos.getY() < self.height and pos.getX() >= 0 and pos.getY() >= 0 class Robot(object): """ Represents a robot cleaning a particular room. At all times the robot has a particular position and direction in the room. The robot also has a fixed speed. Subclasses of Robot should provide movement strategies by implementing updatePositionAndClean(), which simulates a single time-step. """ def __init__(self, room, speed): """ Initializes a Robot with the given speed in the specified room. The robot initially has a random direction and a random position in the room. The robot cleans the tile it is on. room: a RectangularRoom object. speed: a float (speed > 0) """ self.room = room self.speed = speed self.direction = random.randrange(360) self.position = room.getRandomPosition() def getRobotPosition(self): """ Return the position of the robot. returns: a Position object giving the robot's position. """ return self.position def getRobotDirection(self): """ Return the direction of the robot. returns: an integer d giving the direction of the robot as an angle in degrees, 0 <= d < 360. """ return self.direction def setRobotPosition(self, position): """ Set the position of the robot to POSITION. position: a Position object. """ self.position = position def setRobotDirection(self, direction): """ Set the direction of the robot to DIRECTION. direction: integer representing an angle in degrees """ self.direction = direction def updatePositionAndClean(self): """ Simulate the raise passage of a single time-step. Move the robot to a new position and mark the tile it is on as having been cleaned. """ raise NotImplementedError # don't change this! # === Problem 2 class StandardRobot(Robot): """ A StandardRobot is a Robot with the standard movement strategy. At each time-step, a StandardRobot attempts to move in its current direction; when it would hit a wall, it *instead* chooses a new direction randomly. """ def updatePositionAndClean(self): """ Simulate the raise passage of a single time-step. Move the robot to a new position and mark the tile it is on as having been cleaned. """ pos = self.getRobotPosition() direction = self.getRobotDirection() speed = self.speed newPos = Position(pos.getX()+speed*math.sin(math.radians(direction)),pos.getY()+speed*math.cos(math.radians(direction))) if self.room.isPositionInRoom(newPos): self.setRobotPosition(newPos) self.room.cleanTileAtPosition(newPos) else: self.setRobotDirection(random.randrange(360)) # Uncomment this line to see your implementation of StandardRobot in action! ##testRobotMovement(StandardRobot, RectangularRoom) # === Problem 3 def runSimulation(num_robots, speed, width, height, min_coverage, num_trials, robot_type): """ Runs NUM_TRIALS trials of the simulation and returns the mean number of time-steps needed to clean the fraction MIN_COVERAGE of the room. The simulation is run with NUM_ROBOTS robots of type ROBOT_TYPE, each with speed SPEED, in a room of dimensions WIDTH x HEIGHT. num_robots: an int (num_robots > 0) speed: a float (speed > 0) width: an int (width > 0) height: an int (height > 0) min_coverage: a float (0 <= min_coverage <= 1.0) num_trials: an int (num_trials > 0) robot_type: class of robot to be instantiated (e.g. StandardRobot or RandomWalkRobot) """ total_time_steps = 0.0 for trial in range(num_trials): room = RectangularRoom(width, height) robots = [] for i in range(num_robots): robots.append(robot_type(room,speed)) time_steps = 0 while room.getNumCleanedTiles()*1.0/room.getNumTiles() < min_coverage: time_steps += 1 for robot in robots: robot.updatePositionAndClean() total_time_steps += time_steps return total_time_steps/num_trials # === Problem 4 class RandomWalkRobot(Robot): def updatePositionAndClean(self): """ Simulate the raise passage of a single time-step. Move the robot to a new position and mark the tile it is on as having been cleaned. """ pos = self.getRobotPosition() direction = self.getRobotDirection() speed = self.speed newPos = Position(pos.getX()+speed*math.sin(math.radians(direction)),pos.getY()+speed*math.cos(math.radians(direction))) if self.room.isPositionInRoom(newPos): self.setRobotPosition(newPos) self.room.cleanTileAtPosition(newPos) self.setRobotDirection(random.randrange(360)) else: self.setRobotDirection(random.randrange(360)) # === Problem 5 # # 1) Write a function call to showPlot1 that generates an appropriately-labeled # plot. # # showPlot1("Time It Takes 1 - 10 Robots To Clean 80% Of A Room", "Number of Robots", "Time-steps") # # # 2) Write a function call to showPlot2 that generates an appropriately-labeled # plot. # # showPlot2("Time It Takes 1 - 10 Robots To Clean 80% Of A Room ", "Aspect Ratio", "Time-steps") # # def showPlot1(title, x_label, y_label): """ What information does the plot produced by this function tell you? """ num_robot_range = range(1, 11) times1 = [] times2 = [] for num_robots in num_robot_range: print "Plotting", num_robots, "robots..." times1.append(runSimulation(num_robots, 1.0, 20, 20, 0.8, 20, StandardRobot)) times2.append(runSimulation(num_robots, 1.0, 20, 20, 0.8, 20, RandomWalkRobot)) pylab.plot(num_robot_range, times1) pylab.plot(num_robot_range, times2) pylab.title(title) pylab.legend(('StandardRobot', 'RandomWalkRobot')) pylab.xlabel(x_label) pylab.ylabel(y_label) pylab.show() def showPlot2(title, x_label, y_label): """ What information does the plot produced by this function tell you? """ aspect_ratios = [] times1 = [] times2 = [] for width in [10, 20, 25, 50]: height = 300/width print "Plotting cleaning time for a room of width:", width, "by height:", height aspect_ratios.append(float(width) / height) times1.append(runSimulation(2, 1.0, width, height, 0.8, 200, StandardRobot)) times2.append(runSimulation(2, 1.0, width, height, 0.8, 200, RandomWalkRobot)) pylab.plot(aspect_ratios, times1) pylab.plot(aspect_ratios, times2) pylab.title(title) pylab.legend(('StandardRobot', 'RandomWalkRobot')) pylab.xlabel(x_label) pylab.ylabel(y_label) pylab.show()
{ "repo_name": "juampi/6.00x", "path": "ProblemSet07/ps7.py", "copies": "1", "size": "10849", "license": "mit", "hash": -3751101475361587700, "line_mean": 30.265129683, "line_max": 128, "alpha_frac": 0.6258641349, "autogenerated": false, "ratio": 3.9522768670309656, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.004609804951699732, "num_lines": 347 }
"""60. Permutation Sequence https://leetcode.com/problems/permutation-sequence/ The set [1,2,3,...,n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, we get the following sequence for n = 3: "123" "132" "213" "231" "312" "321" Given n and k, return the kth permutation sequence. Note: Given n will be between 1 and 9 inclusive. Given k will be between 1 and n! inclusive. Example 1: Input: n = 3, k = 3 Output: "213" Example 2: Input: n = 4, k = 9 Output: "2314" """ from typing import List class Solution: def get_permutation(self, n: int, k: int) -> str: def count(m: int): mul = 1 for i in range(m, 0, -1): mul *= i return mul def backtrack(nums: List[int], kth: int): res = "" i, j = divmod(kth, count(len(nums) - 1)) if j > 0: res += str(nums.pop(i)) res += backtrack(nums, j) else: res += str(nums.pop(i - 1)) res += ''.join(str(_) for _ in nums[::-1]) return res return backtrack([_ for _ in range(1, n + 1)], k)
{ "repo_name": "isudox/leetcode-solution", "path": "python-algorithm/leetcode/permutation_sequence.py", "copies": "1", "size": "1193", "license": "mit", "hash": -569886761548710000, "line_mean": 20.3035714286, "line_max": 65, "alpha_frac": 0.5398155909, "autogenerated": false, "ratio": 3.2955801104972378, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9335395701397238, "avg_score": 0, "num_lines": 56 }
# 6.15 def print_spiral(array): x = len(array[0]) y = len(array) max_bounds = { "right": x-1, "down": y-1, "left": 0, "up": 1 } number_of_elements = x*y coord = (0, -1) func = go_right result = [] while number_of_elements > 0: number, func, coord = func(array, coord, max_bounds, result) number_of_elements -= number print(", ".join(map(str, result))) def go_right(array, coord, maximum, result): elements = 0 increment = 1 y, x = coord x += increment while x <= maximum["right"]: result.append(array[y][x]) x += increment elements += 1 maximum["right"] -= 1 return elements, go_down, (y, x-increment) def go_down(array, coord, maximum, result): elements = 0 increment = 1 y, x = coord y += increment while y <= maximum["down"]: result.append(array[y][x]) y += increment elements += 1 maximum["down"] -= 1 return elements, go_left, (y-increment, x) def go_left(array, coord, minimum, result): elements = 0 increment = -1 y, x = coord x += increment while x >= minimum["left"]: result.append(array[y][x]) x += increment elements += 1 minimum["left"] += 1 return elements, go_up, (y, x-increment) def go_up(array, coord, minimum, result): elements = 0 increment = -1 y, x = coord y += increment while y >= minimum["up"]: result.append(array[y][x]) y += increment elements += 1 minimum["up"] += 1 return elements, go_right, (y-increment, x) def generate_input(n, m): import random as rnd arr = list() for _ in range(0, m): l = list() for __ in range(0, n): l.append(rnd.randint(0, 100)) arr.append(l) return arr def print_array(array): for l in array: print(l) # print
{ "repo_name": "napplebee/EPI", "path": "epi/spiral_array.py", "copies": "2", "size": "1948", "license": "mit", "hash": 8793734870602898000, "line_mean": 20.8876404494, "line_max": 68, "alpha_frac": 0.5302874743, "autogenerated": false, "ratio": 3.435626102292769, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9960147757550782, "avg_score": 0.001153163808397398, "num_lines": 89 }
#61.题目:打印出杨辉三角形(要求打印出10行如下图)。   #利用生成器解决 def triangle(): x = [1] while True: yield x #zip: 添加0组成元组 x = [sum(i) for i in zip([0]+x, x+[0])] num = 0 for x in triangle(): print(x) num += 1 if num == 10: break #62.题目:查找字符串。 str1 = 'abcdedf' str2 = 'ded' print('The find index is %d ' % str1.find(str2)) #63.题目:画椭圆。  from tkinter import * def draw_oval(): x = 360 y = 160 top = y-30 bottom = y-30 canvas = Canvas(width=400, height=600, bg='white') for i in range(20): canvas.create_oval(250-top, 250-bottom, 250+top, 250+bottom) top -= 5 bottom += 5 canvas.pack() mainloop() #draw_oval() #64. 利用ellipse 和 rectangle 画图。 def draw_rectangle(): canvas = Canvas(width=400, height=600, bg='white') for i in range(num): canvas.create_rectangle(20 - 2 * i, 20-2 * i, 10 * (i+2), 10 * (i+2)) canvas.pack() mainloop() #draw_rectangle() #65. 一个最优美的图案。 #抄的demo import math class PTS: def __init__(self): self.x = 0 self.y = 0 points = [] def line_to_demo(): screenx = 400 screeny = 400 canvas = Canvas(width = screenx,height = screeny,bg = 'white') AspectRatio = 0.85 MAXPTS = 15 h = screeny w = screenx xcenter = w / 2 ycenter = h / 2 radius = (h - 30) / (AspectRatio * 2) - 20 step = 360 / MAXPTS angle = 0.0 for i in range(MAXPTS): rads = angle * math.pi / 180.0 p = PTS() p.x = xcenter + int(math.cos(rads) * radius) p.y = ycenter - int(math.sin(rads) * radius * AspectRatio) angle += step points.append(p) canvas.create_oval(xcenter - radius,ycenter - radius, xcenter + radius,ycenter + radius) for i in range(MAXPTS): for j in range(i,MAXPTS): canvas.create_line(points[i].x,points[i].y,points[j].x,points[j].y) canvas.pack() mainloop() #line_to_demo() #66. 题目:输入3个数a,b,c,按大小顺序输出。 def swap(x1, x2): return x2, x1 m1 = 50 m2 = 100 print('The value is x1 %d, x2 %d' % swap(m1, m2)) #67. 题目:输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组。 def swap_max_first(array): maxNum = 0 for i in range(len(array)-1): if array[maxNum] < array[i]: maxNum = i array[0], array[maxNum] = array[maxNum], array[i] maxArray = [1,3,5,6,9,11,8,7] swap_max_first(maxArray) # for x in maxArray: # print(x) #68. 题目:有n个整数,使其前面各数顺序向后移m个位置,最后m个数变成最前面的m个数 # 循环数组 def rotation_array_by_reversal(array, start, end): while start < end: tmp = array[start] array[start] = array[end] array[end] = tmp start += 1 end -= 1 def rotation_array(array, index): lenx = len(array) rotation_array_by_reversal(array, 0, index-1) rotation_array_by_reversal(array, index, lenx-1) rotation_array_by_reversal(array, 0, lenx-1) rotation_array(maxArray, 2) # for rex in maxArray: # print(rex) #69. 题目:有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。 def rotation_remove(array): i = 1 while len(array) > 1: if i % 3 ==0: array.pop(0) else: array.insert(len(array), array.pop(0)) i += 1 dataArray = [i+1 for i in range(34)] rotation_remove(dataArray) print(dataArray) #70. 题目:写一个函数,求一个字符串的长度,在main函数中输入字符串,并输出其长度。 def str_len(strx): print('The str len is %d' % len(strx)) str_len('aaddffee')
{ "repo_name": "cwenao/python_web_learn", "path": "base100/base100/base_61-70.py", "copies": "1", "size": "3975", "license": "apache-2.0", "hash": -5340528991041915000, "line_mean": 17.7934782609, "line_max": 79, "alpha_frac": 0.574486549, "autogenerated": false, "ratio": 2.255055446836269, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3329541995836269, "avg_score": null, "num_lines": null }
"""62. Unique Paths https://leetcode.com/problems/unique-paths/ A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many possible unique paths are there? Above is a 7 x 3 grid. How many possible unique paths are there? Note: m and n will be at most 100. Example 1: Input: m = 3, n = 2 Output: 3 Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Right -> Down 2. Right -> Down -> Right 3. Down -> Right -> Right Example 2: Input: m = 7, n = 3 Output: 28 """ class Solution: def unique_paths(self, m: int, n: int) -> int: # dp[i][j] is the number of ways to reach grid[i][j] from start corner. dp = [[0] * m for _ in range(n)] dp[0] = [1] * m for _ in range(n): dp[_][0] = 1 for i in range(1, n): for j in range(1, m): dp[i][j] = dp[i][j - 1] + dp[i - 1][j] return dp[n - 1][m - 1]
{ "repo_name": "isudox/leetcode-solution", "path": "python-algorithm/leetcode/unique_paths.py", "copies": "1", "size": "1170", "license": "mit", "hash": 2047565186621674800, "line_mean": 24.4347826087, "line_max": 87, "alpha_frac": 0.6068376068, "autogenerated": false, "ratio": 3.0870712401055407, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4193908846905541, "avg_score": null, "num_lines": null }
# 6-3. Glossary: A Python dictionary can be used to model an actual dictionary. # However, to avoid confusion, let’s call it a glossary. # • Think of five programming words you’ve learned about in the previous chapters. # Use these words as the keys in your glossary, and store their meanings as values. # • Print each word and its meaning as neatly formatted output. You might print the word followed by a colon # and then its meaning, or print the word on one line and then print its meaning indented on a second line. # Use the newline character (\n) to insert a blank line between each word-meaning pair in your output. glossary = { 'str': 'A kind of object related with series of characters.', 'list': 'A collection of items.', 'comments': 'Notes in a program.', 'insert': "It's for add something in a list.", 'del': "It's for delete something in a list.", } word = 'str' print("\n" + word.title() + ": " + glossary[word]) word = 'list' print("\n" + word.title() + ": " + glossary[word]) word = 'comments' print("\n" + word.title() + ": " + glossary[word]) word = 'insert' print("\n" + word.title() + ": " + glossary[word]) word = 'del' print("\n" + word.title() + ": " + glossary[word])
{ "repo_name": "AnhellO/DAS_Sistemas", "path": "Ago-Dic-2019/DanielM/PracticaUno/6.3_Glossary.py", "copies": "1", "size": "1231", "license": "mit", "hash": 7405889597583223000, "line_mean": 38.4838709677, "line_max": 108, "alpha_frac": 0.6696647588, "autogenerated": false, "ratio": 3.341530054644809, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.949956654510194, "avg_score": 0.0023256536685738283, "num_lines": 31 }
# 6.3 def get_battery_capacity(steps): result_capacity = 0 current_capacity = 0 energy_needed = False for step in reversed(steps): # just skip last positive elements if not energy_needed: if step < 0: energy_needed = True else: continue current_capacity -= step if current_capacity > result_capacity: result_capacity = current_capacity elif current_capacity < 0: current_capacity = 0 return result_capacity def prove(max_capacity, steps): print("Testing assumption: {0} for {1}.".format(max_capacity, steps)) current_capacity = max_capacity for step in steps: print("Step: {0}".format(step)) current_capacity += step if current_capacity > max_capacity: current_capacity = max_capacity if current_capacity < 0: print("ERROR: Current capacity below zero") with open("result.out", "w+") as f: f.write("Error found for the assumption: {0} for {1}.".format(max_capacity, steps)) import os f.write(os.linesep) return print("Current capacity: {0}".format(current_capacity)) print("Assumption is correct")
{ "repo_name": "napplebee/algorithms", "path": "epi/robot.py", "copies": "2", "size": "1294", "license": "mit", "hash": 2275122525974983700, "line_mean": 32.1794871795, "line_max": 99, "alpha_frac": 0.5765069552, "autogenerated": false, "ratio": 4.386440677966101, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5962947633166101, "avg_score": null, "num_lines": null }
"""63. Unique Paths II https://leetcode.com/problems/unique-paths-ii/ A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). Now consider if some obstacles are added to the grids. How many unique paths would there be? An obstacle and empty space is marked as 1 and 0 respectively in the grid. Note: m and n will be at most 100. Example 1: Input: [ [0,0,0], [0,1,0], [0,0,0] ] Output: 2 Explanation: There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right """ from typing import List class Solution: def unique_paths_with_obstacles(self, obstacle_grid): """ :type obstacle_grid: List[List[int]] :rtype: int """ rows, cols = len(obstacle_grid), len(obstacle_grid[0]) dp = [[1] * cols for _ in range(rows)] for _ in range(cols): if obstacle_grid[0][_] == 1: dp[0][_] = 0 else: dp[0][_] = dp[0][_ - 1] for _ in range(rows): if obstacle_grid[_][0] == 1: dp[_][0] = 0 else: dp[_][0] = dp[_ - 1][0] for i in range(1, rows): for j in range(1, cols): if obstacle_grid[i][j] == 1: dp[i][j] = 0 else: dp[i][j] = dp[i][j - 1] + dp[i - 1][j] return dp[rows - 1][cols - 1]
{ "repo_name": "isudox/leetcode-solution", "path": "python-algorithm/leetcode/unique_paths_ii.py", "copies": "1", "size": "1695", "license": "mit", "hash": 2167477229631199200, "line_mean": 25.9047619048, "line_max": 74, "alpha_frac": 0.5486725664, "autogenerated": false, "ratio": 3.2041587901701325, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9252831356570133, "avg_score": 0, "num_lines": 63 }
"""64bit ARM/NEON assembly emitter. Used by code generators to produce ARM assembly with NEON simd code. Provides tools for easier register management: named register variable allocation/deallocation, and offers a more procedural/structured approach to generating assembly. """ _WIDE_TYPES = {8: 16, 16: 32, 32: 64, '8': '16', '16': '32', '32': '64', 'i8': 'i16', 'i16': 'i32', 'i32': 'i64', 'u8': 'u16', 'u16': 'u32', 'u32': 'u64', 's8': 's16', 's16': 's32', 's32': 's64'} _NARROW_TYPES = {64: 32, 32: 16, 16: 8, '64': '32', '32': '16', '16': '8', 'i64': 'i32', 'i32': 'i16', 'i16': 'i8', 'u64': 'u32', 'u32': 'u16', 'u16': 'u8', 's64': 's32', 's32': 's16', 's16': 's8'} _TYPE_BITS = {8: 8, 16: 16, 32: 32, 64: 64, '8': 8, '16': 16, '32': 32, '64': 64, 'i8': 8, 'i16': 16, 'i32': 32, 'i64': 64, 'u8': 8, 'u16': 16, 'u32': 32, 'u64': 64, 's8': 8, 's16': 16, 's32': 32, 's64': 64, 'f32': 32, 'f64': 64, 'b': 8, 'h': 16, 's': 32, 'd': 64} class Error(Exception): """Module level error.""" class RegisterAllocationError(Error): """Cannot alocate registers.""" class LaneError(Error): """Wrong lane number.""" class RegisterSubtypeError(Error): """The register needs to be lane-typed.""" class ArgumentError(Error): """Wrong argument.""" def _AppendType(type_name, register): """Calculates sizes and attaches the type information to the register.""" if register.register_type is not 'v': raise ArgumentError('Only vector registers can have type appended.') if type_name in set([8, '8', 'i8', 's8', 'u8']): subtype = 'b' subtype_bits = 8 elif type_name in set([16, '16', 'i16', 's16', 'u16']): subtype = 'h' subtype_bits = 16 elif type_name in set([32, '32', 'i32', 's32', 'u32', 'f32']): subtype = 's' subtype_bits = 32 elif type_name in set([64, '64', 'i64', 's64', 'u64', 'f64']): subtype = 'd' subtype_bits = 64 else: raise ArgumentError('Unknown type: %s' % type_name) new_register = register.Copy() new_register.register_subtype = subtype new_register.register_subtype_count = register.register_bits / subtype_bits return new_register def _UnsignedType(type_name): return type_name in set(['u8', 'u16', 'u32', 'u64']) def _FloatType(type_name): return type_name in set(['f32', 'f64']) def _WideType(type_name): if type_name in _WIDE_TYPES.keys(): return _WIDE_TYPES[type_name] else: raise ArgumentError('No wide type for: %s' % type_name) def _NarrowType(type_name): if type_name in _NARROW_TYPES.keys(): return _NARROW_TYPES[type_name] else: raise ArgumentError('No narrow type for: %s' % type_name) def _LoadStoreSize(register): if register.lane is None: return register.register_bits else: return register.lane_bits def _MakeCompatibleDown(reg_1, reg_2, reg_3): bits = min([reg_1.register_bits, reg_2.register_bits, reg_3.register_bits]) return (_Cast(bits, reg_1), _Cast(bits, reg_2), _Cast(bits, reg_3)) def _MakeCompatibleUp(reg_1, reg_2, reg_3): bits = max([reg_1.register_bits, reg_2.register_bits, reg_3.register_bits]) return (_Cast(bits, reg_1), _Cast(bits, reg_2), _Cast(bits, reg_3)) def _Cast(bits, reg): if reg.register_bits is bits: return reg else: new_reg = reg.Copy() new_reg.register_bits = bits return new_reg def _TypeBits(type_name): if type_name in _TYPE_BITS.keys(): return _TYPE_BITS[type_name] else: raise ArgumentError('Unknown type: %s' % type_name) def _RegisterList(list_type, registers): lanes = list(set([register.lane for register in registers])) if len(lanes) > 1: raise ArgumentError('Cannot mix lanes on a register list.') typed_registers = [_AppendType(list_type, register) for register in registers] if lanes[0] is None: return '{%s}' % ', '.join(map(str, typed_registers)) elif lanes[0] is -1: raise ArgumentError('Cannot construct a list with all lane indexing.') else: typed_registers_nolane = [register.Copy() for register in typed_registers] for register in typed_registers_nolane: register.lane = None register.register_subtype_count = None return '{%s}[%d]' % (', '.join(map(str, typed_registers_nolane)), lanes[0]) class _GeneralRegister(object): """Arm v8 general register: (x|w)n.""" def __init__(self, register_bits, number, dereference=False, dereference_increment=False): self.register_type = 'r' self.register_bits = register_bits self.number = number self.dereference = dereference self.dereference_increment = dereference_increment def Copy(self): return _GeneralRegister(self.register_bits, self.number, self.dereference, self.dereference_increment) def __repr__(self): if self.register_bits is 64: text = 'x%d' % self.number elif self.register_bits <= 32: text = 'w%d' % self.number else: raise RegisterSubtypeError('Wrong bits (%d) for general register: %d' % (self.register_bits, self.number)) if self.dereference: return '[%s]' % text else: return text class _MappedParameter(object): """Object representing a C variable mapped to a register.""" def __init__(self, name, register_bits=64, dereference=False, dereference_increment=False): self.name = name self.register_bits = register_bits self.dereference = dereference self.dereference_increment = dereference_increment def Copy(self): return _MappedParameter(self.name, self.register_bits, self.dereference, self.dereference_increment) def __repr__(self): if self.register_bits is 64: text = '%%x[%s]' % self.name elif self.register_bits <= 32: text = '%%w[%s]' % self.name else: raise RegisterSubtypeError('Wrong bits (%d) for mapped parameter: %s' % (self.register_bits, self.name)) if self.dereference: return '[%s]' % text else: return text class _VectorRegister(object): """Arm v8 vector register Vn.TT.""" def __init__(self, register_bits, number, register_subtype=None, register_subtype_count=None, lane=None, lane_bits=None): self.register_type = 'v' self.register_bits = register_bits self.number = number self.register_subtype = register_subtype self.register_subtype_count = register_subtype_count self.lane = lane self.lane_bits = lane_bits def Copy(self): return _VectorRegister(self.register_bits, self.number, self.register_subtype, self.register_subtype_count, self.lane, self.lane_bits) def __repr__(self): if self.register_subtype is None: raise RegisterSubtypeError('Register: %s%d has no lane types defined.' % (self.register_type, self.number)) if (self.register_subtype_count is None or (self.lane is not None and self.lane is not -1)): typed_name = '%s%d.%s' % (self.register_type, self.number, self.register_subtype) else: typed_name = '%s%d.%d%s' % (self.register_type, self.number, self.register_subtype_count, self.register_subtype) if self.lane is None or self.lane is -1: return typed_name elif self.lane >= 0 and self.lane < self.register_subtype_count: return '%s[%d]' % (typed_name, self.lane) else: raise LaneError('Wrong lane: %d for: %s' % (self.lane, typed_name)) class _ImmediateConstant(object): def __init__(self, value): self.register_type = 'i' self.value = value def Copy(self): return _ImmediateConstant(self.value) def __repr__(self): return '#%d' % self.value class _NeonRegisters64Bit(object): """Utility that keeps track of used 32bit ARM/NEON registers.""" def __init__(self): self.vector = set() self.vector_ever = set() self.general = set() self.general_ever = set() self.parameters = set() def MapParameter(self, parameter): self.parameters.add(parameter) return _MappedParameter(parameter) def _VectorRegisterNum(self, min_val=0): for i in range(min_val, 32): if i not in self.vector: self.vector.add(i) self.vector_ever.add(i) return i raise RegisterAllocationError('Not enough vector registers.') def DoubleRegister(self, min_val=0): return _VectorRegister(64, self._VectorRegisterNum(min_val)) def QuadRegister(self, min_val=0): return _VectorRegister(128, self._VectorRegisterNum(min_val)) def GeneralRegister(self): for i in range(0, 30): if i not in self.general: self.general.add(i) self.general_ever.add(i) return _GeneralRegister(64, i) raise RegisterAllocationError('Not enough general registers.') def MappedParameters(self): return [x for x in self.parameters] def Clobbers(self): return (['x%d' % i for i in self.general_ever] + ['v%d' % i for i in self.vector_ever]) def FreeRegister(self, register): if register.register_type == 'v': assert register.number in self.vector self.vector.remove(register.number) elif register.register_type == 'r': assert register.number in self.general self.general.remove(register.number) else: raise RegisterAllocationError('Register not allocated: %s%d' % (register.register_type, register.number)) def FreeRegisters(self, registers): for register in registers: self.FreeRegister(register) class NeonEmitter64(object): """Emits ARM/NEON 64bit assembly opcodes.""" def __init__(self, debug=False): self.ops = {} self.indent = '' self.debug = debug def PushIndent(self): self.indent += ' ' def PopIndent(self): self.indent = self.indent[:-2] def EmitIndented(self, what): print self.indent + what def PushOp(self, op): if op in self.ops.keys(): self.ops[op] += 1 else: self.ops[op] = 1 def ClearCounters(self): self.ops.clear() def EmitNewline(self): print '' def EmitPreprocessor1(self, op, param): print '#%s %s' % (op, param) def EmitPreprocessor(self, op): print '#%s' % op def EmitInclude(self, include): self.EmitPreprocessor1('include', include) def EmitCall1(self, function, param): self.EmitIndented('%s(%s);' % (function, param)) def EmitAssert(self, assert_expression): if self.debug: self.EmitCall1('assert', assert_expression) def EmitHeaderBegin(self, header_name, includes): self.EmitPreprocessor1('ifndef', (header_name + '_H_').upper()) self.EmitPreprocessor1('define', (header_name + '_H_').upper()) self.EmitNewline() if includes: for include in includes: self.EmitInclude(include) self.EmitNewline() def EmitHeaderEnd(self): self.EmitPreprocessor('endif') def EmitCode(self, code): self.EmitIndented('%s;' % code) def EmitFunctionBeginA(self, function_name, params, return_type): self.EmitIndented('%s %s(%s) {' % (return_type, function_name, ', '.join(['%s %s' % (t, n) for (t, n) in params]))) self.PushIndent() def EmitFunctionEnd(self): self.PopIndent() self.EmitIndented('}') def EmitAsmBegin(self): self.EmitIndented('asm volatile(') self.PushIndent() def EmitAsmMapping(self, elements, modifier): if elements: self.EmitIndented(': ' + ', '.join(['[%s] "%s"(%s)' % (d, modifier, d) for d in elements])) else: self.EmitIndented(':') def EmitClobbers(self, elements): if elements: self.EmitIndented(': ' + ', '.join(['"%s"' % c for c in elements])) else: self.EmitIndented(':') def EmitAsmEnd(self, outputs, inputs, clobbers): self.EmitAsmMapping(outputs, '+r') self.EmitAsmMapping(inputs, 'r') self.EmitClobbers(clobbers) self.PopIndent() self.EmitIndented(');') def EmitComment(self, comment): self.EmitIndented('// ' + comment) def EmitNumericalLabel(self, label): self.EmitIndented('"%d:"' % label) def EmitOp1(self, op, param1): self.PushOp(op) self.EmitIndented('"%s %s\\n"' % (op, param1)) def EmitOp2(self, op, param1, param2): self.PushOp(op) self.EmitIndented('"%s %s, %s\\n"' % (op, param1, param2)) def EmitOp3(self, op, param1, param2, param3): self.PushOp(op) self.EmitIndented('"%s %s, %s, %s\\n"' % (op, param1, param2, param3)) def EmitAdd(self, destination, source, param): self.EmitOp3('add', destination, source, param) def EmitSubs(self, destination, source, param): self.EmitOp3('subs', destination, source, param) def EmitSub(self, destination, source, param): self.EmitOp3('sub', destination, source, param) def EmitMul(self, destination, source, param): self.EmitOp3('mul', destination, source, param) def EmitMov(self, param1, param2): self.EmitOp2('mov', param1, param2) def EmitBeqBack(self, label): self.EmitOp1('beq', '%db' % label) def EmitBeqFront(self, label): self.EmitOp1('beq', '%df' % label) def EmitBneBack(self, label): self.EmitOp1('bne', '%db' % label) def EmitBneFront(self, label): self.EmitOp1('bne', '%df' % label) def EmitVAdd(self, add_type, destination, source_1, source_2): destination, source_1, source_2 = _MakeCompatibleDown(destination, source_1, source_2) self.EmitOp3('add', _AppendType(add_type, destination), _AppendType(add_type, source_1), _AppendType(add_type, source_2)) def EmitVAddw(self, add_type, destination, source_1, source_2): wide_type = _WideType(add_type) destination = _AppendType(wide_type, destination) source_1 = _AppendType(wide_type, source_1) source_2 = _AppendType(add_type, source_2) if _UnsignedType(add_type): self.EmitOp3('uaddw', destination, source_1, source_2) else: self.EmitOp3('saddw', destination, source_1, source_2) def EmitVCvt(self, cvt_to, cvt_from, destination, source): if cvt_to == 'f32' and cvt_from == 's32': self.EmitOp2('scvtf', _AppendType('s32', destination), _AppendType('s32', source)) elif cvt_to == 'f32' and cvt_from == 'u32': self.EmitOp2('ucvtf', _AppendType('u32', destination), _AppendType('u32', source)) else: raise ArgumentError('Convert not supported, to: %s from: %s' % (cvt_to, cvt_from)) def EmitVDup(self, dup_type, destination, source): if (isinstance(source, _GeneralRegister) or isinstance(source, _MappedParameter)): self.EmitOp2('dup', _AppendType(dup_type, destination), _Cast( _TypeBits(dup_type), source)) else: self.EmitOp2('dup', _AppendType(dup_type, destination), _AppendType(dup_type, source)) def EmitVMov(self, mov_type, destination, source): if isinstance(source, _ImmediateConstant): self.EmitOp2('movi', _AppendType(mov_type, destination), source) elif (isinstance(source, _GeneralRegister) or isinstance(source, _MappedParameter)): self.EmitOp2('mov', _AppendType(mov_type, destination), _Cast( _TypeBits(mov_type), source)) else: self.EmitOp2('mov', _AppendType(8, destination), _AppendType(8, source)) def EmitVQmovn(self, mov_type, destination, source): narrow_type = _NarrowType(mov_type) if destination.register_bits * 2 == source.register_bits: self.EmitOp2('sqxtn', _AppendType(narrow_type, destination), _AppendType(mov_type, source)) elif destination.register_bits == source.register_bits: self.EmitOp2('sqxtn', _AppendType(narrow_type, _Cast(destination.register_bits / 2, destination)), _AppendType(mov_type, source)) def EmitVQmovn2(self, mov_type, destination, source_1, source_2): narrow_type = _NarrowType(mov_type) if (destination.register_bits != source_1.register_bits or destination.register_bits != source_2.register_bits): raise ArgumentError('Register sizes do not match.') self.EmitOp2('sqxtn', _AppendType(narrow_type, _Cast(destination.register_bits / 2, destination)), _AppendType(mov_type, source_1)) self.EmitOp2('sqxtn2', _AppendType(narrow_type, destination), _AppendType(mov_type, source_2)) def EmitVQmovun(self, mov_type, destination, source): narrow_type = _NarrowType(mov_type) if destination.register_bits * 2 == source.register_bits: self.EmitOp2('sqxtun', _AppendType(narrow_type, destination), _AppendType(mov_type, source)) elif destination.register_bits == source.register_bits: self.EmitOp2('sqxtun', _AppendType(narrow_type, _Cast(destination.register_bits / 2, destination)), _AppendType(mov_type, source)) def EmitVMul(self, mul_type, destination, source_1, source_2): destination, source_1, source_2 = _MakeCompatibleDown(destination, source_1, source_2) if _FloatType(mul_type): self.EmitOp3('fmul', _AppendType(mul_type, destination), _AppendType(mul_type, source_1), _AppendType(mul_type, source_2)) else: self.EmitOp3('mul', _AppendType(mul_type, destination), _AppendType(mul_type, source_1), _AppendType(mul_type, source_2)) def EmitVMulScalar(self, mul_type, destination, source_1, source_2): self.EmitOp3('mul', _AppendType(mul_type, destination), _AppendType(mul_type, source_1), _AppendType(mul_type, source_2)) def EmitVMull(self, mul_type, destination, source_1, source_2): wide_type = _WideType(mul_type) if _UnsignedType(mul_type): self.EmitOp3('umull', _AppendType(wide_type, destination), _AppendType(mul_type, source_1), _AppendType(mul_type, source_2)) else: self.EmitOp3('smull', _AppendType(wide_type, destination), _AppendType(mul_type, source_1), _AppendType(mul_type, source_2)) def EmitVPadd(self, add_type, destination, source_1, source_2): self.EmitOp3('addp', _AppendType(add_type, destination), _AppendType(add_type, source_1), _AppendType(add_type, source_2)) def EmitVPaddl(self, add_type, destination, source): wide_type = _WideType(add_type) if _UnsignedType(add_type): self.EmitOp2('uaddlp', _AppendType(wide_type, destination), _AppendType(add_type, source)) else: self.EmitOp2('saddlp', _AppendType(wide_type, destination), _AppendType(add_type, source)) def EmitVPadal(self, add_type, destination, source): wide_type = _WideType(add_type) if _UnsignedType(add_type): self.EmitOp2('uadalp', _AppendType(wide_type, destination), _AppendType(add_type, source)) else: self.EmitOp2('sadalp', _AppendType(wide_type, destination), _AppendType(add_type, source)) def EmitVLoad(self, load_no, load_type, destination, source): self.EmitVLoadA(load_no, load_type, [destination], source) def EmitVLoadA(self, load_no, load_type, destinations, source): if source.dereference_increment: increment = sum([_LoadStoreSize(destination) for destination in destinations]) / 8 self.EmitVLoadAPostIncrement(load_no, load_type, destinations, source, self.ImmediateConstant(increment)) else: self.EmitVLoadAPostIncrement(load_no, load_type, destinations, source, None) def EmitVLoadAPostIncrement(self, load_no, load_type, destinations, source, increment): """Generate assembly to load memory to registers and increment source.""" if len(destinations) == 1 and destinations[0].lane is -1: destination = '{%s}' % _AppendType(load_type, destinations[0]) if increment: self.EmitOp3('ld%dr' % load_no, destination, source, increment) else: self.EmitOp2('ld%dr' % load_no, destination, source) return destination_list = _RegisterList(load_type, destinations) if increment: self.EmitOp3('ld%d' % load_no, destination_list, source, increment) else: self.EmitOp2('ld%d' % load_no, destination_list, source) def EmitVLoadAE(self, load_type, elem_count, destinations, source, alignment=None): """Generate assembly to load an array of elements of given size.""" bits_to_load = load_type * elem_count min_bits = min([destination.register_bits for destination in destinations]) max_bits = max([destination.register_bits for destination in destinations]) if min_bits is not max_bits: raise ArgumentError('Cannot mix double and quad loads.') if len(destinations) * min_bits < bits_to_load: raise ArgumentError('To few destinations: %d to load %d bits.' % (len(destinations), bits_to_load)) leftover_loaded = 0 while bits_to_load > 0: if bits_to_load >= 4 * min_bits: self.EmitVLoadA(1, 32, destinations[:4], self.DereferenceIncrement(source, alignment)) bits_to_load -= 4 * min_bits destinations = destinations[4:] elif bits_to_load >= 3 * min_bits: self.EmitVLoadA(1, 32, destinations[:3], self.DereferenceIncrement(source, alignment)) bits_to_load -= 3 * min_bits destinations = destinations[3:] elif bits_to_load >= 2 * min_bits: self.EmitVLoadA(1, 32, destinations[:2], self.DereferenceIncrement(source, alignment)) bits_to_load -= 2 * min_bits destinations = destinations[2:] elif bits_to_load >= min_bits: self.EmitVLoad(1, 32, destinations[0], self.DereferenceIncrement(source, alignment)) bits_to_load -= min_bits destinations = destinations[1:] elif bits_to_load >= 64: self.EmitVLoad(1, 32, _Cast(64, destinations[0]), self.DereferenceIncrement(source)) bits_to_load -= 64 leftover_loaded += 64 elif bits_to_load >= 32: self.EmitVLoad(1, 32, self.Lane(32, destinations[0], leftover_loaded / 32), self.DereferenceIncrement(source)) bits_to_load -= 32 leftover_loaded += 32 elif bits_to_load >= 16: self.EmitVLoad(1, 16, self.Lane(16, destinations[0], leftover_loaded / 16), self.DereferenceIncrement(source)) bits_to_load -= 16 leftover_loaded += 16 elif bits_to_load is 8: self.EmitVLoad(1, 8, self.Lane(8, destinations[0], leftover_loaded / 8), self.DereferenceIncrement(source)) bits_to_load -= 8 leftover_loaded += 8 else: raise ArgumentError('Wrong leftover: %d' % bits_to_load) def EmitVLoadE(self, load_type, count, destination, source, alignment=None): self.EmitVLoadAE(load_type, count, [destination], source, alignment) def EmitVLoadAllLanes(self, load_no, load_type, destination, source): new_destination = destination.Copy() new_destination.lane = -1 new_destination.lane_bits = load_type self.EmitVLoad(load_no, load_type, new_destination, source) def EmitPld(self, load_address_register): self.EmitOp2('prfm', 'pldl1keep', '[%s]' % load_address_register) def EmitPldOffset(self, load_address_register, offset): self.EmitOp2('prfm', 'pldl1keep', '[%s, %s]' % (load_address_register, offset)) def EmitVShl(self, shift_type, destination, source, shift): self.EmitOp3('sshl', _AppendType(shift_type, destination), _AppendType(shift_type, source), _AppendType('i32', shift)) def EmitVStore(self, store_no, store_type, source, destination): self.EmitVStoreA(store_no, store_type, [source], destination) def EmitVStoreA(self, store_no, store_type, sources, destination): if destination.dereference_increment: increment = sum([_LoadStoreSize(source) for source in sources]) / 8 self.EmitVStoreAPostIncrement(store_no, store_type, sources, destination, self.ImmediateConstant(increment)) else: self.EmitVStoreAPostIncrement(store_no, store_type, sources, destination, None) def EmitVStoreAPostIncrement(self, store_no, store_type, sources, destination, increment): source_list = _RegisterList(store_type, sources) if increment: self.EmitOp3('st%d' % store_no, source_list, destination, increment) else: self.EmitOp2('st%d' % store_no, source_list, destination) def EmitVStoreAE(self, store_type, elem_count, sources, destination, alignment=None): """Generate assembly to store an array of elements of given size.""" bits_to_store = store_type * elem_count min_bits = min([source.register_bits for source in sources]) max_bits = max([source.register_bits for source in sources]) if min_bits is not max_bits: raise ArgumentError('Cannot mix double and quad stores.') if len(sources) * min_bits < bits_to_store: raise ArgumentError('To few destinations: %d to store %d bits.' % (len(sources), bits_to_store)) leftover_stored = 0 while bits_to_store > 0: if bits_to_store >= 4 * min_bits: self.EmitVStoreA(1, 32, sources[:4], self.DereferenceIncrement(destination, alignment)) bits_to_store -= 4 * min_bits sources = sources[4:] elif bits_to_store >= 3 * min_bits: self.EmitVStoreA(1, 32, sources[:3], self.DereferenceIncrement(destination, alignment)) bits_to_store -= 3 * min_bits sources = sources[3:] elif bits_to_store >= 2 * min_bits: self.EmitVStoreA(1, 32, sources[:2], self.DereferenceIncrement(destination, alignment)) bits_to_store -= 2 * min_bits sources = sources[2:] elif bits_to_store >= min_bits: self.EmitVStore(1, 32, sources[0], self.DereferenceIncrement(destination, alignment)) bits_to_store -= min_bits sources = sources[1:] elif bits_to_store >= 64: self.EmitVStore(1, 32, _Cast(64, sources[0]), self.DereferenceIncrement(destination, alignment)) bits_to_store -= 64 leftover_stored += 64 elif bits_to_store >= 32: self.EmitVStore(1, 32, self.Lane(32, sources[0], leftover_stored / 32), self.DereferenceIncrement(destination)) bits_to_store -= 32 leftover_stored += 32 elif bits_to_store >= 16: self.EmitVStore(1, 16, self.Lane(16, sources[0], leftover_stored / 16), self.DereferenceIncrement(destination)) bits_to_store -= 16 leftover_stored += 16 elif bits_to_store >= 8: self.EmitVStore(1, 8, self.Lane(8, sources[0], leftover_stored / 8), self.DereferenceIncrement(destination)) bits_to_store -= 8 leftover_stored += 8 else: raise ArgumentError('Wrong leftover: %d' % bits_to_store) def EmitVStoreE(self, store_type, count, source, destination, alignment=None): self.EmitVStoreAE(store_type, count, [source], destination, alignment) def EmitVStoreOffset(self, store_no, store_type, source, destination, offset): self.EmitVStoreOffsetA(store_no, store_type, [source], destination, offset) def EmitVStoreOffsetA(self, store_no, store_type, sources, destination, offset): self.EmitOp3('st%d' % store_no, _RegisterList(store_type, sources), destination, offset) def EmitVStoreOffsetE(self, store_type, count, source, destination, offset): if store_type is not 32: raise ArgumentError('Unsupported store_type: %d' % store_type) if count == 1: self.EmitVStoreOffset(1, 32, self.Lane(32, source, 0), self.Dereference(destination, None), offset) elif count == 2: self.EmitVStoreOffset(1, 32, _Cast(64, source), self.Dereference(destination, None), offset) elif count == 3: self.EmitVStore(1, 32, _Cast(64, source), self.DereferenceIncrement(destination, None)) self.EmitVStoreOffset(1, 32, self.Lane(32, source, 2), self.Dereference(destination, None), offset) self.EmitSub(destination, destination, self.ImmediateConstant(8)) elif count == 4: self.EmitVStoreOffset(1, 32, source, self.Dereference(destination, None), offset) else: raise ArgumentError('To many elements: %d' % count) def EmitVSumReduce(self, reduce_type, elem_count, reduce_count, destinations, sources): """Generate assembly to perform n-fold horizontal sum reduction.""" if reduce_type is not 'u32': raise ArgumentError('Unsupported reduce: %s' % reduce_type) if (elem_count + 3) / 4 > len(destinations): raise ArgumentError('To few destinations: %d (%d needed)' % (len(destinations), (elem_count + 3) / 4)) if elem_count * reduce_count > len(sources) * 4: raise ArgumentError('To few sources: %d' % len(sources)) if reduce_count <= 1: raise ArgumentError('Unsupported reduce_count: %d' % reduce_count) sources = [_Cast(128, source) for source in sources] destinations = [_Cast(128, destination) for destination in destinations] while reduce_count > 1: if len(sources) % 2 == 1: sources.append(sources[-1]) if reduce_count == 2: for i in range(len(destinations)): self.EmitVPadd(reduce_type, destinations[i], sources[2 * i], sources[2 * i + 1]) return else: sources_2 = [] for i in range(len(sources) / 2): self.EmitVPadd(reduce_type, sources[2 * i], sources[2 * i], sources[2 * i + 1]) sources_2.append(sources[2 * i]) reduce_count /= 2 sources = sources_2 def Dereference(self, value, unused_alignment=None): new_value = value.Copy() new_value.dereference = True return new_value def DereferenceIncrement(self, value, alignment=None): new_value = self.Dereference(value, alignment).Copy() new_value.dereference_increment = True return new_value def ImmediateConstant(self, value): return _ImmediateConstant(value) def AllLanes(self, value): return '%s[]' % value def Lane(self, bits, value, lane): new_value = value.Copy() if bits * (lane + 1) > new_value.register_bits: raise ArgumentError('Lane to big: (%d + 1) x %d > %d' % (lane, bits, new_value.register_bits)) new_value.lane = lane new_value.lane_bits = bits return new_value def CreateRegisters(self): return _NeonRegisters64Bit()
{ "repo_name": "shishaochen/TensorFlow-0.8-Win", "path": "third_party/gemmlowp/meta/generators/neon_emitter_64.py", "copies": "5", "size": "33110", "license": "apache-2.0", "hash": 114153941532316770, "line_mean": 34.4496788009, "line_max": 80, "alpha_frac": 0.5894593778, "autogenerated": false, "ratio": 3.5752078609221467, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6664667238722147, "avg_score": null, "num_lines": null }
""" 6502 instructions See for example: http://www.6502.org/tutorials/6502opcodes.html """ from ..isa import Isa from ..encoding import Instruction, Syntax, Operand, Constructor, Relocation from ..token import Token, bit_range isa = Isa() class OpcodeToken(Token): class Info: size = 8 opcode = bit_range(0, 8) class ByteToken(Token): class Info: size = 8 byte = bit_range(0, 8) class WordToken(Token): class Info: size = 16 word = bit_range(0, 16) class Mcs6500Instruction(Instruction): isa = isa @isa.register_relocation class AbsRelocation(Relocation): token = WordToken field = "word" name = "abs16" def calc(self, sym_value, reloc_value): return sym_value class Accumulator(Constructor): # TODO: what is the syntax when the accumulator is intended? syntax = Syntax([]) class Immediate(Constructor): """ Immediate value operand """ imm = Operand("imm", int) syntax = Syntax(["#", imm]) tokens = [ByteToken] patterns = {"byte": imm} class Zeropage(Constructor): imm = Operand("imm", int) syntax = Syntax(["zeropage", imm]) tokens = [ByteToken] patterns = {"byte": imm} class ZeropageX(Constructor): imm = Operand("imm", int) syntax = Syntax(["zeropage", imm, ",", "x"]) tokens = [ByteToken] patterns = {"byte": imm} class ZeropageY(Constructor): imm = Operand("imm", int) syntax = Syntax(["zeropage", imm, ",", "y"]) tokens = [ByteToken] patterns = {"byte": imm} class AbsoluteLabel(Constructor): """ Absolute label """ target = Operand("target", str) syntax = Syntax([target]) tokens = [WordToken] def gen_relocations(self): yield AbsRelocation(self.target) class Absolute(Constructor): """ Absolute 16-bit address """ imm = Operand("imm", int) syntax = Syntax([imm]) tokens = [WordToken] patterns = {"word": imm} class AbsoluteX(Constructor): address = Operand("address", (Absolute, AbsoluteLabel)) syntax = Syntax([address, ",", "x"]) class AbsoluteY(Constructor): address = Operand("address", (Absolute, AbsoluteLabel)) syntax = Syntax([address, ",", "y"]) class IndirectX(Constructor): imm = Operand("imm", int) syntax = Syntax(["(", imm, ",", "x", ")"]) tokens = [ByteToken] patterns = {"byte": imm} class IndirectY(Constructor): imm = Operand("imm", int) syntax = Syntax(["(", imm, ")", ",", "y"]) tokens = [ByteToken] patterns = {"byte": imm} class Relative(Constructor): """ Relative """ target = Operand("target", int) syntax = Syntax([target]) tokens = [ByteToken] patterns = {"byte": target} @isa.register_relocation class RelativeRelocation(Relocation): token = ByteToken field = "byte" name = "rel8" def calc(self, sym_value, reloc_value): return sym_value - (reloc_value + 1) class RelativeLabel(Constructor): """ Relative label """ target = Operand("target", str) syntax = Syntax([target]) tokens = [ByteToken] def gen_relocations(self): yield RelativeRelocation(self.target) class Adc(Mcs6500Instruction): """ Add with carry """ tokens = [OpcodeToken] op = Operand( "op", { Immediate: 0x69, Zeropage: 0x65, ZeropageX: 0x75, Absolute: 0x6D, AbsoluteX: 0x7D, AbsoluteY: 0x79, IndirectX: 0x61, IndirectY: 0x71, }, ) syntax = Syntax(["adc", " ", op]) patterns = {"opcode": op} class And(Mcs6500Instruction): """ Bitwise and """ tokens = [OpcodeToken] op = Operand( "op", { Immediate: 0x29, Zeropage: 0x25, ZeropageX: 0x35, Absolute: 0x2D, AbsoluteX: 0x3D, AbsoluteY: 0x39, IndirectX: 0x21, IndirectY: 0x31, }, ) syntax = Syntax(["and", " ", op]) patterns = {"opcode": op} class Asl(Mcs6500Instruction): """ Arithmatic shift left """ tokens = [OpcodeToken] op = Operand( "op", { Accumulator: 0x0A, Zeropage: 0x06, ZeropageX: 0x16, Absolute: 0x0E, AbsoluteX: 0x1E, }, ) syntax = Syntax(["asl", " ", op]) patterns = {"opcode": op} class Bcc(Mcs6500Instruction): """ Branch if carry clear """ tokens = [OpcodeToken] label = Operand("label", (Relative, RelativeLabel)) syntax = Syntax(["bcc", " ", label]) patterns = {"opcode": 0x90} class Bcs(Mcs6500Instruction): """ Branch if carry set """ tokens = [OpcodeToken] label = Operand("label", (Relative, RelativeLabel)) syntax = Syntax(["bcs", " ", label]) patterns = {"opcode": 0xB0} class Beq(Mcs6500Instruction): """ Branch on equal """ tokens = [OpcodeToken] label = Operand("label", (Relative, RelativeLabel)) syntax = Syntax(["beq", " ", label]) patterns = {"opcode": 0xF0} class Bit(Mcs6500Instruction): """ Test bits """ tokens = [OpcodeToken] op = Operand("op", {Zeropage: 0x24, Absolute: 0x2C}) syntax = Syntax(["bit", " ", op]) patterns = {"opcode": op} class Bmi(Mcs6500Instruction): """ Branch on minus """ tokens = [OpcodeToken] label = Operand("label", (Relative, RelativeLabel)) syntax = Syntax(["bmi", " ", label]) patterns = {"opcode": 0x30} class Bne(Mcs6500Instruction): """ Branch on not equal """ tokens = [OpcodeToken] label = Operand("label", (Relative, RelativeLabel)) syntax = Syntax(["bne", " ", label]) patterns = {"opcode": 0xD0} class Bpl(Mcs6500Instruction): """ Branch on plus """ tokens = [OpcodeToken] label = Operand("label", (Relative, RelativeLabel)) syntax = Syntax(["bpl", " ", label]) patterns = {"opcode": 0x10} class Brk(Mcs6500Instruction): """ Force break """ tokens = [OpcodeToken] syntax = Syntax(["brk"]) patterns = {"opcode": 0} class Clc(Mcs6500Instruction): """ Clear carry flag """ tokens = [OpcodeToken] syntax = Syntax(["clc"]) patterns = {"opcode": 0x18} class Cld(Mcs6500Instruction): """ Clear decimal mode """ tokens = [OpcodeToken] syntax = Syntax(["cld"]) patterns = {"opcode": 0xD8} class Cli(Mcs6500Instruction): """ Clear interrupt disable flag """ tokens = [OpcodeToken] syntax = Syntax(["cli"]) patterns = {"opcode": 0x58} class Clv(Mcs6500Instruction): """ Clear overflow flag """ tokens = [OpcodeToken] syntax = Syntax(["clv"]) patterns = {"opcode": 0xB8} class Cmp(Mcs6500Instruction): """ Compare accumulator """ tokens = [OpcodeToken] op = Operand( "op", { Immediate: 0xC9, Zeropage: 0xC5, ZeropageX: 0xD5, Absolute: 0xCD, AbsoluteX: 0xDD, AbsoluteY: 0xD9, IndirectX: 0xC1, IndirectY: 0xD1, }, ) syntax = Syntax(["cmp", " ", op]) patterns = {"opcode": op} class Cpx(Mcs6500Instruction): """ Compare X register """ tokens = [OpcodeToken] op = Operand("op", {Immediate: 0xE0, Zeropage: 0xE4, Absolute: 0xEC}) syntax = Syntax(["cpx", " ", op]) patterns = {"opcode": op} class Cpy(Mcs6500Instruction): """ Compare Y register """ tokens = [OpcodeToken] op = Operand("op", {Immediate: 0xC0, Zeropage: 0xC4, Absolute: 0xCC}) syntax = Syntax(["cpy", " ", op]) patterns = {"opcode": op} class Dec(Mcs6500Instruction): """ Decrement memory """ tokens = [OpcodeToken] op = Operand( "op", {Zeropage: 0xC6, ZeropageX: 0xD6, Absolute: 0xCE, AbsoluteX: 0xDE}, ) syntax = Syntax(["dec", " ", op]) patterns = {"opcode": op} class Dex(Mcs6500Instruction): """ Decrement index X by 1 """ tokens = [OpcodeToken] syntax = Syntax(["dex"]) patterns = {"opcode": 0xCA} class Dey(Mcs6500Instruction): """ Decrement index Y by 1 """ tokens = [OpcodeToken] syntax = Syntax(["dey"]) patterns = {"opcode": 0x88} class Eor(Mcs6500Instruction): """ Bitwise exclusive or """ tokens = [OpcodeToken] op = Operand( "op", { Immediate: 0x49, Zeropage: 0x45, ZeropageX: 0x55, Absolute: 0x4D, AbsoluteX: 0x5D, AbsoluteY: 0x59, IndirectX: 0x41, IndirectY: 0x51, }, ) syntax = Syntax(["eor", " ", op]) patterns = {"opcode": op} class Inc(Mcs6500Instruction): """ Increment memory """ tokens = [OpcodeToken] op = Operand( "op", {Zeropage: 0xE6, ZeropageX: 0xF6, Absolute: 0xEE, AbsoluteX: 0xFE}, ) syntax = Syntax(["inc", " ", op]) patterns = {"opcode": op} class Inx(Mcs6500Instruction): """ Increment index X by 1 """ tokens = [OpcodeToken] syntax = Syntax(["inx"]) patterns = {"opcode": 0xE8} class Iny(Mcs6500Instruction): """ Increment index Y by 1 """ tokens = [OpcodeToken] syntax = Syntax(["iny"]) patterns = {"opcode": 0xC8} class Jmp(Mcs6500Instruction): """ Jump """ tokens = [OpcodeToken] label = Operand( "label", { Absolute: 0x4C, AbsoluteLabel: 0x4C, # TODO: 6C }, ) syntax = Syntax(["jmp", " ", label]) patterns = {"opcode": label} class Jsr(Mcs6500Instruction): """ Jump to subroutine """ tokens = [OpcodeToken] label = Operand("label", (Absolute, AbsoluteLabel)) syntax = Syntax(["jsr", " ", label]) patterns = {"opcode": 0x20} class Lda(Mcs6500Instruction): """ Load accumulator """ tokens = [OpcodeToken] op = Operand( "op", { Immediate: 0xA9, Zeropage: 0xA5, ZeropageX: 0xB5, Absolute: 0xAD, AbsoluteX: 0xBD, AbsoluteY: 0xB9, IndirectX: 0xA1, IndirectY: 0xB1, }, ) syntax = Syntax(["lda", " ", op]) patterns = {"opcode": op} class Ldx(Mcs6500Instruction): """ Load X register """ tokens = [OpcodeToken] op = Operand( "op", { Immediate: 0xA2, Zeropage: 0xA6, ZeropageY: 0xB6, Absolute: 0xAE, AbsoluteY: 0xBE, }, ) syntax = Syntax(["ldx", " ", op]) patterns = {"opcode": op} class Ldy(Mcs6500Instruction): """ Load Y register """ tokens = [OpcodeToken] op = Operand( "op", { Immediate: 0xA0, Zeropage: 0xA4, ZeropageX: 0xB4, Absolute: 0xAC, AbsoluteX: 0xBC, }, ) syntax = Syntax(["ldy", " ", op]) patterns = {"opcode": op} class Lsr(Mcs6500Instruction): """ Logical shift right """ tokens = [OpcodeToken] op = Operand( "op", { Accumulator: 0x4A, Zeropage: 0x46, ZeropageX: 0x56, Absolute: 0x4E, AbsoluteX: 0x5E, }, ) syntax = Syntax(["lsr", " ", op]) patterns = {"opcode": op} class Ora(Mcs6500Instruction): """ Bitwise or with accumulator """ tokens = [OpcodeToken] op = Operand( "op", { Immediate: 0x09, Zeropage: 0x05, ZeropageX: 0x15, Absolute: 0x0D, AbsoluteX: 0x1D, AbsoluteY: 0x19, IndirectX: 0x01, IndirectY: 0x11, }, ) syntax = Syntax(["ora", " ", op]) patterns = {"opcode": op} class Nop(Mcs6500Instruction): """ No operation """ tokens = [OpcodeToken] syntax = Syntax(["nop"]) patterns = {"opcode": 0xEA} class Pha(Mcs6500Instruction): """ Push accumulator on stack """ tokens = [OpcodeToken] syntax = Syntax(["pha"]) patterns = {"opcode": 0x48} class Php(Mcs6500Instruction): """ Push processor status on stack """ tokens = [OpcodeToken] syntax = Syntax(["php"]) patterns = {"opcode": 0x08} class Pla(Mcs6500Instruction): """ Pull accumulator from stack """ tokens = [OpcodeToken] syntax = Syntax(["pla"]) patterns = {"opcode": 0x68} class Plp(Mcs6500Instruction): """ Pull processor status from stack """ tokens = [OpcodeToken] syntax = Syntax(["plp"]) patterns = {"opcode": 0x28} class Rol(Mcs6500Instruction): """ Rotate left """ tokens = [OpcodeToken] op = Operand( "op", { Accumulator: 0x2A, Zeropage: 0x26, ZeropageX: 0x36, Absolute: 0x2E, AbsoluteX: 0x3E, }, ) syntax = Syntax(["rol", " ", op]) patterns = {"opcode": op} class Ror(Mcs6500Instruction): """ Rotate right """ tokens = [OpcodeToken] op = Operand( "op", { Accumulator: 0x6A, Zeropage: 0x66, ZeropageX: 0x76, Absolute: 0x6E, AbsoluteX: 0x7E, }, ) syntax = Syntax(["ror", " ", op]) patterns = {"opcode": op} class Rti(Mcs6500Instruction): """ Return from interrupt """ tokens = [OpcodeToken] syntax = Syntax(["rti"]) patterns = {"opcode": 0x40} class Rts(Mcs6500Instruction): """ Return from subroutine """ tokens = [OpcodeToken] syntax = Syntax(["rts"]) patterns = {"opcode": 0x60} class Sbc(Mcs6500Instruction): """ Substract with carry """ tokens = [OpcodeToken] op = Operand( "op", { Immediate: 0xE9, Zeropage: 0xE5, ZeropageX: 0xF5, Absolute: 0xED, AbsoluteX: 0xFD, AbsoluteY: 0xF9, IndirectX: 0xE1, IndirectY: 0xF1, }, ) syntax = Syntax(["sbc", " ", op]) patterns = {"opcode": op} class Sec(Mcs6500Instruction): """ Set carry flag """ tokens = [OpcodeToken] syntax = Syntax(["sec"]) patterns = {"opcode": 0x38} class Sed(Mcs6500Instruction): """ Set decimal flag """ tokens = [OpcodeToken] syntax = Syntax(["sed"]) patterns = {"opcode": 0xF8} class Sei(Mcs6500Instruction): """ Set interrupt disable status """ tokens = [OpcodeToken] syntax = Syntax(["sei"]) patterns = {"opcode": 0x78} class Sta(Mcs6500Instruction): """ Store accumulator """ tokens = [OpcodeToken] op = Operand( "op", { Zeropage: 0x85, ZeropageX: 0x95, Absolute: 0x8D, AbsoluteX: 0x9D, AbsoluteY: 0x99, IndirectX: 0x81, IndirectY: 0x91, }, ) syntax = Syntax(["sta", " ", op]) patterns = {"opcode": op} class Stx(Mcs6500Instruction): """ Store X register """ tokens = [OpcodeToken] op = Operand("op", {Zeropage: 0x86, ZeropageY: 0x96, Absolute: 0x8E}) syntax = Syntax(["stx", " ", op]) patterns = {"opcode": op} class Sty(Mcs6500Instruction): """ Store Y register """ tokens = [OpcodeToken] op = Operand("op", {Zeropage: 0x84, ZeropageX: 0x94, Absolute: 0x8C}) syntax = Syntax(["sty", " ", op]) patterns = {"opcode": op} class Tax(Mcs6500Instruction): """ Transfer accumulator to index X """ tokens = [OpcodeToken] syntax = Syntax(["tax"]) patterns = {"opcode": 0xAA} class Tay(Mcs6500Instruction): """ Transfer accumulator to index Y """ tokens = [OpcodeToken] syntax = Syntax(["tay"]) patterns = {"opcode": 0xA8} class Tsx(Mcs6500Instruction): """ Transfer stack pointer to index X """ tokens = [OpcodeToken] syntax = Syntax(["tsx"]) patterns = {"opcode": 0xBA} class Txa(Mcs6500Instruction): """ Transfer index X to accumulator """ tokens = [OpcodeToken] syntax = Syntax(["txa"]) patterns = {"opcode": 0x8A} class Txs(Mcs6500Instruction): """ Transfer index X to stack register """ tokens = [OpcodeToken] syntax = Syntax(["txs"]) patterns = {"opcode": 0x9A} class Tya(Mcs6500Instruction): """ Transfer index Y to accumulator """ tokens = [OpcodeToken] syntax = Syntax(["tya"]) patterns = {"opcode": 0x98} # Pattern matching: @isa.pattern("cnst", "CONSTI8", size=1) def pattern_cnst(context, tree): return Immediate(tree.value) @isa.pattern("a", "REGI8", size=1) def pattern_abs_mem(context, tree): # TODO: use register number? context.emit(Sta(IndirectX(0))) @isa.pattern("cm", "REGI8", size=1) def pattern_tmp_var(context, tree): # TODO: use register number? return IndirectX(0) @isa.pattern("mem", "LABEL", size=2) def pattern_label(context, tree): return AbsoluteLabel(tree.value) @isa.pattern("mem", "FPRELU16", size=1) def pattern_fprel(context, tree): return IndirectX(tree.value.offset) @isa.pattern("cm", "cnst", size=0) def pattern_cm_cnst(context, tree, c0): return c0 @isa.pattern("cm", "mem", size=0) def pattern_cm_mem(context, tree, c0): return c0 # Jumping patterns: @isa.pattern("stm", "JMP", size=4) def pattern_jmp(context, tree): tgt = tree.value context.emit(Jmp(AbsoluteLabel(tgt.name), jumps=[tgt])) @isa.pattern("stm", "CJMPI8(a, mem)", size=4) def pattern_cjmp(context, tree, c0, c1): tgt = tree.value op_map = {">": Bcc, "=": Beq} op = op_map[tree.value] context.emit(Cmp("a", c1)) context.emit(op(AbsoluteLabel(tgt.name), jumps=[tgt])) # Arithmatic patterns: @isa.pattern("a", "ADDI8(a, cm)", size=1) @isa.pattern("a", "ADDU8(a, cm)", size=1) def pattern_add8(context, tree, c0, c1): context.emit(Adc(c1)) return c0 @isa.pattern("a", "SUBI8(a, cm)", size=1) @isa.pattern("a", "SUBU8(a, cm)", size=1) def pattern_sub8(context, tree, c0, c1): context.emit(Sbc(c1)) return c0 @isa.pattern("a", "ANDI8(a, cm)", size=1) @isa.pattern("a", "ANDU8(a, cm)", size=1) def pattern_and8(context, tree, c0, c1): context.emit(And(c1)) return c0 @isa.pattern("a", "ORI8(a, cm)", size=1) @isa.pattern("a", "ORU8(a, cm)", size=1) def pattern_or8(context, tree, c0, c1): context.emit(Ora(c1)) return c0 @isa.pattern("a", "XORI8(a, cm)", size=1) @isa.pattern("a", "XORU8(a, cm)", size=1) def pattern_xor8(context, tree, c0, c1): context.emit(Eor(c1)) return c0 @isa.pattern("a", "cnst", size=1) @isa.pattern("a", "cnst", size=1) def pattern_const8(context, tree, c0): context.emit(Lda(c0)) # Memory transfers: @isa.pattern("a", "LDRI8(mem)", size=2) def pattern_ldr8(context, tree, c0): context.emit(Lda(c0)) @isa.pattern("stm", "STRI8(mem, a)", size=2) def pattern_str8(context, tree, c0, c1): context.emit(Sta(c0)) @isa.pattern("stm", "MOVI8(a)", size=2) def pattern_mov8(context, tree, c0): # TODO! context.emit(Sta(IndirectX(0)))
{ "repo_name": "windelbouwman/ppci-mirror", "path": "ppci/arch/mcs6500/instructions.py", "copies": "1", "size": "18989", "license": "bsd-2-clause", "hash": 6040450708539225000, "line_mean": 20.2881165919, "line_max": 76, "alpha_frac": 0.5635367845, "autogenerated": false, "ratio": 3.3156975729002967, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4379234357400297, "avg_score": null, "num_lines": null }
"""654. Maximum Binary Tree https://leetcode.com/problems/maximum-binary-tree/ Given an integer array with no duplicates. A maximum tree building on this array is defined as follow: The root is the maximum number in the array. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number. The right subtree is the maximum tree constructed from right part subarray divided by the maximum number. Construct the maximum tree by the given array and output the root node of this tree. Example 1: Input: [3,2,1,6,0,5] Output: return the tree root node representing the following tree: ⁠ 6 ⁠ / \ ⁠ 3 5 ⁠ \ / ⁠ 2 0 ⁠ \ ⁠ 1 Note: The size of the given array will be in the range [1,1000]. """ from typing import List from common.tree_node import TreeNode class Solution: def construct_maximum_binary_tree(self, nums: List[int]) -> TreeNode: if not nums: return None max_num = max(nums) max_index = nums.index(max_num) root = TreeNode(max(nums)) root.left = self.construct_maximum_binary_tree(nums[:max_index]) root.right = self.construct_maximum_binary_tree(nums[max_index + 1:]) return root
{ "repo_name": "isudox/leetcode-solution", "path": "python-algorithm/leetcode/maximum_binary_tree.py", "copies": "1", "size": "1262", "license": "mit", "hash": -2037311377261799000, "line_mean": 21.2857142857, "line_max": 77, "alpha_frac": 0.6818910256, "autogenerated": false, "ratio": 3.43801652892562, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46199075545256196, "avg_score": null, "num_lines": null }
"""66. Plus One https://leetcode.com/problems/plus-one/ Given a non-empty array of digits representing a non-negative integer, plus one to the integer. The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit. You may assume the integer does not contain any leading zero, except the number 0 itself. Example 1: Input: [1,2,3] Output: [1,2,4] Explanation: The array represents the integer 123. Example 2: Input: [4,3,2,1] Output: [4,3,2,2] Explanation: The array represents the integer 4321. """ from typing import List class Solution: def plus_one(self, digits: List[int]) -> List[int]: num = 0 for digit in digits: num = num * 10 + digit num += 1 return [int(x) for x in str(num)] def plus_one_2(self, digits: List[int]) -> List[int]: i = len(digits) - 1 gt_ten = True while gt_ten and i >= 0: if i == 0 and digits[i] == 9: digits[i] = 0 digits.insert(0, 1) break digits[i] += 1 if digits[i] >= 10: digits[i] -= 10 else: gt_ten = False i -= 1 return digits
{ "repo_name": "isudox/leetcode-solution", "path": "python-algorithm/leetcode/plus_one.py", "copies": "1", "size": "1277", "license": "mit", "hash": -6169181165776846000, "line_mean": 23.5576923077, "line_max": 76, "alpha_frac": 0.5732184808, "autogenerated": false, "ratio": 3.5373961218836567, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4610614602683657, "avg_score": null, "num_lines": null }
# 66. Puls One # # Given a non-negative number represented as an array of digits, plus one to the number. # # You may assume the integer do not contain any leading zero, except the number 0 itself. # # The digits are stored such that the most significant digit is at the head of the list. # class Solution(object): def plusOne(self, digits): """ :type digits: List[int] :rtype: List[int] """ carry = 1 # another way of traversing list from back # reversed(range(N)) == range(N-1, -1, -1) # e.g.: # In[113]: list(reversed(range(9))) # Out[113]: [8, 7, 6, 5, 4, 3, 2, 1, 0] # # In[114]: list(range(8, -1, -1)) # Out[114]: [8, 7, 6, 5, 4, 3, 2, 1, 0] # for i in reversed(xrange(len(digits))): for i in range(len(digits) - 1, -1, -1): digits[i] += carry carry = digits[i] / 10 # quotient is 1 or 0 digits[i] %= 10 # remainder # msb carry, 1 or 0 if carry: digits = [1] + digits return digits # using extra space def plusOne(self, digits): """ :type digits: List[int] :rtype: List[int] """ carry = 1 n = len(digits) res = [] for i in range(n - 1, -1, -1): digit = (digits[i] + carry) % 10 carry = (digits[i] + carry) / 10 res.insert(0, digit) if carry: res.insert(0, carry) return res if __name__ == "__main__": print Solution().plusOne(digits=[9, 9, 9, 9]) print Solution().plusOne(digits=[9, 9, 9, 2])
{ "repo_name": "gengwg/leetcode", "path": "066_plus_one.py", "copies": "1", "size": "1649", "license": "apache-2.0", "hash": 9188936053089992000, "line_mean": 27.4310344828, "line_max": 89, "alpha_frac": 0.5009096422, "autogenerated": false, "ratio": 3.3448275862068964, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9342852902779448, "avg_score": 0.0005768651254896897, "num_lines": 58 }
# 6.6 递归 from functools import reduce # 递归函数 def recursion(): return recursion() # 阶乘的实现 def factorial(n): result = n for i in range(1, n): result *= i return result print(factorial(5)) # 阶乘的实现(递归版本) def factorial(n): if n == 1: return 1 else: return n * factorial(n-1) # 幂的实现 def power(x, n): result = 1 for i in range(n): result *= x return result # 幂的实现(递归版本) def power(x, n): if n == 0: return 1 else: return x * power(x, n-1) print(power(5, 0)) # 1 print(power(5, 2)) # 25 # 二元查找 # def search(sequence, number, lower=0, upper=None): # if upper is None: # upper = len(sequence) - 1 # if lower == upper: # assert number == sequence[upper] # return upper # else: # middle = (lower + upper) # if number > sequence[middle]: # return search(sequence, number, middle+1, upper) # else: # return search(sequence, number, lower, middle) # # seq = [34, 67, 8, 123, 4, 100, 95] # seq.sort() # print(seq) # search(seq, 34) # --------- 以上注释代码运行有问题。----------- # reduce函数一般来说不能轻松被列表推导式替代,但是通常用不到这个功能。 # 它会将序列的前两个元素与给定的函数联合使用,并且将它们的返回值和第3个元素继续联合使用 # 直到整个序列都处理完毕,并且得到一个最终结果 numbers = [72, 101, 90, 109, 44, 45, 100, 3, 67] print(reduce(lambda x, y: x+y, numbers)) # 631
{ "repo_name": "xiezipei/beginning-python-demo", "path": "demo/func_recur.py", "copies": "1", "size": "1644", "license": "mit", "hash": -8848745177111289000, "line_mean": 18.0704225352, "line_max": 62, "alpha_frac": 0.5649926145, "autogenerated": false, "ratio": 2.1123244929797194, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.31773171074797196, "avg_score": null, "num_lines": null }
''' 67. Add Binary - LeetCode https://leetcode.com/problems/add-binary/description/ ''' # Given two binary strings, return their sum (also a binary string). # For example, # a = "11" # b = "1" # Return "100". class Solution(object): def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ i = 1 m = max(len(a),len(b)) z = 0 res = "" while i < m + 1: x = int(a[len(a)-i]) if i <= len(a) else 0 y = int(b[len(b)-i]) if i <= len(b) else 0 t = x + y + z print x, y, z # debug if t > 1: z = 1 else: z = 0 if t % 2: res = "1" + res else: res = "0" + res i += 1 if z == 1: res = "1" + res return res s = Solution() pairs = [ (("10","1"),"11"), (("111","1"),"1000"), (("101","11"),"1000"), (("1110011","10001"),"10000100") ] for i in pairs: res = s.addBinary(i[0][0],i[0][1]) print res, res == i[1]
{ "repo_name": "heyf/cloaked-octo-adventure", "path": "leetcode/067_add-binary.py", "copies": "1", "size": "1138", "license": "mit", "hash": 6795876896713615000, "line_mean": 20.4905660377, "line_max": 68, "alpha_frac": 0.3892794376, "autogenerated": false, "ratio": 3.17877094972067, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.40680503873206697, "avg_score": null, "num_lines": null }
# 6.9 at page 58 class BigInt(object): def __init__(self, string): if string[0] == "-": self.sign = -1 stop = 1 else: self.sign = 1 stop = 0 self.digits = [] i = len(string) - 1 while i >= stop: self.digits.append(int(string[i])) i -= 1 def multiply(self, number): result = [0]*(len(self.digits)+len(number.digits)) i = 0 while i < len(number.digits): if number.digits[i] != 0: carry = 0 j = 0 while j < len(self.digits) or carry: n_digit = int(result[i+j]) + \ (int(number.digits[i])*int(self.digits[j]) if j < len(self.digits) else 0) + \ carry result[i+j] = n_digit % 10 carry = n_digit / 10 j += 1 i += 1 return BigInt( (["-"] if self.sign == -1 or number.sign == -1 else [])+[str(i) for i in reversed(result)] ) # TODO: add sign support def __str__(self): return "{0}{1}".format( "-" if self.sign == -1 else "", "".join([str(i) for i in reversed(self.digits)]) )
{ "repo_name": "napplebee/algorithms", "path": "epi/bigint.py", "copies": "2", "size": "1306", "license": "mit", "hash": -4871332949125268000, "line_mean": 30.8780487805, "line_max": 108, "alpha_frac": 0.4073506891, "autogenerated": false, "ratio": 3.8753709198813056, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5282721608981306, "avg_score": null, "num_lines": null }
6import pymysql.cursors import urllib2 from multiprocessing.dummy import Pool as ThreadPool import threading import time from itertools import izip_longest #GLOBAL VARIABLE DECLARATIONS count = 1 #"Collect data into fixed-length chunks or blocks" # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx def grouper(n, iterable, fillvalue=None): args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args) #Function used for converting text data into relational database record and feeding it to the database def converter(file_name): flag = False data_list = [] with countLock: global count local_count = count count += 2000 db = pymysql.connect(host="localhost", user="root", passwd="mysql123", db="foodreviewdataset", cursorclass=pymysql.cursors.DictCursor) with open(file_name,'r') as input_file: for word in input_file: if word != '\n': flag = False word = word.rstrip('\n') line = word.split(":") data_list.append(line[1]) else: print "\n", local_count if flag: continue flag = True try: with db.cursor() as cursor: sql = "INSERT INTO `foods` (`sno`,`productID`,`userID`,`profileName`,`helpfulnes`,`reviewscore`,`time`,`summary`,`text`) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)" cursor.execute(sql,(local_count,data_list[0],data_list[1],data_list[2],data_list[3],data_list[4],data_list[5],data_list[6],data_list[7])) db.commit() finally: print "Data feeded" data_list = [] local_count += 1 db.close() n = 18000 fileList = [] with open('sample3.txt','r') as f: for i, g in enumerate(grouper(n, f, fillvalue=''), 1): fileList.append('small_file_{0}.txt'.format(i * n)) with open('small_file_{0}.txt'.format(i * n), 'w') as fout: fout.writelines(g) startTime = time.time() countLock = threading.Lock() pool = ThreadPool(25) results = pool.map(converter,fileList) print "Time taken for feeding of data into database is ",time.time() - startTime," seconds"
{ "repo_name": "Roncool13/generic-python-scripts", "path": "database_feeder.py", "copies": "1", "size": "2371", "license": "mit", "hash": 2368909262698072000, "line_mean": 33.3623188406, "line_max": 181, "alpha_frac": 0.562210038, "autogenerated": false, "ratio": 3.8057784911717496, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9824722175198175, "avg_score": 0.008653270794714755, "num_lines": 69 }
# 6. In video 28. Update, it was suggested that some of the duplicate code in # lookup and update could be avoided by a better design. We can do this by # defining a procedure that finds the entry corresponding to a given key, and # using that in both lookup and update. # Here are the original procedures: def hashtable_update(htable, key, value): bucket, entry = get_hashtable_entry(htable, key) if entry: entry[1] = value else: bucket.append([key, value]) def get_hashtable_entry(htable, key): bucket = hashtable_get_bucket(htable, key) for entry in bucket: if entry[0] == key: return bucket, entry return bucket, None def hashtable_lookup(htable, key): bucket, entry = get_hashtable_entry(htable, key) if entry: return entry[1] return None def make_hashtable(size): table = [] for unused in range(0, size): table.append([]) return table def hash_string(s, size): h = 0 for c in s: h = h + ord(c) return h % size def hashtable_get_bucket(htable, key): return htable[hash_string(key, len(htable))] # Whenever we have duplicate code like the loop that finds the entry in # hashtable_update and hashtable_lookup, we should think if there is a better way # to write this that would avoid the duplication. We should be able to rewrite # these procedures to be shorter by defining a new procedure and rewriting both # hashtable_update and hashtable_lookup to use that procedure. # Modify the code for both hashtable_update and hashtable_lookup to have the same # behavior they have now, but using fewer lines of code in each procedure. You # should define a new procedure to help with this. Your new version should have # approximately the same running time as the original version, but neither # hashtable_update or hashtable_lookup should include any for or while loop, and # the block of each procedure should be no more than 6 lines long. # Your procedures should have the same behavior as the originals. For example, table = make_hashtable(10) hashtable_update(table, 'Python', 'Monty') hashtable_update(table, 'CLU', 'Barbara Liskov') hashtable_update(table, 'JavaScript', 'Brendan Eich') hashtable_update(table, 'Python', 'Guido van Rossum') print hashtable_lookup(table, 'Python') #>>> Guido van Rossum
{ "repo_name": "ezralalonde/cloaked-octo-sansa", "path": "05/hw/04.py", "copies": "1", "size": "2352", "license": "bsd-2-clause", "hash": -3091464502252838400, "line_mean": 35.1846153846, "line_max": 81, "alpha_frac": 0.7142857143, "autogenerated": false, "ratio": 3.4844444444444442, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4698730158744444, "avg_score": null, "num_lines": null }
''' 6-mean_sl.py ========================= AIM: Compute the mean of the stray light in the sense of: - Mean across all points then every minutes - Mean of max value - Mean of direction of maximum (in the orbit) INPUT: files: - <orbit_id>_misc/orbits.dat - <orbit_id>_flux/flux_*.dat variables: see section PARAMETERS (below) OUTPUT: in <orbit_id>_misc/ : stat files CMD: python 6-mean_sl.py ISSUES: <none known> REQUIRES:- standard python libraries, specific libraries in resources/ - Structure of the root folder: * <orbit_id>_flux/ --> flux files * <orbit_id>_figures/ --> figures * <orbit_id>_misc/ --> storages of data * all_figures/ --> comparison figures REMARKS: <none> ''' ########################################################################### ### INCLUDES import numpy as np from resources.routines import * from resources.TimeStepping import * ########################################################################### ### PARAMETERS # Orbit id orbit_id = 1001 ########################################################################### ### INITIALISATION # File name fot the computed orbit file orbits_file = 'orbits.dat' index_file = 'index.dat' # Formatted folders definitions folder_flux, folder_figures, folder_misc = init_folders(orbit_id) ########################################################################### ### Load which orbits were computed start = time.time() orbits = np.loadtxt(folder_misc+orbits_file,dtype='i4') data = np.zeros([np.shape(orbits)[0]-1,6]) mean = np.zeros([np.shape(orbits)[0],2]) mean_max = np.zeros([np.shape(orbits)[0],2]) mean_maxdir = np.zeros([np.shape(orbits)[0],2]) previous_part = -1 for ii, orbit_current in enumerate(orbits[:,0]): # print orbit, orbits[ii+1] t_ini, t_end, a_ini, a_end = orbit2times(orbit_current,orbit_id) mean_orbit = 0 mean_max_orbit = 0 mean_maxdir_orbit = 0 nb_points = 0 sl_max = 0.0 t_ini = np.ceil(t_ini) # not sure it's useful. minute = t_ini ########################################################################### # Iterate on every time. while (minute <= t_end): # initialise the array for the current minute (ie. make sure nothing is left in the table from last time step. try: # Try to load the fluxes for a given minute (minute goes from 0 to period whereas a_ini is the absolute time from 0:0:0.0 1/1/2018 in min ra, dec, S_sl = load_flux_file(int(minute+a_ini), 'flux_', folder=folder_flux) except IOError: # If not found it means that the satellite is (propably) over the SAA. Skip this step. minute +=1 continue mean_orbit += np.mean(S_sl) mean_max_orbit += np.amax(S_sl) if (sl_max < np.amax(S_sl)): sl_max = np.amax(S_sl) index_max = S_sl.argmax() nb_points += 1 minute += 1 mean[ii] = orbit_current, mean_orbit/nb_points mean_max[ii] = orbit_current, mean_max_orbit/(float(t_end)-float(t_ini)) minute = t_ini # second run to get max in axe skipped_minute = 0 while (minute <= t_end): # initialise the array for the current minute (ie. make sure nothing is left in the table from last time step. try: # Try to load the fluxes for a given minute (minute goes from 0 to period whereas a_ini is the absolute time from 0:0:0.0 1/1/2018 in min ra, dec, S_sl = load_flux_file(int(minute+a_ini), 'flux_', folder=folder_flux) except IOError: # If not found it means that the satellite is (propably) over the SAA. Skip this step. minute +=1 continue try: mean_maxdir_orbit += S_sl[index_max] except : skipped_minute += 1 minute += 1 mean_maxdir[ii] = orbit_current, mean_maxdir_orbit/(float(t_end)-float(t_ini)-skipped_minute) #TODO: take direction of max flux for this orbit print orbit_current header = 'orbit,mean' fname = 'mean_sl.dat' np.savetxt(folder_misc+fname,mean,header=header, fmt='%4d,%g') header = 'orbit,mean_max' fname = 'mean_max_sl.dat' np.savetxt(folder_misc+fname,mean_max,header=header, fmt='%4d,%g') header = 'orbit,mean_maxdir' fname = 'mean_maxdir_sl.dat' np.savetxt(folder_misc+fname,mean_maxdir,header=header, fmt='%4d,%g') end = time.time() elapsed_time = round((end-start)/60.,1) print 'Done. Time needed : %3.1f minutes,' % elapsed_time
{ "repo_name": "kuntzer/SALSA-public", "path": "6_mean_sl.py", "copies": "1", "size": "4202", "license": "bsd-3-clause", "hash": 5394654132008850000, "line_mean": 30.1259259259, "line_max": 139, "alpha_frac": 0.6204188482, "autogenerated": false, "ratio": 3.0208483105679367, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9006683158070954, "avg_score": 0.026916800139396554, "num_lines": 135 }
#6. Pyramid (PSO) #Consider n cubes of known sides length s[i] and colors c[i] . Assemble the highest #pyramid from the cubes in such a way that it has 'stability' (there is not a bigger cube #over a smaller one) and there are not two consecutive cubes of the same color. from random import random, randint, shuffle from copy import deepcopy from math import exp import numpy as np W = 0.5 C1 = 0.5 C2 = 1.5 def s(v): return 1 / (1 + exp(-v)) class Particle: global W, c1, c2 def __init__(self, n): self.n = n self.permutation = range(n) shuffle(self.permutation) self.velocity = [random() for _ in range(n)] self.fitness = 0 self.bestPermutation = deepcopy(self.permutation) self.bestFitness = 0 self.w = W def evaluate(self, problem): self.fitness = 1 for i in range(1, self.n): if problem.s[self.permutation[i - 1]] > problem.s[self.permutation[i]] and \ problem.c[self.permutation[i - 1]] == problem.c[self.permutation[i]]: self.fitness += 1 else: break if self.fitness > self.bestFitness: self.bestFitness = self.fitness self.bestPermutation = deepcopy(self.permutation) def update(self, particle, t): global W, C1, C2 for i in range(self.n): if random() < s(self.velocity[i]): this = self.permutation[i] other = particle.permutation[i] for j in range(self.n): if self.permutation[j] == other: (self.permutation[i], self.permutation[j]) = (self.permutation[j], self.permutation[i]) self.velocity[i] = self.w * self.velocity[i] + \ C1 * random() * (particle.bestPermutation[i] - self.permutation[i]) + \ C2 * random() * (self.bestPermutation[i] - self.permutation[i]) self.w = W / (t + 1) class Swarm: def __init__(self, swarmSize, n): self.v = [Particle(n) for _ in range(swarmSize)] self.n = swarmSize def getBestNeighbour(self, particle): return self.getBestParticles(1)[0]; def getBestParticles(self, k): self.v.sort(key = lambda part: part.bestFitness) return self.v[-k:] class Controller: def __init__(self, problem): self.problem = problem self.params = {} self.loadParameteres() def iteration(self): for i in range(self.params["swarmSize"]): current = self.swarm.v[i] p = self.swarm.getBestNeighbour(current) current.update(p, i) current.evaluate(self.problem) def showStat(self): fitness = [] bestRuns = [] for run in range(self.params["runs"]): print("Running %d" % (run + 1)) bestRuns.append(self.runAlg(self.params["bestSize"])) runsBestParticles = map(lambda v: max(v, key = lambda s : s.bestFitness), bestRuns) runsBestFitness = [p.bestFitness for p in runsBestParticles] print("stddev: " + str(np.std(runsBestFitness))) print("mean: " + str(np.mean(runsBestFitness))) print("maxi: " + str(max(runsBestFitness))) def runAlg(self, topK): self.swarm = Swarm(self.params["swarmSize"], self.problem.n) for i in range(self.params["iterations"]): self.iteration() return self.swarm.getBestParticles(topK) def loadParameteres(self): try: f = open("params.in", "r") for x in filter(None, f.read().split('\n')): (param, value) = x.split(' =') value = int(value) self.params[param] = value except Excepiton as e: print("Exception Controller::loadParameters(fileName): " + str(e)) class Problem: def __init__(self, fileName): self.s = [] self.c = [] self.fileName = fileName self.loadProblem(fileName) def loadProblem(self, fileName): try : f = open(fileName, "r") self.n = int(f.readline()) for line in filter(None, f.read().split('\n')): (x, y) = line.split(' ') self.s.append(x) self.c.append(y) except Exception as e: print("Exception Problem::loadProblem(fileName): " + str(e)) p = Problem("data02.in") ctrl = Controller(p) ctrl.showStat() #for part in ctrl.runAlg(10): # print(str(part.bestFitness) + " " + str(part.bestPermutation))
{ "repo_name": "rusucosmin/courses", "path": "ubb/ai/lab4.py", "copies": "1", "size": "4616", "license": "mit", "hash": -8584106011782966000, "line_mean": 33.9696969697, "line_max": 111, "alpha_frac": 0.5608752166, "autogenerated": false, "ratio": 3.6034348165495707, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9594921796601078, "avg_score": 0.013877647309698454, "num_lines": 132 }
# 6. ts/all_species # Get all species that belong to a particular Taxon. import sys, unittest, json sys.path.append('./') sys.path.append('../') import webapp service = webapp.get_service(5004, 'ts/all_species') class TestTsAllSpecies(webapp.WebappTestCase): @classmethod def get_service(self): return service def test_no_parameter(self): request = service.get_request('GET', {}) x = self.start_request_tests(request) self.assertTrue(x.status_code >= 400) self.assertTrue(u'taxon' in x.json()[u'message'], #informative? 'no "taxon" in "%s"' % x.json()[u'message']) def test_bad_name(self): request = service.get_request('GET', {u'taxon': u'Nosuchtaxonia'}) x = self.start_request_tests(request) m = x.json().get(u'message') self.assertTrue(x.status_code >= 400, '%s: %s' % (x.status_code, m)) self.assertTrue(u'No ' in m, #informative? '%no "No" in "%s"' % x.status_code) # TBD: maybe try a very long name? def taxon_tester(self, name): request = service.get_request('GET', {u'taxon': name}) x = self.start_request_tests(request) self.assert_success(x, name) print '%s: %s %s' % (name, len(x.json()[u'species']), x.time) # Found this taxon lineage sequence using the 'lineage' script in # opentreeoflife/reference-taxonomy/bin def test_nested_sequence(self): """Try progressively larger taxa to see when the service breaks.""" self.taxon_tester('Apis mellifera') self.taxon_tester('Apis') self.taxon_tester('Apini') self.taxon_tester('Apinae') # Apidae at 5680 species is a struggle self.taxon_tester('Apidae') if False: # Apoidea: 19566 takes 223 seconds # Doc says "maximum taxonomic rank allowed: family" so why did it work at all? # Doc says "depending on rank" which isn't right, it depends on # the number of species in the taxon. TBD: note it. self.taxon_tester('Apoidea') # Aculeata fails after 339 seconds self.taxon_tester('Aculeata') self.taxon_tester('Apocrita') self.taxon_tester('Hymenoptera') self.taxon_tester('Endopterygota') self.taxon_tester('Neoptera') self.taxon_tester('Pterygota') self.taxon_tester('Dicondylia') self.taxon_tester('Insecta') self.taxon_tester('Hexapoda') self.taxon_tester('Pancrustacea') self.taxon_tester('Mandibulata') self.taxon_tester('Arthropoda') self.taxon_tester('Panarthropoda') self.taxon_tester('Ecdysozoa') self.taxon_tester('Protostomia') self.taxon_tester('Bilateria') self.taxon_tester('Eumetazoa') self.taxon_tester('Metazoa') self.taxon_tester('Holozoa') self.taxon_tester('Opisthokonta') self.taxon_tester('Eukaryota') @unittest.skip("takes too long") def test_big_family(self): """The documentation suggests that you can use the service on families. So try it on a big family (>60,000 species) to what happens. As of 2017-11-05, this fails after crunching for 22 minutes - returns with a non-200 status code.""" self.taxon_tester('Staphylinidae') # Insert here: edge case tests # Insert here: inputs out of range, leading to error or long delay # Insert here: error-generating conditions # (See ../README.md) def test_example_15(self): x = self.start_request_tests(example_15) self.assert_success(x) # Insert: whether result is what it should be according to docs def test_example_16(self): x = self.start_request_tests(example_16) self.assert_success(x) # Insert: whether result is what it should be according to docs null=None; false=False; true=True example_15 = service.get_request('GET', {u'taxon': u'Vulpes'}) example_16 = service.get_request('GET', {u'taxon': u'Canidae'}) if __name__ == '__main__': webapp.main()
{ "repo_name": "jar398/tryphy", "path": "tests/test_ts_all_species.py", "copies": "1", "size": "4216", "license": "bsd-2-clause", "hash": -2218218349133219000, "line_mean": 37.3272727273, "line_max": 90, "alpha_frac": 0.6069734345, "autogenerated": false, "ratio": 3.411003236245955, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9500239867002411, "avg_score": 0.003547360748708785, "num_lines": 110 }
6#!/usr/bin/python # -*- coding: utf-8; -*- # # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import math def derive(zero=0.0, minimum=0.0): def f(y1, y0, x1, x0): if (math.isnan(y0)): return(y1/float(x1)) dx = float(x1 - x0) if (dx == 0.0): return(zero) else: return(max(minimum, (y1-y0) / dx)) return(f) def fst(pair): return(pair[0]) def snd(pair): return(pair[1]) def uncurry(f): def g(args, **kwargs): return(f(*args, **kwargs)) g.__name__ = f.__name__ return(g) def percentage(state1, state0): result = [] xs1 = sum(state1) xs0 = sum(state0) return(map(lambda (y1,y0): derive()(y1, y0, xs1, xs0), zip(state1, state0)))
{ "repo_name": "locaweb/leela-client", "path": "src/python/leela/client/functions.py", "copies": "1", "size": "1299", "license": "apache-2.0", "hash": 759752589505456800, "line_mean": 26.6382978723, "line_max": 80, "alpha_frac": 0.6127790608, "autogenerated": false, "ratio": 3.13768115942029, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9200572708395022, "avg_score": 0.00997750236505369, "num_lines": 47 }
"""6. ZigZag Conversion The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows: string convert(string text, int nRows); convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". """ class Solution(object): def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ if numRows == 1: return s num_per_zigzag = numRows * 2 - 2 num_per_zigzag_fullblock = numRows * 2 zigzag_num, rem = divmod(len(s), num_per_zigzag) if rem > 0: # `math.ceil` on leetcode does not return int? zigzag_num += 1 result = bytearray(num_per_zigzag_fullblock * zigzag_num) for i, c in enumerate(s): block_idx, offset = divmod(i, num_per_zigzag) row = numRows - 1 - abs(offset - numRows + 1) col = 0 if offset < numRows else 1 result[row * zigzag_num * 2 + block_idx * 2 + col] = ord(c) return ''.join(chr(b) for b in result if b)
{ "repo_name": "nadesico19/nadepy", "path": "leetcode/algo_6_zigzag_conversion.py", "copies": "1", "size": "1348", "license": "mit", "hash": -3848648996385796600, "line_mean": 31.65, "line_max": 95, "alpha_frac": 0.5832095097, "autogenerated": false, "ratio": 3.15962441314554, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9240140768669702, "avg_score": 0.0005386308351673809, "num_lines": 40 }
# 70600674 import euler s = """ 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 """ s = s.split() grid = [s[i*20:i*20+20] for i in xrange(20)] for i in xrange(20): grid[i] = [int(v, 10) for v in grid[i]] m = 0 for r in xrange(20): for c in xrange(20): if c < 20 - 3: v = grid[r][c:c+4] t = euler.product(v) if t > m: m = t if r < 20 - 3: v = [grid[r + i][c] for i in xrange(4)] t = euler.product(v) if t > m: m = t if r < 20 - 3 and c < 20 - 3: v = [grid[r + i][c + i] for i in xrange(4)] t = euler.product(v) if t > m: m = t v = [grid[r + 3 - i][c + i] for i in xrange(4)] t = euler.product(v) if t > m: m = t print m
{ "repo_name": "higgsd/euler", "path": "py/11.py", "copies": "1", "size": "2013", "license": "bsd-2-clause", "hash": -1584624586775569000, "line_mean": 36.9811320755, "line_max": 59, "alpha_frac": 0.5494287134, "autogenerated": false, "ratio": 2.8553191489361702, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.390474786233617, "avg_score": null, "num_lines": null }
# 7.1.2015 # Builtins import os, sys # from armchair biology blog (now implemented in biopython) from KGML_parser import read from KGML_vis import KGMLCanvas from KGML_scrape import retrieve_kgml_to_file, retrieve_KEGG_pathway import argparse import pandas as pd ############################ psr = argparse.ArgumentParser(description="Color KEGG maps with the Kegg Orthology entries that exist in your annotated transcriptome. Optional: color up/down-regulated genes red/blue") # kegg pathway name psr.add_argument('--path',help='Kegg Pathway Name', dest="path") # folder for map output psr.add_argument('--output',help='name of output folder', default = './', dest="outDir") # transcriptome KO (for just presence/absence) psr.add_argument('--transcriptomeKO', help='Transcriptome Kegg Orthology', dest='transKO') # upregulated KO psr.add_argument('--upReg', help='OPTIONAL: upregulated KO', nargs='?', default=None, dest= 'upKO') # downregulated KO psr.add_argument('--downReg', help='OPTIONAL: downregulated KO', nargs='?', default=None, dest= 'downKO') ############################## args = psr.parse_args() ############################## if not os.path.exists(args.outDir): os.makedirs(args.outDir) pathway = retrieve_KEGG_pathway(args.path) #pathway of interest def readKOFile(koFile, keggPath): pd_annot_table = pd.io.parsers.read_table(koFile, header=0, sep='\t') koList = pd_annot_table['Kegg_Orthology'] koList = ['ko:' + s for s in koList] # import pdb; pdb.set_trace() ''' with open(koFile, 'r') as koF: for line in koF: path = 'ko:' + line.rstrip() koList.append(path) koF.close() ''' entryList = [e for e in keggPath.entries.values() if len(set(e.name.split()).intersection(koList))] return set(entryList) def colorMapItems(geneSet, color, width): for e in geneSet: for g in e.graphics: if g.type == 'line': g.fgcolor = color g.width = width g.bgcolor = color #main knownKOSet = readKOFile(args.transKO, pathway) enhanceSet = knownKOSet if args.upKO != None: upKOSet = readKOFile(args.upKO, pathway) enhanceSet.update(upKOSet) if args.downKO != None: downKOSet = readKOFile(args.downKO, pathway) enhanceSet.update(downKOSet) notDE = set([e for e in pathway.orthologs if not len(set(e.name.split()).intersection(enhanceSet))]) #non_de_list = [e for e in pathway.entries.values() if not len(set(e.name.split()).intersection(enhanceSet)) and e.type != 'map'] #notDE = set(non_de_list) kgml_map = KGMLCanvas(pathway, show_maps=True) kgml_map.import_imagemap = True # turn this off to allow all elements to go gray! kgml_map.show_maps = False kgml_map.show_orthologs = False kgml_map.draw_relations = False kgml_map.show_compounds = False kgml_map.show_genes = False os.chdir(args.outDir) colorMapItems(notDE,'#D3D3D3', 1) colorMapItems(knownKOSet,'#666666', 10) koInMap = open(args.path + '_KO.txt', 'w') for k in knownKOSet: koInMap.write(k.name + '\t' + 'present' + '\n') if args.upKO != None: colorMapItems(upKOSet,'#FF0000', 10) for k in upKOSet: koInMap.write(k.name + '\t' + 'upregulated' + '\n') if args.downKO != None: colorMapItems(downKOSet,'#0000FF', 10) for k in downKOSet: koInMap.write(k.name + '\t' + 'downregulated' + '\n') koInMap.close() # And rendering elements as an overlay kgml_map.show_compounds = True kgml_map.show_genes = True kgml_map.show_orthologs = True #kgml_map.draw_relations = True kgml_map.draw(args.path + '.pdf')
{ "repo_name": "bluegenes/MakeMyTranscriptome", "path": "scripts/util/color_pathways2.py", "copies": "1", "size": "3579", "license": "bsd-3-clause", "hash": 7207384914111157000, "line_mean": 33.0857142857, "line_max": 185, "alpha_frac": 0.6677842973, "autogenerated": false, "ratio": 2.9481054365733113, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.41158897338733114, "avg_score": null, "num_lines": null }
# 7.1 class Node(object): nxt = None value = None def __init__(self, value, n=None): self.nxt = n self.value = value def merge(head1, head2): if head1.value < head2.value: result = head1 current = result head1 = head1.nxt else: result = head2 current = result head2 = head2.nxt while head1 is not None or head2 is not None: if head2 is None: current.nxt = head1 head1 = head1.nxt elif head1 is None: current.nxt = head2 head2 = head2.nxt elif head1.value > head2.value: current.nxt = head2 head2 = head2.nxt else: current.nxt = head1 head1 = head1.nxt current = current.nxt return result def test(): head1 = Node(1, Node(2, Node(4, Node(9, Node(10))))) head2 = Node(3, Node(5, Node(8))) merged = merge(head1, head2) result = "" while merged is not None: result = "{0}({1})->".format(result, merged.value) merged = merged.nxt print result
{ "repo_name": "napplebee/algorithms", "path": "epi/merge_linked.py", "copies": "2", "size": "1117", "license": "mit", "hash": 5061932790640456000, "line_mean": 20.9019607843, "line_max": 58, "alpha_frac": 0.5264100269, "autogenerated": false, "ratio": 3.4159021406727827, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9942312167572782, "avg_score": 0, "num_lines": 51 }
#71 编写input()和output()函数输入,输出5个学生的数据记录 student = [] def input_stu(stu, num): for i in range(5): stu.append(['', '', []]) for i in range(num): stu[i][0] = input('input the num:\n') stu[i][1] = input('input the name:\n') for j in range(2): stu[i][2].append(int(input('input the score:\n'))) def output_stu(stu): for i in range(len(stu)): print('%-6s%-10s' % (stu[i][0], stu[i][1])) for j in range(len(stu[i][2])): print('%-8d' % stu[i][2][j]) #input_stu(student, 3) #output_stu(student) #72 创建一个链表 def create_link(): pLink = [] for i in range(20): pLink.append(i) print('this is the pLink', pLink) #create_link() #73 题目:反向输出一个链表。 def create_reverse_link(): pLink = [] for i in range(20): pLink.append(i) pLink.reverse() print('this is the pLink to reverse print: ', pLink) #create_reverse_link() #74. 题目:列表排序及连接。 def sorted_and_linked(): head = [1,3,2,5,9,110,67] tail = [111,45,89] head.sort() print('this is sorted the head: ', head) #head + tail 也可以 head.extend(tail) print('this is to extend the head and tail :', head) #sorted_and_linked() #75. 放松一下,算一道简单的题目 # 简单的判断题不想写 #76. 题目:编写一个函数,输入n为偶数时,调用函数求1/2+1/4+...+1/n,当输入n为奇数时,调用函数1/1+1/3+...+1/n def sum_num(n): x = 0 if n % 2 == 0: x = 2 else: x = 1 sum_x = 0 for i in range(x, n+1, 2): sum_x += 1/i print('this is the sum_x: %f ' % sum_x) sum_num(6) #77. 题目:循环输出列表 def rotation_list(): ary = [1, 2, 4, 5, 3] for value in enumerate(ary): print('this is the key: %d , value: %d' %(value[0], value[1])) rotation_list() #78 题目:找到年龄最大的人,并输出。请找出程序中有什么问题。 def find_max_age(): persons = {"a": 18, "b": 20, "c": 34} max_person = "" for x in persons.keys(): if max_person == '': max_person = x if persons[x] > persons[max_person]: max_person = x print("this is the max person %s and age is %d " % (max_person, persons[max_person]) ) find_max_age() #79 题目:字符串排序。 def sort_str(str1, str2): if str1 < str2: return str1, str2 else: return str2, str1 print(sort_str('b', 'a')) #80 题目:海滩上有一堆桃子,五只猴子来分。第一只猴子把这堆桃子平均分为五份,多了一个, # 这只猴子把多的一个扔入海中,拿走了一份。 # 第二只猴子把剩下的桃子又平均分成五份,又多了一个,它同样把多的一个扔入海中,拿走了一份, # 第三、第四、第五只猴子都是这样做的,问海滩上原来最少有多少个桃子? def distribution_things(n, x): if x == 0: return n n = n * 5 + 1 x = x-1 return distribution_things(n, x) print(distribution_things(1, 5))
{ "repo_name": "cwenao/python_web_learn", "path": "base100/base100/base_71-80.py", "copies": "1", "size": "3186", "license": "apache-2.0", "hash": -7421515881557432000, "line_mean": 14.6047904192, "line_max": 90, "alpha_frac": 0.5510360706, "autogenerated": false, "ratio": 1.9757391963608795, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7952667389062954, "avg_score": 0.014821575579585092, "num_lines": 167 }
#720->144->720 import tensorflow as tf from PIL import Image import numpy as np import os.path import random name = 'SCV-CNN-Batch-Re' lr=1e-4 #learning rate ratio = 4/3 H1=144 W1=int(H1*ratio) H15=360 W15=int(H15*ratio) H2=720 W2=int(H2*ratio) path="../Data/" pref2="720p/" suff2=".jpg" train_num=3000000#1000 file_num=24600 batch_num=3 logDir = 'Logs/'+name def weight_variable(shape, name): initial = tf.truncated_normal(shape, stddev=0.01, name="dummy") return tf.Variable(initial, name=name) def bias_variable(shape, name): initial = 0. return tf.Variable(initial, name=name) def getimage(idx): img_2=Image.open(path+pref2+str(idx).zfill(5)+suff2) array_2=np.array(img_2)[:, :, 0:3] array_2=array_2.astype(np.float32) return array_2 def l_relu(x, alpha=0., name="leaky_relu"): with tf.name_scope(name): return tf.nn.relu(x)-alpha*tf.nn.relu(-x) def asImage(tensor): result=tensor[0].astype(np.uint8) return Image.fromarray(result,'RGB') def showres(index, steps): test720 = getimage(index) A=sess.run(y_result, feed_dict={y_image:[test720]}) for x in np.nditer(A, op_flags=['readwrite']): if x>255. : x[...]=255. result = A.astype(np.uint8) asImage(result).save(logDir+'/results/result_'+str(steps).zfill(6)+'__'+str(index).zfill(4)+'.jpg') def conv2d(x, W, B, stride, name="conv_layer"): with tf.name_scope(name): return tf.nn.conv2d(x, W, strides=[1, stride, stride, 1], padding='SAME')+B def saveCost(): fcost=open(logDir+"/cost.txt",'a') ShowCost=sess.run(cost, feed_dict=f_dict) string="step %03d: %f\n" %(steps,ShowCost) fcost.write(string) fcost.close() y_image=tf.placeholder(np.float32,shape=[None,H2,W2,3],name="answer_720_image") weight1 = weight_variable([40, 40, 3, 100], name = 'weight1') bias1 = bias_variable([100], name = 'bias1') weight2 = weight_variable([1, 1, 100, 50], name = 'weight2') bias2 = bias_variable([50], name='bias2') weight3 = weight_variable([10, 10, 50, 3], name = 'weight3') bias3 = bias_variable([3], name = 'bias3') weight4 = weight_variable([40, 40, 3, 100], name = 'weight4') bias4 = bias_variable([100], name = 'bias4') weight5 = weight_variable([1, 1, 100, 50], name = 'weight5') bias5 = bias_variable([50], name='bias5') weight6 = weight_variable([11, 11, 50, 3], name = 'weight6') bias6 = bias_variable([3], name = 'bias6') weight7 = weight_variable([40, 40, 3, 100], name = 'weight7') bias7 = bias_variable([100], name = 'bias7') weight8 = weight_variable([1, 1, 100, 50], name = 'weight8') bias8 = bias_variable([50], name='bias8') weight9 = weight_variable([10, 10, 50, 3], name = 'weight9') bias9 = bias_variable([3], name = 'bias9') tf.summary.histogram('weight1', weight1) tf.summary.histogram('weight2', weight2) tf.summary.histogram('weight3', weight3) tf.summary.histogram('weight4', weight4) tf.summary.histogram('weight5', weight5) tf.summary.histogram('weight6', weight6) tf.summary.histogram('weight7', weight7) tf.summary.histogram('weight8', weight8) tf.summary.histogram('weight9', weight9) tf.summary.histogram('bias1', bias1) tf.summary.histogram('bias2', bias2) tf.summary.histogram('bias3', bias3) tf.summary.histogram('bias4', bias4) tf.summary.histogram('bias5', bias5) tf.summary.histogram('bias6', bias6) tf.summary.histogram('bias7', bias7) tf.summary.histogram('bias8', bias8) tf.summary.histogram('bias9', bias9) F7=l_relu(conv2d(y_image,weight7,bias7,1,"Conv1"),alpha=0.01,name="LReLU7") F8=l_relu(conv2d(F7,weight8,bias8,5,"Conv2"),alpha=0.01,name="LReLu8") F9=l_relu(conv2d(F8,weight9,bias9,1,"Conv3"),alpha=0.01,name="LReLu9") F1 = l_relu(conv2d(F9, weight1, bias1,1, "Conv1"), alpha = 0.01, name="LReLU1") F2 = l_relu(conv2d(F1, weight2, bias2,1, "Conv2"), alpha = 0.01, name="LReLU2") F3 = l_relu(conv2d(F2, weight3, bias3,1, "Conv3"), alpha = 0.01, name="LReLU3") Img2=tf.image.resize_bilinear(F3, (H2,W2)) F4 = l_relu(conv2d(Img2, weight4, bias4,1, "Conv4"), alpha = 0.01, name="LReLU4") F5 = l_relu(conv2d(F4, weight5, bias5,1, "Conv5"), alpha = 0.01, name="LReLU5") F6 = l_relu(conv2d(F5, weight6, bias6,1, "Conv6"), alpha = 0.01, name="LReLU6") y_result= l_relu(F6,alpha=0., name="ReLU") with tf.name_scope("Cost"): cost = tf.reduce_mean(tf.square(y_image-y_result)) with tf.name_scope("Train"): train_step = tf.train.AdamOptimizer(lr).minimize(cost) with tf.name_scope("Saver"): saver = tf.train.Saver() with tf.name_scope("Writer"): writer = tf.summary.FileWriter("Logs/"+name) with tf.name_scope("Init"): init_op = tf.global_variables_initializer() tf.summary.scalar('Cost', cost) tf.summary.image('answer720', y_image) tf.summary.image('output720', y_result) merged_summary = tf.summary.merge_all() with tf.Session() as sess: sess.run(init_op) saver.restore(sess, "Graphs/SCV-CNN-Batch/model.ckpt") writer.add_graph(sess.graph) if not os.path.exists(logDir+'/results'): os.makedirs(logDir+'/results') for steps in range(train_num): index_list = [ random.randrange(1,file_num+1) for _ in range(batch_num) ] # index=random.randrange(1,file_num+1) # array720= getimage(index) # f_dict={y_image:[array720]} input_list = [ getimage(x) for x in index_list ] f_dict = {y_image:input_list} sess.run(train_step, feed_dict=f_dict) if(steps%100==0): index=random.randrange(1,file_num+1) showres(index, steps) print (str(steps).zfill(3), sess.run(cost, feed_dict=f_dict)) saveCost() if(steps%500==0): save_path = saver.save(sess, "Graphs/"+name+"/model.ckpt") print("Model saved in file: %s" % save_path) summary = sess.run(merged_summary, feed_dict = f_dict) writer.add_summary(summary, steps) print ("DONE!!!!")
{ "repo_name": "yhunroh/SSHS-Waifu", "path": "SCV-batch.py", "copies": "1", "size": "5949", "license": "mit", "hash": -2501068361271973000, "line_mean": 35.4150943396, "line_max": 103, "alpha_frac": 0.6481761641, "autogenerated": false, "ratio": 2.6115013169446883, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8628875078231806, "avg_score": 0.02616048056257657, "num_lines": 159 }
#720->144->720 import tensorflow as tf from PIL import Image import numpy as np import os.path import random name = 'SCV-CNN-Re' lr=1e-4 #learning rate ratio = 4/3 H1=144 W1=int(H1*ratio) H15=360 W15=int(H15*ratio) H2=720 W2=int(H2*ratio) path="Data/" pref2="720p/" suff2=".jpg" train_num=3000000#1000 file_num=24600 logDir = 'Logs/'+name com_layer=[[40,40,3,100],[1,1,100,50],[10,10,50,3]] res_layer=[[40,40,3,100],[1,1,100,50],[10,10,50,3]] afterres_layer=[[40,40,3,100],[1,1,100,50],[10,10,50,3]] com_stride=[1,5,1] res_stride=[1,1,1] afterres_stride=[1,1,1] def graph_variable(shape): graph=[[],[]] for i in range(len(shape)): graph[0].append(tf.Variable(tf.truncated_normal(shape[i],stddev=0.01,name="weight"+str(i)))) graph[1].append(tf.Variable(tf.zeros(shape[i][-1]),name="bias"+str(i))) return graph def l_relu(x, alpha=0., name="leaky_relu"): with tf.name_scope(name): return tf.nn.relu(x)-alpha*tf.nn.relu(-x) def getimage(idx): img_2=Image.open(path+pref2+str(idx).zfill(5)+suff2) array_2=np.array(img_2)[:, :, 0:3] array_2=array_2.astype(np.float32) return array_2 def asImage(tensor): result=tensor[0].astype(np.uint8) return Image.fromarray(result,'RGB') def showres(index, steps): test720 = getimage(index) A=sess.run(y_result, feed_dict={y_image:[test720]}) for x in np.nditer(A, op_flags=['readwrite']): if x>255. : x[...]=255. result = A.astype(np.uint8) asImage(result).save(logDir+'/results/result_'+str(steps).zfill(6)+'__'+str(index).zfill(4)+'.jpg') def conv2d(x, W, B,stride, name="conv_layer"): with tf.name_scope(name): return tf.nn.conv2d(x, W, strides=[1, stride, stride, 1], padding='SAME')+B def saveCost(): fcost=open(logDir+"/cost.txt",'a') ShowCost=sess.run(cost, feed_dict=f_dict) string="step %03d: %f\n" %(steps,ShowCost) fcost.write(string) fcost.close() def tfsummary(graph): for i in graph: tf.summary.histogram(i[0].name,i[0]) tf.summary.histogram(i[1].name,i[1]) def conv_pic(image,weight,bias,stride): img=image for i in range(len(weight)): img=l_relu(conv2d(img,weight[i],bias[i],stride[i]),alpha =0.01) return img y_image=tf.placeholder(np.float32,shape=[None,H2,W2,3],name="answer_720_image") com_graph=graph_variable(com_layer) com_weight=com_graph[0] com_bias=com_graph[1] res_graph=graph_variable(res_layer) res_weight=res_graph[0] res_bias=res_graph[1] afterres_graph=graph_variable(afterres_layer) afterres_weight=afterres_graph[0] afterres_bias=afterres_graph[1] tfsummary(com_graph) tfsummary(res_graph) tfsummary(afterres_graph) com_img=conv_pic(y_image,com_weight,com_bias,com_stride) res_img=conv_pic(com_img,res_weight,res_bias,res_stride) res_img=tf.image.resize_bilinear(res_img,(H2,W2)) afterres_img=conv_pic(res_img,afterres_weight,afterres_bias,afterres_stride) y_result=l_relu(afterres_img,alpha=0., name="ReLU") with tf.name_scope("Cost"): cost = tf.reduce_mean(tf.square(y_image-y_result)) with tf.name_scope("Train"): train_step = tf.train.AdamOptimizer(lr).minimize(cost) with tf.name_scope("Saver"): saver = tf.train.Saver() with tf.name_scope("Writer"): writer = tf.summary.FileWriter("Logs/"+name) with tf.name_scope("Init"): init_op = tf.global_variables_initializer() tf.summary.scalar('Cost', cost) tf.summary.image('answer720', y_image) tf.summary.image('output720', y_result) merged_summary = tf.summary.merge_all() with tf.Session() as sess: sess.run(init_op) #saver.restore(sess, "Graphs/SCV-CNN/model.ckpt") #writer.add_graph(sess.graph) #if not os.path.exists(logDir+'/results'): # os.makedirs(logDir+'/results') for steps in range(train_num): print(steps) index=random.randrange(1,file_num+1) array720= getimage(index) f_dict={y_image:[array720]} sess.run(train_step, feed_dict=f_dict) if(steps%2==0): showres(index, steps) print (str(steps).zfill(3), sess.run(cost, feed_dict=f_dict)) #saveCost() #if(steps%500==0): #save_path = saver.save(sess, "Graphs/"+name+"/model.ckpt") #print("Model saved in file: %s" % save_path) #summary = sess.run(merged_summary, feed_dict = f_dict) #writer.add_summary(summary, steps) print ("DONE!!!!")
{ "repo_name": "yhunroh/SSHS-Waifu", "path": "RNE-수정.py", "copies": "1", "size": "4572", "license": "mit", "hash": 1501142592260606000, "line_mean": 29.5310344828, "line_max": 103, "alpha_frac": 0.6290463692, "autogenerated": false, "ratio": 2.6705607476635516, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.37996071168635515, "avg_score": null, "num_lines": null }
#720->144->720 import tensorflow as tf from PIL import Image import numpy as np import os.path import random name = 'SCV-CNN-Re' lr=1e-4 #learning rate ratio = 4/3 H1=144 W1=int(H1*ratio) H15=360 W15=int(H15*ratio) H2=720 W2=int(H2*ratio) path="../Data/" pref2="720p/" suff2=".jpg" train_num=3000000#1000 file_num=24600 logDir = 'Logs/'+name def weight_variable(shape, name): initial = tf.truncated_normal(shape, stddev=0.01, name="dummy") return tf.Variable(initial, name=name) def bias_variable(shape, name): initial = 0. return tf.Variable(initial, name=name) def getimage(idx): img_2=Image.open(path+pref2+str(idx).zfill(5)+suff2) array_2=np.array(img_2)[:, :, 0:3] array_2=array_2.astype(np.float32) return array_2 def l_relu(x, alpha=0., name="leaky_relu"): with tf.name_scope(name): return tf.nn.relu(x)-alpha*tf.nn.relu(-x) def asImage(tensor): result=tensor[0].astype(np.uint8) return Image.fromarray(result,'RGB') def showres(index, steps): test720 = getimage(index) A=sess.run(y_result, feed_dict={y_image:[test720]}) for x in np.nditer(A, op_flags=['readwrite']): if x>255. : x[...]=255. result = A.astype(np.uint8) asImage(result).save(logDir+'/results/result_'+str(steps).zfill(6)+'__'+str(index).zfill(4)+'.jpg') def conv2d(x, W, B,stride, name="conv_layer"): with tf.name_scope(name): return tf.nn.conv2d(x, W, strides=[1, stride, stride, 1], padding='SAME')+B def saveCost(): fcost=open(logDir+"/cost.txt",'a') ShowCost=sess.run(cost, feed_dict=f_dict) string="step %03d: %f\n" %(steps,ShowCost) fcost.write(string) fcost.close() y_image=tf.placeholder(np.float32,shape=[None,H2,W2,3],name="answer_720_image") weight1 = weight_variable([40, 40, 3, 100], name = 'weight1') bias1 = bias_variable([100], name = 'bias1') weight2 = weight_variable([1, 1, 100, 50], name = 'weight2') bias2 = bias_variable([50], name='bias2') weight3 = weight_variable([10, 10, 50, 3], name = 'weight3') bias3 = bias_variable([3], name = 'bias3') weight4 = weight_variable([40, 40, 3, 100], name = 'weight4') bias4 = bias_variable([100], name = 'bias4') weight5 = weight_variable([1, 1, 100, 50], name = 'weight5') bias5 = bias_variable([50], name='bias5') weight6 = weight_variable([11, 11, 50, 3], name = 'weight6') bias6 = bias_variable([3], name = 'bias6') weight7 = weight_variable([40, 40, 3, 100], name = 'weight7') bias7 = bias_variable([100], name = 'bias7') weight8 = weight_variable([1, 1, 100, 50], name = 'weight8') bias8 = bias_variable([50], name='bias8') weight9 = weight_variable([10, 10, 50, 3], name = 'weight9') bias9 = bias_variable([3], name = 'bias9') tf.summary.histogram('weight1', weight1) tf.summary.histogram('weight2', weight2) tf.summary.histogram('weight3', weight3) tf.summary.histogram('weight4', weight4) tf.summary.histogram('weight5', weight5) tf.summary.histogram('weight6', weight6) tf.summary.histogram('weight7', weight7) tf.summary.histogram('weight8', weight8) tf.summary.histogram('weight9', weight9) tf.summary.histogram('bias1', bias1) tf.summary.histogram('bias2', bias2) tf.summary.histogram('bias3', bias3) tf.summary.histogram('bias4', bias4) tf.summary.histogram('bias5', bias5) tf.summary.histogram('bias6', bias6) tf.summary.histogram('bias7', bias7) tf.summary.histogram('bias8', bias8) tf.summary.histogram('bias9', bias9) F7=l_relu(conv2d(y_image,weight7,bias7,1,"Conv1"),alpha=0.01,name="LReLU7") F8=l_relu(conv2d(F7,weight8,bias8,5,"Conv2"),alpha=0.01,name="LReLu8") F9=l_relu(conv2d(F8,weight9,bias9,1,"Conv3"),alpha=0.01,name="LReLu9") F1 = l_relu(conv2d(F9, weight1, bias1,1, "Conv1"), alpha = 0.01, name="LReLU1") F2 = l_relu(conv2d(F1, weight2, bias2,1, "Conv2"), alpha = 0.01, name="LReLU2") F3 = l_relu(conv2d(F2, weight3, bias3,1, "Conv3"), alpha = 0.01, name="LReLU3") Img2=tf.image.resize_bilinear(F3, (H2,W2)) F4 = l_relu(conv2d(Img2, weight4, bias4,1, "Conv4"), alpha = 0.01, name="LReLU4") F5 = l_relu(conv2d(F4, weight5, bias5,1, "Conv5"), alpha = 0.01, name="LReLU5") F6 = l_relu(conv2d(F5, weight6, bias6,1, "Conv6"), alpha = 0.01, name="LReLU6") y_result= l_relu(F6,alpha=0., name="ReLU") with tf.name_scope("Cost"): cost = tf.reduce_mean(tf.square(y_image-y_result)) with tf.name_scope("Train"): train_step = tf.train.AdamOptimizer(lr).minimize(cost) with tf.name_scope("Saver"): saver = tf.train.Saver() with tf.name_scope("Writer"): writer = tf.summary.FileWriter("Logs/"+name) with tf.name_scope("Init"): init_op = tf.global_variables_initializer() tf.summary.scalar('Cost', cost) tf.summary.image('answer720', y_image) tf.summary.image('output720', y_result) merged_summary = tf.summary.merge_all() with tf.Session() as sess: sess.run(init_op) saver.restore(sess, "Graphs/SCV-CNN/model.ckpt") writer.add_graph(sess.graph) if not os.path.exists(logDir+'/results'): os.makedirs(logDir+'/results') for steps in range(train_num): index=random.randrange(1,file_num+1) array720= getimage(index) f_dict={y_image:[array720]} sess.run(train_step, feed_dict=f_dict) if(steps%100==0): showres(index, steps) print (str(steps).zfill(3), sess.run(cost, feed_dict=f_dict)) saveCost() if(steps%500==0): save_path = saver.save(sess, "Graphs/"+name+"/model.ckpt") print("Model saved in file: %s" % save_path) summary = sess.run(merged_summary, feed_dict = f_dict) writer.add_summary(summary, steps) print ("DONE!!!!")
{ "repo_name": "yhunroh/SSHS-Waifu", "path": "SCV.py", "copies": "1", "size": "5690", "license": "mit", "hash": 2657230980662313500, "line_mean": 34.9480519481, "line_max": 103, "alpha_frac": 0.6509666081, "autogenerated": false, "ratio": 2.607699358386801, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.37586659664868005, "avg_score": null, "num_lines": null }
"""72. Edit Distance https://leetcode.com/problems/edit-distance/description/ Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2. You have the following 3 operations permitted on a word: - Insert a character - Delete a character - Replace a character Example 1: Input: word1 = "horse", word2 = "ros" Output: 3 Explanation: horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e') Example 2: Input: word1 = "intention", word2 = "execution" Output: 5 Explanation: intention -> inention (remove 't') inention -> enention (replace 'i' with 'e') enention -> exention (replace 'n' with 'x') exention -> exection (replace 'n' with 'c') exection -> execution (insert 'u') """ class Solution: def min_distance(self, word1: str, word2: str) -> int: len1, len2 = len(word1), len(word2) # dp[i][j] is the min distance to convert word1[:i] to word2[:j] dp = [[-1] * (len2 + 1) for _ in range(len1 + 1)] for i in range(len2 + 1): # insert i characters dp[0][i] = i for j in range(len1 + 1): # delete j characters dp[j][0] = j # state-transition equation: # if word1[i] equals to word2[j], it doesn't need any operations; # otherwise it should insert a character based on dp[i][j-1], # or delete a character based on dp[i-1][j], # or replace a character based on dp[i-1][j-1]. for i in range(1, len1 + 1): for j in range(1, len2 + 1): if word1[i - 1] == word2[j - 1]: dp[i][j] = dp[i - 1][j - 1] else: dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) + 1 return dp[len1][len2]
{ "repo_name": "isudox/leetcode-solution", "path": "python-algorithm/leetcode/edit_distance.py", "copies": "1", "size": "1842", "license": "mit", "hash": 4992643133368479000, "line_mean": 28.7096774194, "line_max": 73, "alpha_frac": 0.562432139, "autogenerated": false, "ratio": 3.154109589041096, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9216541728041096, "avg_score": 0, "num_lines": 62 }
#7.2 Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form: #X-DSPAM-Confidence: 0.8475 #Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. #You can download the sample data at http://www.pythonlearn.com/code/mbox-short.txt when you are testing below enter mbox-short.txt as the file name. fname = raw_input("Enter file name: ") count = 0 floataverage = 0 converted_string = 0 average_string = 0 if len(fname) == 0: fname = 'mbox-short.txt' fh = open(fname) for line in fh: if not line.startswith("X-DSPAM-Confidence:") : continue count += 1 converted_string = 0 spaces = line.find(' ') eol = line.find('"') number_string = line[spaces : eol] stripped_string = number_string.strip() try: converted_string = float(stripped_string) except: print 'couldn\t convert to a string, your stuff above broke something' average_string += converted_string #print 'sum is ',average_string #used these for debugging #print 'count is ',count#used these for debugging floataverage = average_string / count print 'Average spam confidence:',floataverage
{ "repo_name": "joeyb182/pynet_ansible", "path": "Coursera-UMich/files_7-2_assignment.py", "copies": "1", "size": "1286", "license": "apache-2.0", "hash": -210679510462083140, "line_mean": 41.8666666667, "line_max": 157, "alpha_frac": 0.7122861586, "autogenerated": false, "ratio": 3.738372093023256, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49506582516232556, "avg_score": null, "num_lines": null }
# 7.2 Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form: # X-DSPAM-Confidence: 0.8475 # Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. # You can download the sample data at http://www.pythonlearn.com/code/mbox-short.txt when you are testing below enter mbox-short.txt as the file name. # declare variables countline = 0 total = 0 # Query for filename fname = "mbox-short.txt" # fname = raw_input("Enter file name: ") try : fhandle = open(fname) except : print "Unknown Filename" exit() for line in fhandle : if not line.startswith("X-DSPAM-Confidence:") : continue chrpos = line.find(":") chrnum = line[chrpos+1:].strip() total = total + float(chrnum) countline = countline + 1 print "Average spam confidence: ", total/countline # Read file # fcontent = fhandle.read() # fcontent = fcontent.strip() # print fcontent.upper()
{ "repo_name": "jerrydeboer/crs-assignments", "path": "assignement72.py", "copies": "1", "size": "1059", "license": "cc0-1.0", "hash": -9135569060161607000, "line_mean": 31.0909090909, "line_max": 158, "alpha_frac": 0.7072710104, "autogenerated": false, "ratio": 3.553691275167785, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9462333310532813, "avg_score": 0.059725795006994514, "num_lines": 33 }
# 73167176531330624919225119674426574742355349194934 # 96983520312774506326239578318016984801869478851843 # 85861560789112949495459501737958331952853208805511 # 12540698747158523863050715693290963295227443043557 # 66896648950445244523161731856403098711121722383113 # 62229893423380308135336276614282806444486645238749 # 30358907296290491560440772390713810515859307960866 # 70172427121883998797908792274921901699720888093776 # 65727333001053367881220235421809751254540594752243 # 52584907711670556013604839586446706324415722155397 # 53697817977846174064955149290862569321978468622482 # 83972241375657056057490261407972968652414535100474 # 82166370484403199890008895243450658541227588666881 # 16427171479924442928230863465674813919123162824586 # 17866458359124566529476545682848912883142607690042 # 24219022671055626321111109370544217506941658960408 # 07198403850962455444362981230987879927244284909188 # 84580156166097919133875499200524063689912560717606 # 05886116467109405077541002256983155200055935729725 # 71636269561882670428252483600823257530420752963450 # Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? import math def main(): number_of_digits = 4 max_product = 1 big_number = """73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450""" first_digit = big_number[0] new_digit = big_number[9] for i in big_number[:4]: max_product = max_product*int(i) print max_product for i in big_number[5:]: if i.isdigit(): new_digit = i main()
{ "repo_name": "utsavnarayan/projecteuler", "path": "solutions/8.py", "copies": "1", "size": "2926", "license": "mit", "hash": 2401993863502567400, "line_mean": 47.7666666667, "line_max": 127, "alpha_frac": 0.7812713602, "autogenerated": false, "ratio": 2.7840152235965747, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.40652865837965746, "avg_score": null, "num_lines": null }
"""75. Sort Colors https://leetcode.com/problems/sort-colors/ Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note: You are not suppose to use the library's sort function for this problem. Example: Input: [2,0,2,1,1,0] Output: [0,0,1,1,2,2] """ from typing import List class Solution: def sort_colors_1_pass(self, nums: List[int]) -> None: left = 0 right = len(nums) - 1 i = 0 while i <= right: if nums[i] == 0: nums[i], nums[left] = nums[left], 0 left += 1 i += 1 elif nums[i] == 2: nums[i], nums[right] = nums[right], 2 right -= 1 else: i += 1 def sort_colors_2_pass(self, nums: List[int]) -> None: store = {0: 0, 1: 0, 2: 0} for num in nums: store[num] += 1 i = 0 for k, v in store.items(): nums[i: i + v] = [k] * v i += v
{ "repo_name": "isudox/leetcode-solution", "path": "python-algorithm/leetcode/sort_colors.py", "copies": "1", "size": "1202", "license": "mit", "hash": -6440219481216702000, "line_mean": 26.3181818182, "line_max": 78, "alpha_frac": 0.5266222962, "autogenerated": false, "ratio": 3.3669467787114846, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4393569074911485, "avg_score": null, "num_lines": null }
"""76. Minimum Window Substring https://leetcode.com/problems/minimum-window-substring/ Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). Example: Input: S = "ADOBECODEBANC", T = "ABC" Output: "BANC" Note: If there is no such window in S that covers all characters in T, return the empty string "". If there is such window, you are guaranteed that there will always be only one unique minimum window in S. """ class Solution: def min_window(self, s: str, t: str) -> str: def is_valid(d: dict): for v in d.values(): if v > 0: return False return True store = {} for c in t: if c not in store: store[c] = 1 else: store[c] = store[c] + 1 min_head = min_tail = 0 head = tail = -1 min_len = len(s) + 1 not_found = True while head <= tail: if not_found: # if not found, move the cur_tail pointer. if tail == len(s) - 1: break tail += 1 cur_char = s[tail] if cur_char in store: store[cur_char] = store[cur_char] - 1 if is_valid(store): not_found = False cur_len = tail - head if cur_len < min_len: min_head, min_tail, min_len = head, tail, cur_len else: # already found, move the cur_head pointer. head += 1 cur_char = s[head] cur_len = tail - head if cur_char in store: store[cur_char] = store[cur_char] + 1 if not is_valid(store): not_found = True else: if cur_len < min_len: min_head, min_tail, min_len = head, tail, cur_len else: if cur_len < min_len: min_head, min_tail, min_len = head, tail, cur_len return s[min_head + 1:min_tail + 1]
{ "repo_name": "isudox/leetcode-solution", "path": "python-algorithm/leetcode/minimum_window_substring.py", "copies": "1", "size": "2253", "license": "mit", "hash": -3524778804632741400, "line_mean": 30.7323943662, "line_max": 77, "alpha_frac": 0.459831336, "autogenerated": false, "ratio": 4.059459459459459, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5019290795459459, "avg_score": null, "num_lines": null }
# 796. Rotate String # We are given two strings, A and B. # A shift on A consists of taking string A and moving the leftmost character to the rightmost position. # For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. # Return True if and only if A can become B after some number of shifts on A. # Example 1: # Input: A = 'abcde', B = 'cdeab' # Output: true # Example 2: # Input: A = 'abcde', B = 'abced' # Output: false # Note: # A and B will have length at most 100. # -------------------------- # Given two string s1 and s2 how will you check if s1 is a rotated version of s2 ? # # Example: # # If s1 = "stackoverflow" then the following are some of its rotated versions: # # "tackoverflows" # "ackoverflowst" # "overflowstack" # where as "stackoverflwo" is not a rotated version. class Solution(object): def rotateString(self, A, B): """ :type A: str :type B: str :rtype: bool """ return len(A) == len(B) and A in B * 2 def isRotation(s1, s2): if not s1 and not s2: return True for i in range(0, len(s1)): s3 = s1[-i:] + s1[:-i] if s3 == s2: return True return False def isRotation(s1, s2): return len(s1) == len(s2) and s1 in s2 * 2 def isRotation(s1, s2): if len(s1) != len(s2): return False return s1 in s2 * 2 if __name__ == '__main__': s1 = "stackoverflow" print isRotation(s1, "tackoverflows") print isRotation(s1, "ackoverflowst") print isRotation(s1, "overflowstack") print isRotation(s1, "stackoverflwo")
{ "repo_name": "gengwg/leetcode", "path": "796_rotate_string.py", "copies": "1", "size": "1605", "license": "apache-2.0", "hash": -4576956812069303300, "line_mean": 24.4761904762, "line_max": 104, "alpha_frac": 0.600623053, "autogenerated": false, "ratio": 3.062977099236641, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9048671528794074, "avg_score": 0.022985724688513363, "num_lines": 63 }
"""79 characters long """ import sys import webbrowser import praw import prawcore from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * reddit = praw.Reddit('cheeseywhiz') class InputDialog(QMainWindow): """Enter subreddit: [Enter] [input field] [Action:] """ def __init__(self): super().__init__() self.setWindowIcon(self.style().standardIcon(QStyle.SP_ComputerIcon)) self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.WindowCloseButtonHint | Qt.WindowMinimizeButtonHint | Qt.MSWindowsFixedSizeDialogHint) self.setWindowTitle('Get Reddit Link') self.setCentralWidget(InputWidget(self)) self.minimumWidth_ = 248 self.setMinimumWidth(self.minimumWidth_) self.setFixedSize(self.minimumSize()) self.show() class InputWidget(QWidget): """Argument to class is parent object (self) Gathers all elements to be displayed in the main dialog """ def __init__(self, caller): self.caller = caller super().__init__() self.init_elements() self.init_connections() self.setLayout(self.input_layout()) def init_elements(self): self.inputField = InputField(self) self.linksDropdown = ActionsDropdown(self, ['Part of submission:', 'Comments', 'Link']) self.sortDropdown = ActionsDropdown(self, ['Sort:', 'Hot', 'Top', 'New']) self.timesDropdown = ActionsDropdown(self, ['Time limit:', 'all', 'year', 'month', 'week', 'day', 'hour']) self.statusLine = QLabel('Waiting on subreddit...') def init_connections(self): self.get_inputEvent([self.inputField]) self.get_optionChangeEvent([self.sortDropdown]) def input_layout(self): layout = QVBoxLayout() widgets = [self.label_InputField_widget(), self.linksDropdown, self.sortDropdown, self.timesDropdown, self.statusLine] for widget in widgets: layout.addWidget(widget) self.timesDropdown.hide() self.statusLine.hide() return layout def label_InputField_widget(self): row = QWidget() rowLayout = QHBoxLayout() rowLayout.setContentsMargins(0, 0, 0, 0) rowLayout.addWidget(QLabel('Enter subreddit:')) rowLayout.addWidget(self.inputField) row.setLayout(rowLayout) return row def get_inputEvent(self, sources): for source in sources: source.inputEvent.connect(self.on_input_event) def get_optionChangeEvent(self, sources): for source in sources: source.optionChangeEvent.connect(self.on_sort_change_event) def on_input_event(self, self_): link = self_.linksDropdown.currentIndex() sort = self_.sortDropdown.currentIndex() userInput = self_.inputField.text() self.statusLine.show() try: if userInput == '': raise Exception('No subreddit entered') self_.open_link(link, sort, userInput) except prawcore.exceptions.Redirect as error: self_.statusLine.setText('Subreddit not found') except prawcore.exceptions.NotFound as error: self_.statusLine.setText('Subreddit not found') except Exception as error: self_.statusLine.setText(str(type(error))) def on_sort_change_event(self, self_): if self.sortDropdown.currentIndex() == 2: self.timesDropdown.show() else: if self.timesDropdown.isVisible(): self.timesDropdown.hide() self.setMinimumWidth(self.caller.minimumWidth_) self.caller.setFixedSize(self.minimumSize()) def open_link(self, link, sort, userInput): self.statusLine.setText('Opening...') QCoreApplication.processEvents() time = self.timesDropdown.currentIndex() subreddit = reddit.subreddit(userInput) timeDictionary = {0: 'all', 1: 'all', 2: 'year', 3: 'month', 4: 'week', 5: 'day', 6: 'hour'} timeString = timeDictionary[time] sortDictionary = {0: (subreddit.hot(limit=5), 'hottest'), 1: (subreddit.hot(limit=5), 'hottest'), 2: (subreddit.top(time_filter=timeString, limit=5), 'top/' + timeString), 3: (subreddit.new(limit=5), 'newest')} posts, sortString = sortDictionary[sort] submission = [post for post in posts if not post.stickied][0] linkDictionary = {0: (submission.shortlink, 'Opened comments from '), 1: (submission.shortlink, 'Opened comments from '), 2: (submission.url, 'Opened link from ')} url, linkString = linkDictionary[link] webbrowser.open(url) self.statusLine.setText( linkString + sortString + ' in /r/' + userInput) class InputField(QLineEdit): """InputField(parent): Argument allows for parent to receive signal. Sends signal inputEvent on return. """ inputEvent = pyqtSignal('QObject') def __init__(self, caller): self.caller = caller super().__init__() self.returnPressed.connect(self.on_return_pressed) def on_return_pressed(self): self.inputEvent.emit(self.caller) def mousePressEvent(self, event): self.selectAll() class ActionsDropdown(QComboBox): """Drop down box with the first element being uneditable """ optionChangeEvent = pyqtSignal('QObject') def __init__(self, caller, actions): self.caller = caller super().__init__() for action in actions: self.addItem(action) index = self.model().index(0, 0) self.model().setData(index, QVariant(0), Qt.UserRole - 1) self.currentIndexChanged.connect(self.on_index_change) def on_index_change(self, event): self.optionChangeEvent.emit(self.caller) if __name__ == '__main__': app = QApplication(sys.argv) id = InputDialog() sys.exit(app.exec_())
{ "repo_name": "cheeseywhiz/cheeseywhiz", "path": "Reddit-scripts/GetRedditLink/Dialogs/Input.py", "copies": "1", "size": "7010", "license": "mit", "hash": 2151585535274177500, "line_mean": 35.5104166667, "line_max": 79, "alpha_frac": 0.5370898716, "autogenerated": false, "ratio": 4.490711082639334, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5527800954239334, "avg_score": null, "num_lines": null }
import sys import os.path from getopt import gnu_getopt, GetoptError import re BASIC_SET = set([ 'BTEQZ', 'BNEZ', 'MTSP', 'JR', 'SUBU', 'SRA', 'BEQZ', 'MFPC', 'CMP', 'LI', 'LW', 'MFIH', 'MTIH', 'ADDIU', 'B', 'ADDIU3', 'SLL', 'SW_SP', 'LW_SP', 'AND', 'ADDU', 'SW', 'ADDSP', 'NOP', 'OR', ]) EXTEND_SET = {'JRRA', 'SLTI', 'ADDSP3', 'SLLV', 'SLT'} PAT_HEX = re.compile(r'^-?(0x)?([0-9a-f]+)h?$') PAT_REG = re.compile(r'^r[0-7]$') PAT_BINSTR = re.compile(r'[01]{16}') ferr = sys.stderr # options debug = False printBin = True # global state lineNum = 0 codeAddr = 0 # global info labelAddr = {} labelLine = {} def usage(msg=''): ferr.write('%s\n' % msg) ferr.write(__doc__) sys.exit(2) def main(): try: opts, args = gnu_getopt(sys.argv[1:], 'qvh', ['stdio', 'help']) except GetoptError as err: usage(err) fin = None fout = None for o, a in opts: if o == '-h' or o == '--help': usage() elif o == '--stdio': fin = sys.stdin fout = sys.stdout else: usage('Unknown option "%s".' % o) if fin is None: if len(args) > 0: fin = open(args[0], 'rU') if len(args) > 1: outFilename = args[1] if len(args) > 2: usage('Too many arguments.') else: outFilename = os.path.basename(args[0]) + '.bin' else: usage() global lineNum, codeAddr, labelAddr, labelLine codeBuf = [] while 1: line = fin.readline() if line == '': break lineNum += 1 commentPos = line.find(';') if commentPos != -1: line = line[:commentPos] tokenList = line.split() if len(tokenList) == 0: continue if debug: ferr.write('%s %s\n' % (lineNum, tokenList)) if tokenList[0][-1] == ':': label = tokenList[0][:-1] assert label not in labelAddr,\ 'Line %d: Label already found at Line %d, Addr 0x%04x.' %\ (lineNum, labelLine[label], labelAddr[label]) labelAddr[label] = codeAddr labelLine[label] = lineNum assert len(tokenList) == 1,\ 'Line %d: No token allowed after label.' % lineNum else: inst = tokenList[0] codeBuf.append((lineNum, tokenList)) codeAddr += 1 if fin != sys.stdin: fin.close() if debug: ferr.write('%s\n' % labelAddr) if fout is None: fout = open(outFilename, 'wb') codeAddr = 0 for curLineNum, tokenList in codeBuf: lineNum = curLineNum inst = tokenList[0] if inst not in (BASIC_SET | EXTEND_SET): ferr.write( 'Warning Line %d: Non-basic instruction "%s" used.\n' % (lineNum, inst) ) try: # Parsers other than parseWithPrototype can be invoke here # to provide smarter parse. Keep parseWithPrototype pure and # clean. if printBin: meow = parseWithPrototype(tokenList) print 'L:{0:<3d}'.format(lineNum), (meow), print '{0:6}'.format(hex(int(meow, 2))), print 'C:{0:<3d}'.format(codeAddr), tokenList fout.write(genFromBinStr(parseWithPrototype(tokenList))) except Exception as err: raise Exception('Line %d: %s' % (lineNum, err.message)) codeAddr += 1 ferr.write('END.\n') if fout != sys.stdout: fout.close() def hex2int(h): if h.isdigit(): return ord(h) - ord('0') else: assert h in set('abcdef') return ord(h) - ord('a') + 10 def parseImm(token, bitN=8, relative=None): if token in labelAddr: value = labelAddr[token] if relative is not None: value -= (codeAddr + 1) else: token = token.lower() mat = PAT_HEX.match(token) if mat is not None: hexStr = mat.group(2) value = reduce(lambda s, i: (s << 4) + hex2int(i), hexStr, 0) if token[0] == '-': value = - value else: raise Exception('Unknown base for Immediate "%s".' % token) if value >= (1 << 15): oldV = value value -= (1 << 16) ferr.write( 'Warning Line %d: Fixed Immediate "%s" to "%s".\n' % (lineNum, hex(oldV), hex(value)) ) if value >= (1 << bitN) or value < - (1 << (bitN - 1)): raise Exception( 'Immediate too large, "%s"(%s) exceeds %d bits.' % (token, hex(value), bitN) ) if value < 0: value += (1 << bitN) ans = bin(value)[2:] ans = '0' * (bitN - len(ans)) + ans return ans def parseReg(token): token = token.lower() mat = PAT_REG.match(token) if mat is None: raise Exception('Unable to parse register from "%s".' % token) ans = bin(ord(token[1]) - ord('0'))[2:] ans = '0' * (3 - len(ans)) + ans return ans def genFromBinStr(binStr): assert PAT_BINSTR.match(binStr) is not None word = reduce(lambda s, i: (s << 1) + (i == '1'), binStr, 0) return chr(word & 255) + chr(word >> 8) # Endian!!! PROTOTYPE = { 'ADDIU': ['10001', parseReg, parseImm, ], 'ADDIU3': ['10101', parseReg, parseReg, '0', lambda t: parseImm(t, 4), ], 'ADDSP3': ['10011', parseReg, parseImm, ], 'ADDSP': ['01110', parseImm, '000'], 'ADDU': ['01100', parseReg, parseReg, parseReg, '00', ], 'AND': ['00101', parseReg, parseReg, '00000', ], 'B': ['11000', lambda t: parseImm(t, 11, relative='rel'), ], 'BEQZ': ['11010', parseReg, lambda t: parseImm(t, relative='rel'), ], 'BNEZ': ['11011', parseReg, lambda t: parseImm(t, relative='rel'), ], 'BTEQZ': ['11001', lambda t: parseImm(t, relative='rel'), '000'], # 'BTNEZ': ['01100001', lambda t: parseImm(t, relative='rel'), ], 'CMP': ['01001', parseReg, parseReg, '00000', ], # 'CMPI': ['01110', parseReg, parseImm, ], # 'INT': ['111110000000', lambda t: parseImm(t, 4), ], # 'JALR': ['11101', parseReg, '11000000', ], 'JR': ['11101', parseReg, '00000000', ], 'JRRA': ['1110000000000000', ], 'LI': ['10100', parseReg, parseImm, ], 'LW': ['10110', parseReg, parseReg, lambda t: parseImm(t, 5), ], 'LW_SP': ['01111', parseReg, parseImm, ], 'MFIH': ['00001', parseReg, '00000000', ], 'MFPC': ['00010', parseReg, '00000000', ], # 'MOVE': ['01111', parseReg, parseReg, '00000', ], 'MTIH': ['00011', parseReg, '00000000', ], 'MTSP': ['00100', parseReg, '00000000', ], # 'NEG': ['11101', parseReg, parseReg, '01011', ], 'NOT': ['00111', parseReg, parseReg, '00000', ], 'NOP': ['0000000000000000', ], 'OR': ['00110', parseReg, parseReg, '00000', ], 'SLL': ['01010', parseReg, parseReg, lambda t: parseImm(t, 3), '00', ], # 'SLLV': ['11101', parseReg, parseReg, '00100', ], 'SLT': ['01000', parseReg, parseReg, '00000', ], 'SLTI': ['10010', parseReg, parseImm, ], # 'SLTU': ['11101', parseReg, parseReg, '00011', ], # 'SLTUI': ['01011', parseReg, parseImm, ], 'SRA': ['01011', parseReg, parseReg, lambda t: parseImm(t, 3), '00', ], # 'SRAV': ['11101', parseReg, parseReg, '00111', ], # 'SRL': ['00110', parseReg, parseReg, lambda t: parseImm(t, 3), '10', ], # 'SRLV': ['11101', parseReg, parseReg, '00110', ], 'SUBU': ['01101', parseReg, parseReg, parseReg, '00', ], 'SW': ['10111', parseReg, parseReg, lambda t: parseImm(t, 5), ], # 'SW_RS': ['01100010', parseImm, ], 'SW_SP': ['11010', parseReg, parseImm, ], # 'XOR': ['11101', parseReg, parseReg, '01110', ], 'RET': ['1111111111111111', ], # 'LIT': [lambda t: parseImm(t, 16), ], } def parseWithPrototype(tokenList): inst = tokenList[0] if inst in PROTOTYPE: ans = '' idx = 1 for part in PROTOTYPE[inst]: if isinstance(part, str): ans += part else: if len(tokenList) <= idx: raise Exception( 'Argument %d of instruction "%s" not found.' % (idx, inst) ) ans += part(tokenList[idx]) idx += 1 if len(tokenList) > idx: raise Exception('Too many arguments for instruction "%s".' % inst) return ans else: raise Exception('Unknown instruction "%s".' % inst) if __name__ == '__main__': main()
{ "repo_name": "fupolarbear/THU-Class-CO-makecomputer", "path": "assembler/thcoas.py", "copies": "1", "size": "9359", "license": "mit", "hash": -4572262676468717600, "line_mean": 32.7870036101, "line_max": 79, "alpha_frac": 0.5097766855, "autogenerated": false, "ratio": 3.283859649122807, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.42936363346228074, "avg_score": null, "num_lines": null }
"""79. Word Search https://leetcode.com/problems/word-search/description/ Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. Example: board = [ ⁠ ['A','B','C','E'], ⁠ ['S','F','C','S'], ⁠ ['A','D','E','E'] ] Given word = "ABCCED", return true. Given word = "SEE", return true. Given word = "ABCB", return false. """ from typing import List class Solution: def exist(self, board: List[List[str]], word: str) -> bool: rows, cols, length = len(board), len(board[0]), len(word) # mark the element in board usable = [[True] * cols for _ in range(rows)] # four directions d = [[0, 1], [0, -1], [-1, 0], [1, 0]] def backtrack(r: int, c: int, i: int) -> bool: """ backtrack checking the character :param r: the index of row :param c: the index of col :param i: the index of character :return: """ if i == length: return True if r < 0 or r >= rows or c < 0 or c >= cols: return False if board[r][c] != word[i]: return False if not usable[r][c]: return False usable[r][c] = False if any(backtrack(r + x[0], c + x[1], i + 1) for x in d): return True usable[r][c] = True return False for row in range(rows): for col in range(cols): if backtrack(row, col, 0): return True return False
{ "repo_name": "isudox/leetcode-solution", "path": "python-algorithm/leetcode/word_search.py", "copies": "1", "size": "1779", "license": "mit", "hash": -3279024242654806000, "line_mean": 27.1428571429, "line_max": 77, "alpha_frac": 0.518894529, "autogenerated": false, "ratio": 3.6481481481481484, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9667042677148148, "avg_score": 0, "num_lines": 63 }
# 7 may 2013 from idc import * def panic(msg): print(msg) exit() def addseg(name, start, end): err = idc.AddSeg(start, end, 0, 1, idc.saAbs, idc.scPub) if err != 1: panic("add segment %s failed" % (name)) err = idc.RenameSeg(start, name) if not(err): panic("rename segment %s failed" % (name)) def setLabelAndComment(addr, label, comment): err = idc.MakeNameEx(addr, label, idc.SN_PUBLIC) if err != 1: panic("rename 0x%X to %s failed" % (addr, label)) idc.MakeRptCmt(addr, comment) def makeByte(addr, label, comment): err = idc.MakeByte(addr) if err != 1: panic("make 0x%X (%s) byte failed" % (addr, label)) setLabelAndComment(addr, label, comment) def makeWord(addr, label, comment): err = idc.MakeWord(addr) if err != 1: panic("make 0x%X (%s) word failed" % (addr, label)) setLabelAndComment(addr, label, comment) def makeLong(addr, label, comment): err = idc.MakeDword(addr) if err != 1: panic("make 0x%X (%s) long failed" % (addr, label)) setLabelAndComment(addr, label, comment) def main(): err = idc.rebase_program(0x08000000, idc.MSF_FIXONCE) if err != idc.MOVE_SEGM_OK: # TODO more descriptive panic("could not rebase program: %d" % (err)) addseg("WRAMo", 0x02000000, 0x02040000) addseg("WRAMc", 0x03000000, 0x03008000) addseg("IOREG", 0x04000000, 0x04000400) addseg("CRAM", 0x05000000, 0x05000400) addseg("VRAM", 0x06000000, 0x06018000) addseg("OAM", 0x07000000, 0x07000400) # ROM addseg("SRAM", 0x0E000000, 0x0E010000) makeWord(0x4000000, "DISPCNT", "LCD") makeWord(0x4000002, "UNDOC_GREENSWAP", "Undocumented - Green") makeWord(0x4000004, "DISPSTAT", "General LCD Status") makeWord(0x4000006, "VCOUNT", "Vertical Counter") makeWord(0x4000008, "BG0CNT", "BG0") makeWord(0x400000A, "BG1CNT", "BG1") makeWord(0x400000C, "BG2CNT", "BG2") makeWord(0x400000E, "BG3CNT", "BG3") makeWord(0x4000010, "BG0HOFS", "BG0") makeWord(0x4000012, "BG0VOFS", "BG0") makeWord(0x4000014, "BG1HOFS", "BG1") makeWord(0x4000016, "BG1VOFS", "BG1") makeWord(0x4000018, "BG2HOFS", "BG2") makeWord(0x400001A, "BG2VOFS", "BG2") makeWord(0x400001C, "BG3HOFS", "BG3") makeWord(0x400001E, "BG3VOFS", "BG3") makeWord(0x4000020, "BG2PA", "BG2 Rotation/Scaling Parameter A") makeWord(0x4000022, "BG2PB", "BG2 Rotation/Scaling Parameter B") makeWord(0x4000024, "BG2PC", "BG2 Rotation/Scaling Parameter C") makeWord(0x4000026, "BG2PD", "BG2 Rotation/Scaling Parameter D") makeLong(0x4000028, "BG2X", "BG2 Reference Point") makeLong(0x400002C, "BG2Y", "BG2 Reference Point") makeWord(0x4000030, "BG3PA", "BG3 Rotation/Scaling Parameter A") makeWord(0x4000032, "BG3PB", "BG3 Rotation/Scaling Parameter B") makeWord(0x4000034, "BG3PC", "BG3 Rotation/Scaling Parameter C") makeWord(0x4000036, "BG3PD", "BG3 Rotation/Scaling Parameter D") makeLong(0x4000038, "BG3X", "BG3 Reference Point") makeLong(0x400003C, "BG3Y", "BG3 Reference Point") makeWord(0x4000040, "WIN0H", "Window 0 Horizontal") makeWord(0x4000042, "WIN1H", "Window 1 Horizontal") makeWord(0x4000044, "WIN0V", "Window 0 Vertical") makeWord(0x4000046, "WIN1V", "Window 1 Vertical") makeWord(0x4000048, "WININ", "Inside of Window 0 and") makeWord(0x400004A, "WINOUT", "Inside of OBJ Window & Outside of") makeWord(0x400004C, "MOSAIC", "Mosaic") makeWord(0x4000050, "BLDCNT", "Color Special Effects") makeWord(0x4000052, "BLDALPHA", "Alpha Blending") makeWord(0x4000054, "BLDY", "Brightness (Fade-In/Out)") makeWord(0x4000060, "SOUND1CNT_L", "Channel 1 Sweep register") makeWord(0x4000062, "SOUND1CNT_H", "Channel 1 Duty/Length/Envelope (NR11,") makeWord(0x4000064, "SOUND1CNT_X", "Channel 1 Frequency/Control (NR13,") makeWord(0x4000068, "SOUND2CNT_L", "Channel 2 Duty/Length/Envelope (NR21,") makeWord(0x400006C, "SOUND2CNT_H", "Channel 2 Frequency/Control (NR23,") makeWord(0x4000070, "SOUND3CNT_L", "Channel 3 Stop/Wave RAM select") makeWord(0x4000072, "SOUND3CNT_H", "Channel 3 Length/Volume (NR31,") makeWord(0x4000074, "SOUND3CNT_X", "Channel 3 Frequency/Control (NR33,") makeWord(0x4000078, "SOUND4CNT_L", "Channel 4 Length/Envelope (NR41,") makeWord(0x400007C, "SOUND4CNT_H", "Channel 4 Frequency/Control (NR43,") makeWord(0x4000080, "SOUNDCNT_L", "Control Stereo/Volume/Enable (NR50,") makeWord(0x4000082, "SOUNDCNT_H", "Control Mixing/DMA") makeWord(0x4000084, "SOUNDCNT_X", "Control Sound on/off") makeWord(0x4000088, "SOUNDBIAS", "Sound PWM") # 4000090h 2x10h R/W WAVE_RAM Channel 3 Wave Pattern RAM (2 banks!!) makeLong(0x40000A0, "FIFO_A", "Channel A FIFO, Data") makeLong(0x40000A4, "FIFO_B", "Channel B FIFO, Data") makeLong(0x40000B0, "DMA0SAD", "DMA 0 Source") makeLong(0x40000B4, "DMA0DAD", "DMA 0 Destination") makeWord(0x40000B8, "DMA0CNT_L", "DMA 0 Word") makeWord(0x40000BA, "DMA0CNT_H", "DMA 0") makeLong(0x40000BC, "DMA1SAD", "DMA 1 Source") makeLong(0x40000C0, "DMA1DAD", "DMA 1 Destination") makeWord(0x40000C4, "DMA1CNT_L", "DMA 1 Word") makeWord(0x40000C6, "DMA1CNT_H", "DMA 1") makeLong(0x40000C8, "DMA2SAD", "DMA 2 Source") makeLong(0x40000CC, "DMA2DAD", "DMA 2 Destination") makeWord(0x40000D0, "DMA2CNT_L", "DMA 2 Word") makeWord(0x40000D2, "DMA2CNT_H", "DMA 2") makeLong(0x40000D4, "DMA3SAD", "DMA 3 Source") makeLong(0x40000D8, "DMA3DAD", "DMA 3 Destination") makeWord(0x40000DC, "DMA3CNT_L", "DMA 3 Word") makeWord(0x40000DE, "DMA3CNT_H", "DMA 3") makeWord(0x4000100, "TM0CNT_L", "Timer 0") makeWord(0x4000102, "TM0CNT_H", "Timer 0") makeWord(0x4000104, "TM1CNT_L", "Timer 1") makeWord(0x4000106, "TM1CNT_H", "Timer 1") makeWord(0x4000108, "TM2CNT_L", "Timer 2") makeWord(0x400010A, "TM2CNT_H", "Timer 2") makeWord(0x400010C, "TM3CNT_L", "Timer 3") makeWord(0x400010E, "TM3CNT_H", "Timer 3") makeLong(0x4000120, "SIODATA32", "SIO Data (Normal-32bit Mode) (shared with") makeWord(0x4000120, "SIOMULTI0", "SIO Data 0 (Parent) (Multi-Player") makeWord(0x4000122, "SIOMULTI1", "SIO Data 1 (1st Child) (Multi-Player") makeWord(0x4000124, "SIOMULTI2", "SIO Data 2 (2nd Child) (Multi-Player") makeWord(0x4000126, "SIOMULTI3", "SIO Data 3 (3rd Child) (Multi-Player") makeWord(0x4000128, "SIOCNT", "SIO Control") makeWord(0x400012A, "SIOMLT_SEND", "SIO Data (Local of Multi-Player) (shared") makeWord(0x400012A, "SIODATA8", "SIO Data (Normal-8bit and UART") makeWord(0x4000130, "KEYINPUT", "Key") makeWord(0x4000132, "KEYCNT", "Key Interrupt") makeWord(0x4000134, "RCNT", "SIO Mode Select/General Purpose") makeWord(0x4000140, "JOYCNT", "SIO JOY Bus") makeLong(0x4000150, "JOY_RECV", "SIO JOY Bus Receive") makeLong(0x4000154, "JOY_TRANS", "SIO JOY Bus Transmit") makeWord(0x4000158, "JOYSTAT", "SIO JOY Bus Receive") makeWord(0x4000200, "IE", "Interrupt Enable") makeWord(0x4000202, "IF", "Interrupt Request Flags / IRQ") makeWord(0x4000204, "WAITCNT", "Game Pak Waitstate") makeWord(0x4000208, "IME", "Interrupt Master Enable") makeByte(0x4000300, "POSTFLG", "Undocumented - Post Boot") makeByte(0x4000301, "HALTCNT", "Undocumented - Power Down") makeLong(0x03007FFC, "IRQAddr", "") idc.Jump(0x08000000) print("success") main()
{ "repo_name": "andlabs/idapyscripts", "path": "gbaload.py", "copies": "1", "size": "7051", "license": "mit", "hash": -7422922637238306000, "line_mean": 42.524691358, "line_max": 79, "alpha_frac": 0.7128066941, "autogenerated": false, "ratio": 2.222187204538292, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3434993898638292, "avg_score": null, "num_lines": null }
''' 7-plot-means.py ========================= AIM: Plots the means of 6-mean_sl.py ! Comparison for an arbitrary number of cases INPUT: files: - <orbit_id>_misc/orbits.dat - <orbit_id>_flux/flux_*.dat variables: see section PARAMETERS (below) OUTPUT: in all_figures/ : comparison for every orbit_id CMD: python 7-plot-means.py ISSUES: <None known> REQUIRES:- standard python libraries, specific libraries in resources/ - Structure of the root folder: * <orbit_id>_flux/ --> flux files * <orbit_id>_figures/ --> figures * <orbit_id>_misc/ --> storages of data * all_figures/ --> comparison figures REMARKS: <none> ''' ########################################################################### ### INCLUDES import numpy as np import pylab as plt import os from resources.routines import * from resources.TimeStepping import * import parameters as param import resources.figures as figures from matplotlib.ticker import MaxNLocator, MultipleLocator, FormatStrFormatter ########################################################################### ### PARAMETERS # Show plots and detailled analysis ? show = True # Fancy plots ? fancy = True save = False # what kind of average to plot ? nothing --> average of average # '_max' average of max # '_maxdir' maxdirection for each orbit average = '' orbit_ids = [1001] legends = ['Clean'] ########################################################################### ### INITIALISATION # File name fot the computed orbit file error_file = 'mean%s_sl.dat' % average if average=='': model=True else: model=False if fancy: figures.set_fancy() ########################################################################### fig=plt.figure() ax=plt.subplot(111) maxy = 0. miny = 0. for orbit_id, legend in zip(orbit_ids,legends): folder_flux, folder_figures, folder_misc = init_folders(orbit_id) data = np.loadtxt('%d_misc/%s' % (orbit_id, error_file), delimiter=',') dates = data[:,0]/param.last_orbits[orbit_id]*365. values= data[:,1] if np.amax(values) > maxy: maxy = np.amax(values) if np.min(values) < miny: miny = np.amin(values) dates = figures.convert_date(dates) ax.plot(dates, values,label=legend, linewidth=2) fig.autofmt_xdate() plt.ylim([miny*0.95,maxy*1.05]) plt.grid() ax.xaxis.grid(True,'major',linewidth=2) ax.yaxis.grid(True,'major',linewidth=2) plt.legend(loc='upper center') folder_figures= 'all_figures/' if average == '' : plt.ylabel(r'$\mathrm{Mean\ stray\ light\ flux\ }\left[\frac{\mathrm{ph}}{\mathrm{px}\cdot\mathrm{s}}\right]$') if average == '_max' : plt.ylabel(r'$\mathrm{Mean\ maximum\ stray\ light\ flux\ }\left[\frac{\mathrm{ph}}{\mathrm{px}\cdot\mathrm{s}}\right]$') if average == '_maxdir' : plt.ylabel(r'$\mathrm{Flux\ in\ worst\ direction}\left[\frac{\mathrm{ph}}{\mathrm{px}\cdot\mathrm{s}}\right]$') ########################################################################### ########################################################################### ########################################################################### ### Loading the value of n(alpha) values = np.loadtxt('704_misc/angle_usage_704_35_1-5322.dat') xo = values[:-1,0] yo = values[:-1,1] from scipy import stats slope, intercept, r_value, p_value, std_err = stats.linregress(xo,yo) s = slope c1 = intercept def ni(alpha,s=s,c1=c1): return s * alpha + c1 n=np.vectorize(ni) fig=plt.figure() ax=plt.subplot(111) maxy = 0. miny = 0. n_sampling = 55 angles_s = np.linspace(35,89,n_sampling) from scipy.optimize import leastsq orbit_ini = [1,441,891,1331,1771,2221,2661,3111,3551,3991,4441,4881] orbit_end = [441,891,1331,1771,2221,2661,3111,3551,3991,4441,4881,5322] def residuals(p, y, x): s,pw,c,s2,pw2 = p err = y - (s*np.power(x,pw) + s2*np.power(x,pw2) + c) return err def peval(x, p): return p[0]*np.power(x,p[1])+p[2] + p[3]*np.power(x,p[4]) p0 = [0.2, 1.0, -2.,0.,1.] ''' for oi, of in zip(orbit_ini, orbit_end): values = np.loadtxt('704_misc/angle_usage_704_35_%d-%d.dat' % (oi, of)) xo = values[:-1,0] yo = values[:-1,1] plsq = leastsq(residuals, p0, args=(yo, xo), maxfev=2500) ''' for orbit_id, legend in zip(orbit_ids,legends): ### Loading the PST values = np.loadtxt('pst/%d.dat' % orbit_id) angles = values[:,0] pst_val= values[:,1] yinterp = np.interp(angles_s, angles, pst_val) n_pst = n(angles_s) n_pst = yinterp * n_pst tot = n_pst.sum() print tot, legend folder_flux, folder_figures, folder_misc = init_folders(orbit_id) data = np.loadtxt('%d_misc/%s' % (orbit_id, error_file), delimiter=',') dates = data[:,0]/param.last_orbits[orbit_id]*365. values= data[:,1]/tot if np.amax(values) > maxy: maxy = np.amax(values) if np.min(values) < miny: miny = np.amin(values) dates = figures.convert_date(dates) ax.semilogy(dates, values,label=legend, linewidth=2) fig.autofmt_xdate() #plt.ylim([miny*0.95,maxy*1.05]) plt.grid() ax.xaxis.grid(True,'major',linewidth=2) ax.yaxis.grid(True,'major',linewidth=2) plt.legend(loc='upper center') plt.title('divided by n*PST') folder_figures= 'all_figures/' if average == '' : plt.ylabel(r'$\mathrm{Mean\ stray\ light\ flux\ }\left[\frac{\mathrm{ph}}{\mathrm{px}\cdot\mathrm{s}}\right]$') if average == '_max' : plt.ylabel(r'$\mathrm{Mean\ maximum\ stray\ light\ flux\ }\left[\frac{\mathrm{ph}}{\mathrm{px}\cdot\mathrm{s}}\right]$') if average == '_maxdir' : plt.ylabel(r'$\mathrm{Flux\ in\ worst\ direction}\left[\frac{\mathrm{ph}}{\mathrm{px}\cdot\mathrm{s}}\right]$') ########################################################################### ########################################################################### ########################################################################### if show: plt.show() # Saves the figure fname = '%sPST_mean_fluxes' % (folder_figures) fname = '%smean%s_fluxes' % (folder_figures,average) fname = '%smean%s_fluxes' % (folder_figures,average) if save: figures.savefig(fname,fig,fancy) print 'saved as', fname exit()
{ "repo_name": "kuntzer/SALSA-public", "path": "7a_plot_means.py", "copies": "1", "size": "5969", "license": "bsd-3-clause", "hash": 757400171365195000, "line_mean": 28.4039408867, "line_max": 143, "alpha_frac": 0.5885407941, "autogenerated": false, "ratio": 2.855980861244019, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3944521655344019, "avg_score": null, "num_lines": null }
# 7. Reverse Integer QuestionEditorial Solution My Submissions # Total Accepted: 166072 # Total Submissions: 698816 # Difficulty: Easy # Reverse digits of an integer. # Example1: x = 123, return 321 # Example2: x = -123, return -321 # Have you thought about this? # Here are some good questions to ask before coding. Bonus points for you if you have already thought through this! # If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100. # Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases? # For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ is_positive = True if(x < 0): is_positive = False x = -x r = int(str(x)[::-1]) if(r > 2147483647): return 0 if(is_positive): return r return -r
{ "repo_name": "huhuanming/leetcode", "path": "Python/reverse_integer.py", "copies": "1", "size": "1115", "license": "mit", "hash": -7330281477262549000, "line_mean": 30.8571428571, "line_max": 172, "alpha_frac": 0.6439461883, "autogenerated": false, "ratio": 3.8184931506849313, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49624393389849314, "avg_score": null, "num_lines": null }
7#!/sw/xc40/python/2.7.11/sles11.3_gnu5.1.0/bin/python import argparse from decimate import * import pprint DEBUG = False cmd_line = (" ".join(sys.argv)).split("--decimate") cmd_line = (" ".join(sys.argv)) if 'DPARAM' in os.environ.keys(): cmd_line = clean_line(os.environ['DPARAM']) + " " + cmd_line if len(cmd_line) >= 2: if cmd_line.find(" API ") > -1 or cmd_line.find("API,") > -1\ or cmd_line.find(",API") > -1: DEBUG = True class slurm_frontend(decimate): def __init__(self): decimate.__init__(self,app_name='decimate', decimate_version_required='0.5', app_version='0.1',extra_args=True) ######################################################################### def user_filtered_args(self): self.job_script = None index = 1 args = [] decimate_args = [] is_decimate = False is_job_parameter = False self.job_parameter = [] for f in sys.argv[1:]: if os.path.exists(f) and not is_decimate: self.job_script = f is_job_parameter = True continue if f == "--decimate": is_decimate = True continue if is_decimate: decimate_args = decimate_args + [f] elif is_job_parameter: self.job_parameter = self.job_parameter + [f] else: args = args + [f] index = index + 1 self.create_slurm_parser(DEBUG) self.slurm_args = self.slurm_parser.parse_args(args) if DEBUG: print('command line slurm_args: %s' % pprint.pformat(self.slurm_args)) if (self.slurm_args.help): print(HELP_MESSAGE) sys.exit(1) decimate_extra_config = [] if 'DPARAM' in os.environ.keys(): decimate_extra_config = clean_line(os.environ['DPARAM']).split(" ") if (self.slurm_args.decimate_help or decimate_extra_config == ["-h"]): return ['-h'] if not(self.job_script) and len(decimate_args) == 0: self.error('job script missing...', exit=True) if self.slurm_args.yalla: decimate_extra_config = decimate_extra_config + ['--yalla'] if self.slurm_args.filter: decimate_extra_config = decimate_extra_config + ['--filter',self.slurm_args.filter] if self.slurm_args.max_retry: decimate_extra_config = decimate_extra_config + \ ['--max-retry', "%s" % self.slurm_args.max_retry] if self.slurm_args.yalla_parallel_runs: decimate_extra_config = decimate_extra_config + \ ['--yalla-parallel-runs', "%s" % self.slurm_args.yalla_parallel_runs] if self.slurm_args.use_burst_buffer_size: decimate_extra_config = decimate_extra_config + ['--use-burst-buffer-size'] if DEBUG: print('job_file=/%s/\nargs=/%s/\nparams=/%s/\ndecimate_args=/%s/' % \ (self.job_script,args,self.job_parameter,decimate_extra_config + decimate_args)) return decimate_extra_config + decimate_args ######################################################################### def user_initialize_parser(self): self.parser.add_argument("-e", "--ends", type=int, help=argparse.SUPPRESS,default=-1) self.parser.add_argument("--banner", action="store_true", help=argparse.SUPPRESS, default=False) self.parser.add_argument("-np", "--no-pending", action="store_true", help='do not keep pending the log', default=True) ######################################################################### # submitting all the first jobs ######################################################################### def user_launch_jobs(self): # self.log_info('ZZZZZZZZZZZZZ setting max_retry to 1 ZZZZZZZZZZZZ') self.load() new_job = {} p_slurm_args = vars(self.slurm_args) self.slurm_args.script = os.path.abspath("%s" % self.job_script) # does the checking script exist? if self.slurm_args.check: if not(os.path.exists(self.slurm_args.check)): self.error('checking job script %s missing...' % self.slurm_args.check, exit=True) self.slurm_args.check = os.path.abspath("%s" % self.slurm_args.check) for k,v in p_slurm_args.items(): new_job[k] = v self.log_debug('job submitted:\n%s' % \ self.print_job(new_job,allkey=False,\ print_all=True,except_none=True), \ 4, trace='API') if self.args.yalla: new_job['yalla'] = self.args.yalla_parallel_runs if self.args.use_burst_buffer_size: new_job['burst_buffer_size'] = self.args.burst_buffer_size if self.args.use_burst_buffer_space: new_job['burst_buffer_space'] = self.args.burst_buffer_space (job_id, cmd) = self.submit_job(new_job) self.log_debug("Saving Job Ids...",1) self.save() print('Submitted batch job %s' % job_id) ######################################################################### # checking job correct completion ######################################################################### def check_job_old(self, what, attempt, task_id, running_dir, output_file, error_file, is_done, fix, job_tasks,step_tasks): self.log_info(("check_job(what=>%s<, attempt=>%s<, task_id=>%s<, running_dir=>%s<," +\ "output_file=>%s<, error_file=>%s<, is_done=>%s<, fix=>%s<, " +\ "job_tasks=>%s<,step_tasks=>%s<") % \ (what, attempt, task_id, running_dir, output_file, error_file, is_done, fix, job_tasks,step_tasks)) return SUCCESS ######################################################################### # checking job correct completion ######################################################################### def check_job(self,step, attempt, task_id,running_dir,output_file,error_file,\ is_job_completed,fix=True,job_tasks=None,step_tasks=None): s = "CHECKING step : %s attempt : %s task : %s " % \ (step,attempt,task_id) + "\n" + \ "job_tasks : %s \t step_tasks : %s" % (job_tasks,step_tasks) + "\n" +\ "Output file : %s" % (output_file) + "\n" +\ "Error file : %s" % (error_file) + "\n" +\ "Running dir : %s" % (running_dir) + "\n" self.log_info(s,4,trace='CHECK,USER_CHECK') done = 'job DONE' is_done = self.greps(done,output_file,exclude_patterns=['[INFO','[DEBUG']) if not(is_done): return FAILURE else: return SUCCESS if __name__ == "__main__": K = slurm_frontend() K.start()
{ "repo_name": "KAUST-KSL/decimate", "path": "slurm_frontend.py", "copies": "1", "size": "6591", "license": "bsd-2-clause", "hash": 1277133867381063400, "line_mean": 32.9742268041, "line_max": 99, "alpha_frac": 0.5307237142, "autogenerated": false, "ratio": 3.44177545691906, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.447249917111906, "avg_score": null, "num_lines": null }
"""7th update, adds an index to the api_key on games Revision ID: 563495edabd3 Revises: ea0a548215f Create Date: 2015-11-23 12:23:44.895973 """ # revision identifiers, used by Alembic. revision = '563495edabd3' down_revision = 'ea0a548215f' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_index(op.f('ix_games_api_key'), 'games', ['api_key'], unique=True) op.drop_constraint(u'games_api_key_key', 'games', type_='unique') op.alter_column('users', 'game_id', existing_type=sa.INTEGER(), nullable=True) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.alter_column('users', 'game_id', existing_type=sa.INTEGER(), nullable=False) op.create_unique_constraint(u'games_api_key_key', 'games', ['api_key']) op.drop_index(op.f('ix_games_api_key'), table_name='games') ### end Alembic commands ###
{ "repo_name": "Rdbaker/Rank", "path": "migrations/versions/563495edabd3_.py", "copies": "2", "size": "1040", "license": "mit", "hash": -8628744957737330000, "line_mean": 29.5882352941, "line_max": 80, "alpha_frac": 0.6403846154, "autogenerated": false, "ratio": 3.229813664596273, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9825867442803469, "avg_score": 0.008866167438561097, "num_lines": 34 }
7#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 15 13:38:48 2018 @author: BallBlueMeercat """ from scipy.integrate import odeint from scipy.interpolate import interp1d import firstderivs_cython as f import numpy as np firstderivs_functions = { 'rainbow':f.rainbow, 'niagara':f.niagara, 'kanangra':f.kanangra, 'waterfall':f.waterfall, 'stepfall':f.stepfall, 'exotic':f.exotic, 'late_intxde':f.late_intxde, 'heaviside_late_int':f.heaviside_late_int, 'heaviside_sudden':f.heaviside_sudden, 'late_int':f.late_int, 'expgamma':f.expgamma, 'txgamma':f.txgamma, 'zxgamma':f.zxgamma, 'gamma_over_z':f.gamma_over_z, 'zxxgamma':f.zxxgamma, 'gammaxxz':f.gammaxxz, 'rdecay_m':f.rdecay_m, 'rdecay_de':f.rdecay_de, 'rdecay_mxde':f.rdecay_mxde, 'rdecay':f.rdecay, 'interacting':f.interacting, 'LCDM':f.LCDM, 'rLCDM':f.rLCDM } def zodesolve(names, values, zpicks, model, plot_key, interpolate=False): """ Takes in: names = list of strings, names of parameters to be fitted; values = np.array, values of parameters; zpicks = np.ndarray of redshifts ; model = string, name of model being tested. """ all_zpicks = zpicks if len(zpicks) > 1048: # larger than pantheon sample interpolate = True zpicks = np.linspace(zpicks[0], zpicks[-1], num=100, endpoint=True) # Inserting 0 at the front of redshifts to use initial conditions. zpicks = np.insert(zpicks, 0, 0.0) # Standard cosmological parameters. H0 = 1.0 c = 1.0 c_over_H0 = 4167 * 10**6 # c/H0 in parsecs # Initial conditions at z = 0 (now). t0 = 0.0 # time a0 = 1.0 # scale factor z0 = 0.0 # redshift dl0 = 0.0 # luminosity distance rho_c0 = H0**2 # critical density # Pack up the initial conditions and interaction terms. int_terms = [] if model == 'rainbow': int_in = 12 elif model == 'niagara': int_in = 10 elif model == 'kanangra': int_in = 8 elif model == 'waterfall': int_in = 6 elif model == 'stepfall': int_in = 4 elif model == 'exotic': int_in = 3 elif model == 'LCDM' or model == 'rLCDM': int_in = len(values) else: int_in = 2 int_terms = values[int_in:] fluids = values[1:int_in] ombar_de0 = rho_c0/rho_c0 - np.sum(fluids) t0a0 = np.array([t0, a0]) de0z0dl0 = np.array([ombar_de0, z0, dl0]) # Remember that you lost precision when concatenating arr over using a list. v0 = np.concatenate((t0a0, fluids, de0z0dl0)) # Extracting the parsed mode of interaction. firstderivs_function = firstderivs_functions.get(model,0) assert firstderivs_function != 0, "zodesolve doesn't have this firstderivs_key at the top" # Call the ODE solver with all zpicks or cut_zpicks if len(zpicks) > 2000. vsol = odeint(firstderivs_function, v0, zpicks, args=(int_terms,H0), mxstep=5000000, atol=1.0e-8, rtol=1.0e-6) z = vsol[1:,-2] dl = vsol[1:,-1] * (1+z) # in units of dl*(H0/c) da = dl * (1.0+z)**(-2.0) # in units of dl*(H0/c) dlpc = dl * c_over_H0 # dl in parsecs (= vsol[dl] * c/H0) dapc = dlpc * (1.0+z)**(-2.0) # in units of pc dapc = dapc / 10**3 # in units of kpc # integrated_dlpc = dlpc plot_var = {} if plot_key: # Separate results into their own arrays: plot_var['t'] = vsol[1:,0] plot_var['a'] = vsol[1:,1] # Collecting fluids and their names for plotting: fluid_arr = np.zeros(((int_in), (len(zpicks)-1))) fluid_names = [] for i in range((int_in-1)): fluid_names.append(names[i+1]) fluid_arr[i] = vsol[1:,(i+2)] fluid_names.append('de_ombar') fluid_arr[-1] = vsol[1:,-3] plot_var['fluid_names'] = fluid_names plot_var['fluid_arr'] = fluid_arr plot_var['z'] = z plot_var['dl'] = dl # in units of dl*(H0/c) plot_var['int_terms'] = int_terms plot_var['da'] = da Hz = H0 * (np.sum(fluid_arr, axis=0))**(0.5) plot_var['Hz'] = Hz daMpc = dlpc/10**6 * (1.0+z)**(-2.0) # in units of dl in Mpc*(H0/c) dV = (daMpc**2 * c*z/Hz)**(1/3) # combines radial and transverse dilation plot_var['dV'] = dV if interpolate: # Interpolating results to give output for all zpicks: interp_dlpc = interp1d(zpicks[1:], dlpc) interp_da = interp1d(zpicks[1:], da) dlpc = interp_dlpc(all_zpicks) da = interp_da(all_zpicks) # return dlpc, da, z, integrated_dlpc, plot_var return dlpc, da, plot_var
{ "repo_name": "lefthandedroo/Cosmo-models", "path": "Models/zodesolve.py", "copies": "1", "size": "4884", "license": "mit", "hash": 465899834873995900, "line_mean": 30.5161290323, "line_max": 114, "alpha_frac": 0.5642915643, "autogenerated": false, "ratio": 2.867880211391662, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3932171775691662, "avg_score": null, "num_lines": null }
7#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 15 13:38:48 2018 @author: BallBlueMeercat """ from scipy.integrate import odeint import firstderivs_cython as f #import firstderivs as f firstderivs_functions = { 'exotic':f.exotic, 'late_intxde':f.late_intxde, 'heaviside_late_int':f.heaviside_late_int, 'late_int':f.late_int, 'expgamma':f.expgamma, 'txgamma':f.txgamma, 'zxgamma':f.zxgamma, 'gamma_over_z':f.gamma_over_z, 'zxxgamma':f.zxxgamma, 'gammaxxz':f.gammaxxz, 'rdecay_m':f.rdecay_m, 'rdecay_de':f.rdecay_de, 'rdecay_mxde':f.rdecay_mxde, 'rdecay':f.rdecay, 'interacting':f.interacting, 'LCDM':f.LCDM } def zodesolve(params, zpicks, firstderivs_key): """ Takes in: params = dictionary w/ key:value 'gamma':int/float = interaction constant; 'm':int/float = e_m(t)/ec(t0) at t=t0; zpicks = list of redshifts ; firstderivs_key = string, name of IVCDM model to use for model mag. """ # print('@@ zodesolve has been called') # Inserting 0 at the front of redshifts to allow initial conditions. zpicks = [0.0] + zpicks # Standard cosmological parameters. H0 = 1.0 c_over_H0 = 4167 * 10**6 # c/H0 in parsecs # Initial conditions at z = 0 (now). t0 = 0.0 # time a0 = 1.0 # scale factor z0 = 0.0 # redshift dl0 = 0.0 # luminosity distance rho_c0 = H0**2 # critical density ombar_m0 = params.get('m', 0) # e_m(z)/ec(z=0) gamma = params.get('gamma',0) zeta = params.get('zeta', 0) ombar_de0 = params.get('de', rho_c0/rho_c0 -ombar_m0) # e_de(z)/ec(z=0) ombar_r0 = 0.0 # ODE solver parameters: abserr = 1.0e-8 relerr = 1.0e-6 # Extracting the parsed mode of interaction. firstderivs_function = firstderivs_functions.get(firstderivs_key,0) if firstderivs_function == 0: print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@') print("firstderivs_functions dict didn't have the key zodeosolve asked for") print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@') if firstderivs_key == 'exotic': # Pack up the initial conditions and eq of state parameters. v0 = [t0, a0, ombar_m0, ombar_r0, ombar_de0, z0, dl0] # Call the ODE solver. vsol = odeint(firstderivs_function, v0, zpicks, args=(gamma,zeta,H0), atol=abserr, rtol=relerr) # Separate results into their own arrays: t = vsol[1:,0] a = vsol[1:,1] ombar_m = vsol[1:,2] ombar_r = vsol[1:,3] ombar_de = vsol[1:,4] z = vsol[1:,5] dl = vsol[1:,6] * (1+z) # in units of dl*(H0/c) dlpc = dl * c_over_H0 # dl in parsecs (= vsol[dl] * c/H0) # import matplotlib.pyplot as plt # plt.figure() # plt.xlabel('redshift $z$') # plt.ylabel(r'$\bar \Omega $') # plt.grid(True) # plt.plot(z, ombar_m, label=r'$\bar \Omega_{m}$', # color='xkcd:coral', linestyle=':') # plt.plot(z, ombar_de, label=r'$\bar \Omega_{DE}$', # color='xkcd:aquamarine') # plt.plot(z, ombar_r, label=r'$\bar \Omega_{r}$', # color='xkcd:black') # plt.legend() # plt.title(r'$\bar \Omega_{r}$ evolution, model = %s, $\gamma$ = %s' # %(firstderivs_key, gamma)) plot_var = t, dlpc, dl, a, ombar_m, ombar_r, gamma, zeta, ombar_de, ombar_m0, ombar_r0, ombar_de0 else: # Pack up the initial conditions and eq of state parameters. v0 = [t0, a0, ombar_m0, ombar_de0, z0, dl0] # Call the ODE solver. vsol = odeint(firstderivs_function, v0, zpicks, args=(gamma,H0), atol=abserr, rtol=relerr) # Separate results into their own arrays: t = vsol[1:,0] a = vsol[1:,1] ombar_m = vsol[1:,2] ombar_de = vsol[1:,3] z = vsol[1:,4] dl = vsol[1:,5] * (1+z) # in units of dl*(H0/c) dlpc = dl * c_over_H0 # dl in parsecs (= vsol[dl] * c/H0) plot_var = t, dlpc, dl, a, ombar_m, gamma, ombar_de, ombar_m0, ombar_de0 return dlpc, plot_var #def odesolve(params, zpicks, firstderivs_key): # """ # Takes in: # gamma = interaction constant; # m = e_m(t)/ec(t0) at t=t0; ## de = e_de(t)/ec(t0) at t=t0. # Returns: # z = numpoints number of redshifts zmin<z<zmax; # dlpc = luminosity distance in pc. # # """ ## print('@@ zodesolve has been called') # # # Inserting 0 at the front of redshifts to allow initial conditions. # zpicks = [0.0] + zpicks # # # Standard cosmological parameters. # H0 = 1 # c_over_H0 = 4167 * 10**6 # c/H0 in parsecs # # # Initial conditions at z = 0 (now). # dl0 = 0 # luminosity distance # rho_c0 = H0**2 # critical density # ombar_m0 = params.get('m', 0) # e_m(z)/ec(z=0) # gamma = params.get('gamma',0) # ombar_de0 = params.get('de', rho_c0/rho_c0 -ombar_m0)# e_de(z)/ec(z=0) # # # ODE solver parameters: # abserr = 1.0e-8 # relerr = 1.0e-6 # # # Pack up the initial conditions and eq of state parameters. # v0 = [ombar_m0, ombar_de0, dl0] # # # Extracting the parsed mode of interaction. # firstderivs_function = firstderivs_functions.get(firstderivs_key,0) # if firstderivs_function == 0: # print("firstderivs_functions dict didn't have the key zodeosolve asked for") # # # Call the ODE solver. # vsol = odeint(firstderivs_function, v0, zpicks, args=(gamma,H0), # atol=abserr, rtol=relerr) # # # Separate results into their own arrays: # z = np.asarray(zpicks) # z = z[1:] # ombar_m = vsol[1:,0] # ombar_de = vsol[1:,1] # dl = vsol[1:,2] * (1+z) # in units of dl*(H0/c) # dlpc = dl * c_over_H0 # dl in parsecs (= vsol[dl] * c/H0) # # plot_var = dlpc, dl, ombar_m, gamma, ombar_de, ombar_m0, ombar_de0 # # return dlpc, plot_var
{ "repo_name": "lefthandedroo/Cosmo-models", "path": "zprev versions/Models_py_backup/Models backup/zodesolve.py", "copies": "1", "size": "6361", "license": "mit", "hash": -2541292502403166700, "line_mean": 33.3891891892, "line_max": 105, "alpha_frac": 0.5277472096, "autogenerated": false, "ratio": 2.709114139693356, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3736861349293356, "avg_score": null, "num_lines": null }
7#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 15 13:38:48 2018 @author: BallBlueMeercat """ from scipy.integrate import odeint import firstderivs_cython as f import numpy as np import matplotlib.pyplot as plt firstderivs_functions = { 'rainbow':f.rainbow, 'kanangra':f.kanangra, 'waterfall':f.waterfall, 'stepfall':f.stepfall, 'exotic':f.exotic, 'late_intxde':f.late_intxde, 'heaviside_late_int':f.heaviside_late_int, 'heaviside_sudden':f.heaviside_sudden, 'late_int':f.late_int, 'expgamma':f.expgamma, 'txgamma':f.txgamma, 'zxgamma':f.zxgamma, 'gamma_over_z':f.gamma_over_z, 'zxxgamma':f.zxxgamma, 'gammaxxz':f.gammaxxz, 'rdecay_m':f.rdecay_m, 'rdecay_de':f.rdecay_de, 'rdecay_mxde':f.rdecay_mxde, 'rdecay':f.rdecay, 'interacting':f.interacting, 'LCDM':f.LCDM, 'rLCDM':f.rLCDM } def zodesolve(names, values, zpicks, model, plot_key): """ Takes in: names = list of strings, names of parameters to be fitted; values = np.array, values of parameters; zpicks = np.ndarray of redshifts ; model = string, name of model being tested. """ # Inserting 0 at the front of redshifts to use initial conditions. zpicks = np.insert(zpicks, 0, 0.0) # Standard cosmological parameters. H0 = 1.0 c = 1.0 c_over_H0 = 4167 * 10**6 # c/H0 in parsecs # Initial conditions at z = 0 (now). t0 = 0.0 # time a0 = 1.0 # scale factor z0 = 0.0 # redshift dl0 = 0.0 # luminosity distance rho_c0 = H0**2 # critical density # Pack up the initial conditions and interaction terms. int_terms = [] if model == 'rainbow': int_in = 12 elif model == 'kanangra': int_in = 8 elif model == 'waterfall': int_in = 6 elif model == 'stepfall': int_in = 4 elif model == 'exotic': int_in = 3 elif model == 'LCDM' or model == 'rLCDM': int_in = len(values) else: int_in = 2 int_terms = values[int_in:] fluids = values[1:int_in] ombar_de0 = rho_c0/rho_c0 - np.sum(fluids) t0a0 = np.array([t0, a0]) de0z0dl0 = np.array([ombar_de0, z0, dl0]) # Remember that you lost precision when concatenating arr over using a list. v0 = np.concatenate((t0a0, fluids, de0z0dl0)) # Extracting the parsed mode of interaction. firstderivs_function = firstderivs_functions.get(model,0) assert firstderivs_function != 0, "zodesolve doesn't have this firstderivs_key at the top" # Call the ODE solver. vsol = odeint(firstderivs_function, v0, zpicks, args=(int_terms,H0), mxstep=5000000, atol=1.0e-8, rtol=1.0e-6) z = vsol[1:,-2] dl = vsol[1:,-1] * (1+z) # in units of dl*(H0/c) da = dl * (1.0+z)**(-2.0) # in units of dl*(H0/c) dlpc = dl * c_over_H0 # dl in parsecs (= vsol[dl] * c/H0) dapc = dlpc * (1.0+z)**(-2.0) # in units of pc dapc = dapc / 10**3 # in units of kpc # theta = dl/da # print('theta',theta[-1]) # print(model,'redshift = ',z[-1],'da =',da[-1]) # plt.figure() # plt.title('Angular diameter distance vs redshift') # plt.xlabel('z') # plt.ylabel('D_A') # plt.plot(z, da, label='da') # plt.legend() # # plt.figure() # plt.title('Angular diameter vs redshift') # plt.xlabel('z') # plt.ylabel(r'$\theta$') # plt.plot(z, theta, label='theta') # plt.legend() # plt.show() plot_var = {} if plot_key: # Separate results into their own arrays: plot_var['t'] = vsol[1:,0] plot_var['a'] = vsol[1:,1] # Collecting fluids and their names for plotting: fluid_arr = np.zeros(((int_in), (len(zpicks)-1))) fluid_names = [] for i in range((int_in-1)): fluid_names.append(names[i+1]) fluid_arr[i] = vsol[1:,(i+2)] fluid_names.append('de_ombar') fluid_arr[-1] = vsol[1:,-3] plot_var['fluid_names'] = fluid_names plot_var['fluid_arr'] = fluid_arr plot_var['z'] = z plot_var['dl'] = dl # in units of dl*(H0/c) plot_var['int_terms'] = int_terms plot_var['da'] = da # plt.figure() # plt.title('Angular diameter distance evolution') # plt.xlabel('z') # plt.ylabel(r'$ \left( \frac{H_0}{c} \right) d_A $', fontsize=15, labelpad=10) # plt.plot(z, da) Hz = H0 * (np.sum(fluid_arr, axis=0))**(0.5) plot_var['Hz'] = Hz daMpc = dlpc/10**6 * (1.0+z)**(-2.0) # in units of dl in Mpc*(H0/c) dV = (daMpc**2 * c*z/Hz)**(1/3) # combines radial and transverse dilation plot_var['dV'] = dV # plt.figure() # plt.title(r'$d_V$ evolution') # plt.xlabel('z') # plt.ylabel(r'$ d_V (z)$ [Mpc]') # plt.grid(True) # plt.plot(z, dV) # Dv = ((1+z)**2 * daMpc**2 * c*z/Hz)**(1/3) # plt.figure() # plt.title(r'$D_v$ evolution') # plt.xlabel('z') # plt.ylabel(r'$ D_v (z)$ [Mpc]') # plt.grid(True) # plt.plot(z, Dv) # # Calculating the sound horizon # ombar_m = vsol[1:,2] # ombar_baryon = ombar_m*0.04 #0.0125 ## ombar_baryon = values[(fluid_in-1)] # s = 44.5 * np.log(9.83 / ombar_m) / (1 +10 * ombar_baryon**(3/4))**(1/2) # plt.figure() # plt.title('Sound horizon') # plt.xlabel(r'$z$') # plt.ylabel('Physical length in Mpc') # plt.grid(True) # plt.plot(z, s, label=r'$s_H$') # plt.legend() plt.show() return dlpc, da, plot_var
{ "repo_name": "lefthandedroo/Cosmo-models", "path": "Models/zodesolve backup.py", "copies": "1", "size": "5775", "license": "mit", "hash": -5447164605442512000, "line_mean": 30.0537634409, "line_max": 114, "alpha_frac": 0.5383549784, "autogenerated": false, "ratio": 2.7292060491493384, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3767561027549339, "avg_score": null, "num_lines": null }
7#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 15 13:38:48 2018 @author: BallBlueMeercat """ from scipy.integrate import odeint import zfirstderivs # Standard cosmological parameters. c_over_H0 = 4167 * 10**6 # c/H0 in parsecs def zodesolve(gamma,m,de,zpicks): """ Takes in: gamma = interaction constant; m = e_m(t)/ec(t0) at t=t0; de = e_de(t)/ec(t0) at t=t0. Returns: z = numpoints number of redshifts zmin<z<zmax; dlpc = luminosity distance in pc. """ # print('@@ zodesolve has been called') # Initial conditions at z = 0. t0 = 0 a0 = 1.0 # scale factor e_dash0m = m # e_m(t)/ec(t0) e_dash0de = de # e_de(t)/ec(t0) z0 = 0 dl0 = 0 # ODE solver parameters: abserr = 1.0e-8 relerr = 1.0e-6 # Pack up the initial conditions and eq of state parameters. v0 = [t0, a0, e_dash0m, e_dash0de, z0, dl0] # Call the ODE solver. maxstep=5000000 added later to try and avoid vsol = odeint(zfirstderivs.zfirstderivs, v0, zpicks, args=(gamma,), atol=abserr, rtol=relerr, mxstep=5000000) # Separate results into their own arrays: t = vsol[:,0] a = vsol[:,1] e_dashm = vsol[:,2] e_dashde = vsol[:,3] z = vsol[:,4] dl = vsol[:,5] * (1+z) # in units of dl*(H0/c) dlpc = dl * c_over_H0 # dl in parsecs (= vsol[dl] * c/H0) return t, dlpc, dl, a, e_dashm, e_dashde
{ "repo_name": "lefthandedroo/Cosmo-models", "path": "zprev versions/zodesolve copy.py", "copies": "1", "size": "1511", "license": "mit", "hash": 3986755388088950300, "line_mean": 25.5087719298, "line_max": 72, "alpha_frac": 0.5598941099, "autogenerated": false, "ratio": 2.693404634581105, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3753298744481105, "avg_score": null, "num_lines": null }