## p.p1 function to print out estimation of pi

p.p1 {margin: 0.

0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #4bd156; background-color: #000000}p.p2 {margin: 0.

We Will Write a Custom Essay Specifically
For You For Only \$13.90/page!

order now

0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica; background-color: #000000; min-height: 14.

0px}p.p3 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #ffffff; background-color: #000000}p.p4 {margin: 0.

0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #ff4647; background-color: #000000}p.

p5 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.

0px Menlo; color: #ffffff; background-color: #000000; min-height: 13.0px}p.p6 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #de38a5; background-color: #000000}p.

p7 {margin: 0.0px 0.0px 0.0px 0.

0px; font: 11.0px Menlo; color: #8b87ff; background-color: #000000}span.s1 {color: #de38a5}span.s2 {color: #ffffff}span.s3 {color: #8b87ff}span.

s4 {color: #ff4647}############## QUESTION 1 ####################used to generate random pointsimport random#takes in user inputdecimalPlaces = int(input(“Enter the number of decimal places you want to estimate to : “))def estimate_pi(precision):        #deals with bad user input and does not run function until it receives a valid input    if not (precision > 0):        raise ArithmeticError(“%s: Must be a positive integer.” %(precision))    try:        precision += 1    except TypeError as error:        print(“Must be an integer”, error)            numberPoints = 10**precision        #generates dimensions of square and circle involved    sideLength = 10**5    centre = sideLength/2,sideLength/2        #function to check whether point has landed inside the circle    def in_circle(point):       x = point0       y = point1       centre_x = centre0       centre_y = centre1       radius = sideLength/2       return (x – centre_x)**2 + (y – centre_y)**2 < radius**2        #records total number of points tried and total number of those that ended up in the circle    count = inside_count = 0    for i in range(numberPoints):        point = random.randint(1,sideLength),random.randint(1,sideLength)        if in_circle(point):            inside_count += 1        count += 1    #applys Monte Carlo method formula to find estimation of pi    pi = (inside_count / count) * 4    print(pi)#calls function to print out estimation of pi to desired precisionestimate_pi(decimalPlaces)############## QUESTION 2 ###################'''to run the code below, you will need to download the english_quadgram.txt.zip file from    https://github.com/torognes/enigma/blob/master/english_quadgrams.

txtunzip and store it in the same directory as the following cipher python file code”’#allows scoring of text using n-gram probabilitiesfrom math import log10class ngram_score(object):    def __init__(self,ngramfile,sep=’ ‘):        #load a file containing ngrams and counts and calculate log probabilities        self.ngrams = {}        for line in open(ngramfile):            key,count = line.split(sep)            self.ngramskey = int(count)        self.

L = len(key)        self.N = sum(self.ngrams.values())        #calculate log probabilities        for key in self.ngrams.keys():            self.

ngramskey = log10(float(self.ngramskey)/self.N)        self.floor = log10(0.01/self.N)        #this function computes the score of the text    def score(self,text):        score = 0        ngrams = self.

ngrams.__getitem__        for i in range(len(text)-self.L+1):            if (texti:i+self.L in self.ngrams):                score += ngrams(texti:i+self.

L)            else:                score += self.floor    return score#importing relevant modules to run the codefrom pycipher import SimpleSubstitution as SimpleSubimport randomimport re#loads our quadgram statisticsfitness = ngram_score(‘english_quadgrams.txt’)text= input(“Enter text to be deciphered : “)#deals with bad user input by converting all of the input to upper casetext = re.sub(‘^A-Z’,”,text.upper())def break_cipher(text):    maxkey = list(‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’)    maxscore = -99e9    parentscore,parentkey = maxscore,maxkey:    print (“Substitution Cipher solver, you may have to wait several iterations”)    print (“for the correct result. Press ctrl+c to exit program.”)    #keep going until we are killed by the user    i = 0    while (1):        i = i+1        #using in-built functions from pycipher modules        random.shuffle(parentkey)        deciphered = SimpleSub(parentkey).decipher(text)        parentscore = fitness.score(deciphered)        count = 0        while (count < 1000):            a = random.randint(0,25)            b = random.randint(0,25)            child = parentkey:            #swap two characters in the child            childa,childb = childb,childa            deciphered = SimpleSub(child).decipher(text)            score = fitness.score(deciphered)            #if the child was better, replace the parent with it            if (score > parentscore):                parentscore = score                parentkey = child:                count = 0            count = count+1        #keep track of best score seen so far        if (parentscore>maxscore):            maxscore,maxkey = parentscore,parentkey:            ss = SimpleSub(maxkey)            print (‘    best key: ‘+”.join(maxkey))            print (‘    plaintext: ‘+ss.decipher(text))break_cipher(text)############## QUESTION 3 ###################exp = input(“Enter your simple expression : “)#this function splits up the expression from the user, in to a list of strings containing each characterdef tokenize(exp):    element = exp.split()    return element#calling the tokenize function to initialize the listlistOfElements = tokenize(exp)#returns value of calculationdef calculate(listOfElements):        #defining other characters other than numbers that may be part of the expression    op1 = ‘+’    op2 = ‘-‘    op3 = ‘*’    op4 = ‘/’    openB = ‘(‘    closeB = ‘)’            #operation functions to carry out calculations on strings    def add(x,y):        return int(x) + int(y)    def subtract(x,y):        return int(x) – int(y)    def multiply(x,y):        return int(x) * int(y)    def divide(x,y):        return int(x) / int(y)        #returns the index of all open brackets and closed brackets in the list of elements which we just initialized    openBPositions = i for i, x in enumerate(listOfElements) if x == “(”    closeBPositions = i for i, x in enumerate(listOfElements) if x == “)”        #uses operation functions to evaluate and expression    def evaluateExpression(newList):        if (len(newList) == 1):            return int(newList0)        if (newList1 == op1):            return add(newList0, newList2)        if (newList1 == op2):            return subtract(newList0, newList2)        if (newList1 == op3):            return multiply(newList0, newList2)        if (newList1 == op4):            return divide(newList0, newList2)    #finds the result of a “simple expression”    #we define a simple expression so that there are only 5 elements left in the list    #e.g ‘(‘, ‘2’, ‘+’, ‘3’, ‘)’    def evaluateSimple(listOfElements):        listOfElements.remove(‘(‘)        listOfElements.remove(‘)’)        answer = evaluateExpression(listOfElements)        return answer    #simplifies a “longer expression” in to a more simple one    def convertToSimple(listOfElements):                #find index of first open bracket that can evaluate an expression        for position in range(len(listOfElements)):            if ((listOfElementsposition == openB) and (listOfElementsposition + 1 == ‘0’ or ‘1’ or ‘2’ or ‘3’ or ‘4’ or ‘5’ or ‘6’ or ‘7’ or ‘8’ or ‘9’)):                indexFirstOpenBracket = position                #find index of next closed bracket to complete the expression        pos = 0        for element in listOfElements:            pos = pos + 1            if( element == closeB ):                indexNextClosedBracket = pos – 1                break        #try and evaluate expression in between indicies of said brackets        subList = listOfElementsindexFirstOpenBracket + 1 : indexNextClosedBracket        value = evaluateExpression(subList)        #remove brackets and anything in between from the list        del listOfElementsindexFirstOpenBracket: indexNextClosedBracket + 1        #replace this with the value found        listOfElements.insert(indexFirstOpenBracket,value)        return listOfElements            #keeps calling convertToSimple function until a “simple expression” is reached    def subCalculate(listOfElements):        while (len(listOfElements) != 5):            return convertToSimple(listOfElements)        subCalculate(listOfElements)        return evaluateSimple(listOfElements)#calls calculate function to print out resultprint(calculate(listOfElements))

x Hi!
I'm Mary!

Would you like to get a custom essay? How about receiving a customized one?

Check it out