""" Authors: CS111 faculty Consulted: Purpose: CS111 Lab 5 Solutions: loops Filename: lab05.py """ # -------------------------------------------------------------- import random # to generate random star placement # --------------------------------------------------- # -------------------- PART 1 ----------------------- # --------------------------------------------------- def box(size, char): '''Draws a box of size using given char''' for side in range(size): print(char * size) def boxWhile(size, char): '''Draws a box of size using given char''' rows = 0 while rows < size: print(char*size) rows +=1 def rect(width, height, char): '''Draws a rectangle that is height x width dimensions using given char''' for length in range(height): print(char * width) def rectWhile(width, height, char): '''Draws a rectangle that is height x width dimensions using given char''' rows = 0 while rows < height: print(char * width) rows +=1 def triangle(height, char): '''Draws a triangle that increases in length with each successive line so that the final line of the triangle contains height characters''' for bar in range(1,height+1): # need height + 1 to get the full height print(char * bar) def triangleWhile(height, char): '''Draws a triangle that increases in length with each successive line so that the final line of the triangle contains height characters''' row = 1 while row <= height: print(char * row) row += 1 def findMultiplesOf(start, stop, factor): '''Prints all the multiples of factor between start and stop, inclusive''' count = 0 for num in range(start, stop+1): if num % factor == 0: print(num) count +=1 print('There are',count,'multiples of',factor,'between',start,'and',str(stop)+'.') def findMultiplesOfWhile(start, stop, factor): '''Prints all the multiples of factor between start and stop, inclusive''' count = 0 num = start while num <= stop: if num % factor == 0: print(num) count +=1 num += 1 print('There are',count,'multiples of',factor,'between',start,'and',str(stop)+'.') def addOdds(num): '''Returns the sum of odd numbers up to and including the given number''' result = 0 for i in range(1,num+1): if i%2==1: result += i return result def addOddsWhile(num): '''Returns the sum of odd numbers up to and including the given number''' result = 0 currentNum = 1 while currentNum <= num: if currentNum % 2 == 1: result += currentNum currentNum += 1 return result def makeN(height, char): '''Draws a capital letter N made up of given char with given height. The entire width of the capital letter N is height + 2. There is always a char in the leftmost column and also in the rightmost column, and there is a third character and (height-1) spaces in between. The third character moves progressively to the right with each successive line to form the slant of the N. ''' for bar in range(height): spaceBefore = bar spaceAfter = height - bar - 1 # note: spaceBefore + spaceAfter = height - 1 print(char + ' '* spaceBefore + char + ' ' * spaceAfter + char) def makeNWhile(height, char): '''Draws a capital letter N made up of given char with given height. The entire width of the capital letter N is height + 2. There is always a char in the leftmost column and also in the rightmost column, and there is a third character and (height-1) spaces in between. The third character moves progressively to the right with each successive line to form the slant of the N. ''' row = 0 while row < height: spaceBefore = row spaceAfter = height - row - 1 print(char + ' '* spaceBefore + char + ' ' * spaceAfter + char) row += 1 # --------------------------------------------------- # -------------------- PART 2 ----------------------- # --------------------------------------------------- def getWordValue(word): """Returns value of a word, where each vowel (a,e,i,o,u) counts as 5 and each consonant counts as 1""" total= 0 for letter in word: letter = letter.lower() # make the letter lower case if letter in 'aeiou': total += 5 elif letter in 'bcdfghjklmnpqrstvwxyz': # put all consonants in one string total += 1 return total print('Testing getWordValue') print(getWordValue('hello')) print(getWordValue('I')) print(getWordValue('ouch')) print(getWordValue('WELLESLEY')) print(getWordValue('Go 123 Wellesley!!!!')) #----------------------------------------------------- # Writing string functions def starify(word): """Return a new string containing the original word with stars after each letter""" stars = "" for letter in word: stars = stars + letter + '*' return stars print('Testing starify') print(starify('OMG')) print(starify('wicked')) print(starify('Starry')) # -------------------------------------------------------------- # This is a BUGGY version of betterStarify because if the word # happens to contain the last letter of the word more than once, # e.g. "wow" or "tent" or "roadrunner", then any occurrence # of the last letter would not get a '*' after it, e.g. "wo*w" # or "te*n*t" or "ro*a*d*ru*n*n*e*r". def betterStarifyBuggy(word): """Return a new string containing the original word with stars between each letter (no star at the end)""" stars = "" for letter in word: if letter != word[-1]: # not the last letter stars = stars + letter + '*' else: stars = stars + letter return stars # If word happens to be empty, then this version will generate an error # e.g. betterStarify1("") because the line indicated below accesses # the last character of an empty string def betterStarify1(word): """Return a new string containing the original word with stars between each letter (no star at the end)""" # Special case to handle empty string, since ''[-1] gives index error. if word == '': return '' stars = "" # Put star after the letter at every index but last # Note that len(word) - 1 is the index of the last letter in the word for index in range(len(word) - 1): stars = stars + word[index] + '*' # Add last letter w/o star stars = stars + word[-1] # will generate error if word is empty string return stars # This version handles the special case if word is the empty string def betterStarify2(word): """Return a new string containing the original word with stars between each letter (no star at the end)""" # Special case to handle empty string, since ''[-1] gives index error. if word == '': return '' stars = "" # Put star after the letter at every index but last for letter in word[0:-1]: stars = stars + letter + '*' # Add last letter w/o star stars = stars + word[-1] return stars print('Testing betterStarify') print(betterStarifyBuggy('OMG')) print(betterStarifyBuggy('wicked')) print(betterStarifyBuggy('Starry')) print(betterStarifyBuggy('bob')) print(betterStarifyBuggy('')) print('Testing betterStarify1') print(betterStarify1('OMG')) print(betterStarify1('wicked')) print(betterStarify1('Starry')) print(betterStarify1('bob')) print(betterStarify1('')) print('Testing betterStarify2') print(betterStarify2('OMG')) print(betterStarify2('wicked')) print(betterStarify2('Starry')) print(betterStarify2('bob')) print(betterStarify2('')) # ---------------- starrySky ---------------------------------------------- import random def starTime(): """Returns True 20 percent of the time; False 80 percent of the time """ return random.random() > 0.80 def makeOneRow(rowLength): """Returns a string of length rowLength that contains * and -. The string is built by adding a * when starTime is True; otherwise, a dash is added to the string. """ row = '' for r in range(rowLength): if starTime(): row += '*' else: row += '-' return row def starrySky(height, width): """Returns a string that represents a starry sky. The multi-line string has dimensions height x width and is composed of rows created by calls to makeOneRow. The sky contains a newline character (\n) at the end of each row. """ sky = '' for r in range(rows): sky += makeOneRow(width) + '\n' return sky # -------------------------------------------------------------- # isVowel is borrowed from Lecture 6 def isVowel(s): l = s.lower() return (l == 'a' or l == 'e' or l == 'i' or l == 'o' or l == 'u') def lottaVowels(word): Vcount = 0 for letter in word: if isVowel(letter): Vcount += 1 if Vcount > 2: return True # yay! Found more than 2 vowels # Note that we are outside the loop here. The only way # to get to this point is if all letters in the word # have been visited, and the vowel count is less than or equal to 2 return False print(lottaVowels('OMG')) print(lottaVowels('hello')) print(lottaVowels('ABBA')) print(lottaVowels('GottaLOVEABBA')) print(lottaVowels('piano')) print(lottaVowels('eee')) print(lottaVowels('gummybears')) print(lottaVowels('laugh')) # -------------------------------------------------------------- def checkPassword(word): """Returns True if valid password, False otherwise. Password must contain a mix of upper and lower case letters, at least 1 number and 1 special character from this set: !#$%&*""" foundUpper = False foundLower = False foundNum = False foundSpecial = False for symbol in word: if symbol.islower(): foundLower = True if symbol.isupper(): foundUpper = True if symbol.isdigit(): foundNum = True if symbol in '!#$%*': foundSpecial = True if foundUpper and foundLower and foundNum and foundSpecial: return True # We are outside the loop here, and the only way to get here # is if the password does not meet the specified criteria return False print('Testing checkPassword') print(checkPassword('hello123')) print(checkPassword('PASSWORD')) print(checkPassword('myPASSWORD?')) print(checkPassword('loveMyDogCharlie!')) print(checkPassword('CS111#rocksmyworld')) print(checkPassword('running99*FAST')) # -------------------------------------------------------------- # returns true 50% of time def capitalize(): coin = random.randint(1,2) # returns a number between 1 and 2, inclusive return coin == 1 def ransom(sentence): """generate ransom note in mixed upper and lower case""" newsentence = "" for letter in sentence: if capitalize(): newsentence = newsentence + letter.upper() else: newsentence = newsentence + letter.lower() return newsentence print("ransom(Must provide chocolate to get your teddy bear back)") print(ransom("Must provide chocolate to get your teddy bear back")) print("ransom(Meet me at grand central station with harry styles and a million dollars tonight)") print(ransom("Meet me at grand central station with harry styles and a million dollars tonight"))