Suggested SolutionsPractice AssignmentsLife Path Number# Data Input File Namefn ='LPNin.txt'## Function to reduce digits to single digit and return the single digit## Unless it is a modulo of 11, then just return the numberdef reduceDigits(digits): dn = int(digits) #print(digits) while dn > 9 and dn%11 != 0: dz = 0 for c in str(dn): #print(f'digit= {c}') dz += int(c) dn = dz #print(f'+{dn:4d}',end="") return dndef processRec(rec): lpn = 0 dt = rec dl = dt.split('/') ## break down date by / into a list (dl) for dd in dl: ## for each component (dd) of date lpn += reduceDigits(dd) ## if resulting lpn is not single digit - reduceDigits it if lpn>9: lpn=reduceDigits(lpn) print(f'{lpn} {dt}')## Read Input from Filewith open(fn,'r') as f: n = int(f.readline()) # get number of loops in first line # now read the rest for rec in f: nl = processRec(rec.strip()) ## process Record but first get rid of <CR><LF> at end of lineVersion 2: # This routine adds up digits in def addUpDigits(num): strNum=str(num) num=int(strNum) sumDigits=0 #if number passed in <10, just return it if num<10: return num #if num is a special number, return it if num in (11,22,33): return num #if number > 10 then add up digits for char in strNum: num = int(char) sumDigits += num #take the sum and pass it back into this function to reduce the digits return addUpDigits(sumDigits) #----------------------------------------------------------------# def main(): inputDate = input("Enter date: ") #inputDate = "23/4/1994" dateArray = inputDate.split('/') print(dateArray) #for each part of the date - add up all the digits bigTotal = 0 for element in dateArray: bigTotal += addUpDigits(element) print(f"{element} = {bigTotal}") #add up all the digits of the final total too bigTotal = addUpDigits(bigTotal) print(bigTotal) main() Detecting Cycles#-------------------------------------------------------------------------------# Name: Detecting Cycles# Purpose:## Author: jlai## Created: 08/05/2018# Copyright: (c) jlai 2018# Licence: <your licence>#-------------------------------------------------------------------------------## Test data for AssignmenttestData = [ [1,7,43,2], ##devt test data, not assessment test data [1,3,100,11], [5,5,8888,88], [1,9,666,10], [1,1,31,1]]## INPUT: a,b,c,d## PROCESS: generates next number in sequence## OUTPUT: ddef next_val(a,b,c,d): return (int(a) * int(d)*int(d) + int(b))%int(c)## PROCESS: generate a sequence of numbers until a cycle is founddef doTest(a,b,c,d): cycleFound = False nums = [] pos = 0 dict = {} repeat = 0 cycle = 0 string = 0 while not cycleFound: nums.append(d) if d in dict: cycleFound = True cycle = pos - dict[d] repeat = d string = dict[d] break else: dict[d] = pos d = next_val(a,b,c,d) pos +=1 print(f"repeat = {repeat}, string = {string}, cycle = {cycle}\n") #print(f"{nums} {dict}")## Run multiple tests based on test data listt = 1for a,b,c,d in testData: print(f"Test {t}: a={a}, b={b}, c={c}, d={d}") doTest(a,b,c,d) t+=1doors = []max = 64doors.append("blank") #ignore 0th elementfor i in range(max): doors.append(0) # adds doors 1-64 (as doors[0] already added)print(" ",doors)#each monk comes infor monk in range(max): # put monk name in 0th index doors[0]=f"monk {monk+1}" # for door in range(monk+1,max+1,monk+1): doors[door] = abs(doors[door]-1) #flips a door open/closed to closed/open # print(monk+1, doors, "Open={}".format(doors.count(1)))Palindromesimport re ## Regular Expressions search for patterns in stringsfn = "palindromes2.txt"def checkPal(phrase): ''' INPUT: Phrase - line read with all spaces and punctuations removed PROCESS: Start checking phrase character by character from left and right ends If left & right chars are all the same then Palindrome If not the same, then not a palindrome OUTPUT: Yes - if all left chars same as right chars No - if they are not the same ''' wl = len(phrase) left = 0 if wl <= 1: return "Yes" else: right = wl - 1 while left <= right: if phrase[left]!= phrase[right]: return "No" left += 1 right -= 1 return "Yes"with open(fn,'r') as f: ## with open - auto closes file at end for line in f.readlines(): line = line.rstrip('\r\n') ## remove any <CR><LF> on each line read phrase = re.sub(r'\W+', '', line).lower() ##strip all non char symbols and lowercase them isPal = checkPal(phrase) ##returns Yes or No print(f'{isPal.rjust(3)} "{line}"')Two Out of Three Ain't Bad Consider the following product of fractions: ![]() For large k, Pk converges slowly to 2/3. Write a program that determines the largest value of k for which Pk > 0.6666667000... ReferencesNick's Mathematical Puzzles, number 15 limit = 0.6666667000 def calcTerm(k): kcube = k**3 n = kcube-1 d = kcube+1 term =(n/d) #print(f"{n}/{d} * ",end="") return term pk=1 k = 1 ## for 7/9 to be the first element, k = 2, i.e 2^3 = 8-1=7, 8+1=9 while True: k +=1 pk = pk*calcpk(k) if pk<=limit: break print(f" {k} {pk:.15f}") #print(f" {k} {pk}") Plurals#-------------------------------------------------------------------------------# Name: plurals# Purpose:## Author: jlai## Created: 19/05/2018# Copyright: (c) jlai 2018# Licence: <your licence>#-------------------------------------------------------------------------------# Data Input File Namefn ='plurals.txt'def quantity(q): qi = int(q) plural=False if qi>1: plural=True elif qi==0: plural=True q="no" else: q="one" return plural, qdef plurals(word): if word.endswith(("s", "x", "z", "ch","sh")): word +="es" elif word.endswith("o"): if word[len(word)-2] not in ('aeiouy'): word +="es" else: word += "s" elif word.endswith("y"): if word[len(word)-2] not in ('aeiouy'): word = word[:len(word)-1]+"ies" else: word += "s" elif word.endswith("fe"): if word[len(word)-3] != "f": word = word[:len(word)-2]+"ves" else: word += "s" elif word.endswith("f"): if word[len(word)-1]!="f": word = word[len(word)-1]+"ves" else: word += "s" else: word += "s" return word#Process each data record as followsdef processRec(rec): q, word = rec.lower().split(' ') plural, q = quantity(q) if plural: word = plurals(word) print(f"{q} {word}")## Read Input from Filewith open(fn,'r') as f: n = int(f.readline()) # get number of loops in first line # now read the rest for rec in f: ## process Record but first strip <CR><LF> at end of line nl = processRec(rec.strip())Word Isomorphsimport sys,re,randomdef getPattern(word): patt = "" for i in range(len(word)): ch = word[i] rest=word[i+1:] x = rest.find(ch)+1 if x>0: patt += f"+{x} " else: patt += "0 " #print(ch,rest,x) return pattdef isomorphs(w1,w2): if len(w1) != len(w2): print(f"{w1}, {w2} have different lengths") else: p1 = getPattern(w1) p2 = getPattern(w2) if p1!=p2: print(f"{w1}, {w2} are not isomorphs") else: print(f"{w1}, {w2} are isomorphs with repetition pattern {p1}")def processFile(): fn = "isomorph.txt" M = 0 k = 0 T = 0 days = 0 try: with open(fn,'r') as f: n = int(f.readline()) # read the first rec which contains count of records #print(f"Processing: {n}") for line in f: words = line.split() isomorphs(words[0],words[1]) except: print("Error: {}".format(sys.exc_info()[0]))processFile()#------------------------------------------------------------------------------- # Name: zigzag # Purpose: # # Author: jlai # # Created: 14/06/2019 # Copyright: (c) jlai 2019 # Licence: <your licence> #------------------------------------------------------------------------------- la = '\u2190' ra = '\u2192' la = '<-' ra = '->' # FYI:TASK SAYS THAT A ROW IS EVEN IF NUMBER OF ELEMENTS ARE EVEN, # SINCE ARRAYS IN PYTHON START FROM 0, ROW 1 is ROW[0] # SO EVEN ROW (ZIG) IS ROW AN ODD ROW NUMBER !!!!! def isZig(row): #row number is odd - then zig (rows starts from 0) row = float(row) return row != int(row/2)*2 #determines if odd = Zig # input: # prev - previous line so we can generate next current # row - determines number of iterations = row + 1 (row = 1, 2 iterations) # process: # left to right = zero to num of rows - 1 # start with 0, add previous row to current number to generate next number # add each new number to array # output: # return array def doZig(prev,row): l = len(prev) new=[0] num = 0 for x in range(0,l,1): num = num + prev[x] new.append(num) #print(new) return new # input: # prev - previous line so we can generate next current # row - determines number of iterations = row + 1 (row = 1, 2 iterations) # process: # left to right = zero to num of rows - 1 # start with 0, add previous row to current number to generate next number # add each new number to array # output: # return array def doZag(prev,row): l = len(prev) new=[0] num = 0 for x in range(l-1,-1,-1): #print(x) num = num + prev[x] new.insert(0,num) #print(new) return new # repeat for each row - growing row by 1 - until reached max number of rows max=8 #number of rows to complete current = [1] final = [] final.append(current) #array of arrays for each line of triangle for row in range(1,max,1): if isZig(row): current=doZig(current,row) else: current=doZag(current,row) final.append(current) #print out in pyramid # width = length of array # center = round(width/2 width = len(final) left=True for line in final: lw = len(line) print((width-lw)*f"{' ':5s}",end='') for element in line: lw -= 1 print(f"{element:^5d}", end='') if lw>0: print(f"{la:^5s}" if left else f"{ra:^5s}", end='') print() left=not left |

