Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 1
- def printName():
- name = input('What is your name?: ')
- print(name)
- # 2
- # Prints the Unicode code point of every character of the string 'This is a message'
- # 3
- def replaceVowels(inputString):
- vowels = 'aeiouAEIOU'
- outputString = ''
- for i in range(len(inputString)):
- if inputString[i] in vowels:
- outputString += '1'
- else:
- outputString += inputString[i]
- return outputString
- def testReplaceVowels():
- name = input('What is your name?: ')
- name = replaceVowels(name)
- print(name)
- # 4
- def decryptSecretMessage(evenString, oddString):
- decryptedString = ''
- # Each loop adds a pair of decrypted characters to decryptedString
- for i in range(len(evenString)):
- decryptedString += evenString[i]
- decryptedString += oddString[i]
- # If the odd string has an extra character, this if statement adds it to decryptedString
- if len(oddString) - len(evenString) == 1:
- decryptedString += oddString[-1]
- print(decryptedString)
- # Bonus
- def encryptString(inputString):
- encryptedString = ''
- for i in range(len(inputString)):
- encryptedString += str(ord(inputString[i])) + ' '
- return encryptedString
- def decryptString(inputString):
- decryptedString = ''
- currentOrd = ''
- for i in range(len(inputString)):
- if inputString[i] == ' ':
- decryptedString += str(chr(int(currentOrd)))
- currentOrd = ''
- else:
- currentOrd += inputString[i]
- return decryptedString
- # 1
- # No, the replaceVowels function can not decrypt a string it has already encrypted
- # This is because the replaceVowels function only replaces vowels, instead
- # of putting vowels back into the string.
- # 2
- # See cryptography.py
- # 3
- def rot13(msg):
- alphabet = 'abcdefghijklmnopqrstuvwxyz '
- rot13Key = 'nopqrstuvwxyzabcdefghijklm '
- msg = msg.lower()
- rot13Msg = ''
- for char in msg:
- rot13Msg += rot13Key[alphabet.find(char)]
- return rot13Msg
- #print(rot13('unir n tbbq jrrxraq'))
- # 'have a good weekend'
- # BONUS
- def caesarCipher(msg, shiftValue):
- lowerAlphabet = 'abcdefghijklmnopqrstuvwxyz'
- upperAlphabet = 'ABCDEFGHIJKLMOPQRSTUVWXYZ'
- encryptedMsg = ''
- for char in msg:
- if char.lower() in lowerAlphabet:
- idx = lowerAlphabet.find(char) + shiftValue
- if idx > 25:
- idx -= 26
- if char == char.lower():
- encryptedMsg += lowerAlphabet[idx]
- elif char == char.upper():
- encryptedMsg += upperAlphabet[idx]
- elif char == ' ':
- encryptedMsg += ' '
- else:
- encryptedMsg += char
- return encryptedMsg
- def removeDupes(myString):
- newStr = ""
- for ch in myString:
- if ch not in newStr:
- newStr = newStr + ch
- return newStr
- def removeMatches(myString, removeString):
- newStr = ""
- for ch in myString:
- if ch not in removeString:
- newStr = newStr + ch
- return newStr
- #Note: This is slightly different from the code in the book
- #It supports spaces and auto-lowercases your password for you
- #It also doesn't assign to a parameter, which is a thing the book's code
- #does on Line 3 in Listing 3.10, that you should NEVER do
- def genKeyFromPass(password):
- masterASCIIKey = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
- fixedPassword = removeDupes(password)
- lastChar = fixedPassword[-1]
- lastIdx = masterASCIIKey.find(lastChar)
- afterString = removeMatches(masterASCIIKey[lastIdx+1:], fixedPassword)
- beforeString = removeMatches(masterASCIIKey[:lastIdx], fixedPassword)
- key = fixedPassword + afterString + beforeString
- return key
- # add your code here
- masterASCIIKey = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
- def substitutionEncrypt(plainText,key):
- masterASCIIKey = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
- cipherText = ""
- for ch in plainText:
- idx = masterASCIIKey.find(ch)
- cipherText = cipherText + key[idx]
- return cipherText
- def substitutionDecrypt(cipherText, key):
- masterASCIIKey = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
- plainText = ''
- for char in cipherText:
- plainText += masterASCIIKey[key.find(char)]
- return plainText
- def encryptInputWithUserPassword():
- userPlainTextPass = input("Enter your password: ")
- userKey = genKeyFromPass(userPlainTextPass)
- print(userKey)
- userPlainTextMsg = input("Enter your message: ")
- userEncryptedMsg = substitutionEncrypt(userPlainTextMsg, userKey)
- print('Your encrypted message is: ' + userEncryptedMsg)
- print('Your decrypted message is: ' + (substitutionDecrypt(userEncryptedMsg, userKey)))
- # Switches the order of substrings in the key as well as reverses some substrings
- # This decreases the readability of the key, making it slightly more secure
- def genKeyFromPass2(password):
- masterASCIIKey = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
- fixedPassword = removeDupes(password)
- lastChar = fixedPassword[-1]
- lastIdx = masterASCIIKey.find(lastChar)
- afterString = removeMatches(masterASCIIKey[lastIdx+1:], fixedPassword)
- beforeString = removeMatches(masterASCIIKey[:lastIdx], fixedPassword)
- key = beforeString + fixedPassword[::-1] + afterString[::-1]
- return key
- #Book's code for Vigenere cipher
- #Note: Spellings "Vigenere" and "Vignere" are both acceptable
- # Takes 1 parameter:
- # ch, a single character string
- # Returns the index of ch within the alphabet
- def letterToIndex(ch):
- alphabet = "abcdefghijklmnopqrstuvwxyz"
- idx = alphabet.find(ch.lower())
- if idx < 0:
- print("error: letter not in the alphabet: ", ch)
- return idx
- # Takes 1 parameter:
- # idx, an integer from 0 to 25
- # Returns the character found at that index of the alphabet
- def indexToLetter(idx):
- alphabet = "abcdefghijklmnopqrstuvwxyz"
- if idx > 25:
- print("error: ", idx, " is too large")
- letter = ''
- elif idx < 0:
- print("error: ", idx, " is too small")
- letter = ''
- else:
- letter = alphabet[idx]
- return letter
- # Takes 2 parameters:
- # keyLetter, the character to use as a key for the vignere cipher
- # plainTextLetter, the character being encrypted
- # Returns the encrypted version of plainTextLetter
- def vignereIndex(keyLetter, plainTextLetter):
- keyIndex = letterToIndex(keyLetter)
- ptIndex = letterToIndex(plainTextLetter)
- newIdx = (ptIndex + keyIndex) % 26
- return indexToLetter(newIdx)
- # Takes 2 parameters:
- # key, the string to use as a key for the vignere cipher
- # plainText, the string being encrypted
- # Returns the encrypted version of plainText
- def encryptVignere(key, plainText):
- cipherText = ""
- keyLen = len(key)
- for i in range(len(plainText)):
- ch = plainText[i]
- if ch == ' ':
- cipherText = cipherText + ch
- else:
- cipherText = cipherText + vignereIndex(key[i % keyLen], ch)
- return cipherText
- # ===================
- # ===================
- # ===== MY CODE =====
- # ===================
- # ===================
- # 3.28
- # Takes 2 parameters:
- # keyLetter, the character to use as a key for the vignere cipher
- # ctLetter, the character being decrypted
- # Returns the decrypted version of ctLetter
- def undoVig(keyLetter, ctLetter):
- keyIndex = letterToIndex(keyLetter)
- ctIndex = letterToIndex(ctLetter)
- ptLetter = indexToLetter((ctIndex - keyIndex + 26) % 26)
- return ptLetter
- # 3.29
- # Takes 2 parameters:
- # key, the string to use as a key for the vignere cipher
- # cipherText, the string being decrypted
- # Returns the decrypted version of cipherText
- def decryptVignere(key, cipherText):
- plainText = ''
- keyLen = len(key)
- for i in range(len(cipherText)):
- ctLetter = cipherText[i]
- keyLetter = key[i % keyLen]
- if ctLetter == ' ':
- plainText += ctLetter
- else:
- plainText += undoVig(keyLetter, ctLetter)
- return plainText
- # Takes no parameters
- # Takes user input for a key and a message to be encrypted/decrypted
- # using the encryptVignere and decryptVignere functions
- def vignereEncryptInputWithUserKey():
- userKey = input("Enter your key: ")
- userPlainTextMsg = input("Enter your message: ")
- encryptedMsg = encryptVignere(userKey, userPlainTextMsg)
- print('Your encrypted message is: ' + encryptedMsg)
- decryptedMsg = decryptVignere(userKey, encryptedMsg)
- print('Your decrypted message is: ' + decryptedMsg)
- # ===================
- # ===================
- # ===== BONUS =====
- # ===================
- # ===================
- import random
- # Takes no parameters
- # Returns a random lowercase letter
- def randomLetter():
- letter = indexToLetter(random.randint(0,25))
- return letter
- # Takes 2 parameters:
- # key, the string to use as a key for the random seed vignere cipher
- # msg, the string being encrypted
- # Returns the encrypted version of msg
- def randomSeedEncrypt(key, msg):
- random.seed(key)
- cipherText = ''
- for i in range(len(msg)):
- ch = msg[i]
- randCh = randomLetter()
- if ch == ' ':
- cipherText += ch
- else:
- cipherText += vignereIndex(randCh, ch)
- return cipherText
- # Takes 2 parameters:
- # key, the string to use as a key for the random seed vignere cipher
- # msg, the string being decrypted
- # Returns the decrypted version of msg
- def randomSeedDecrypt(key, msg):
- random.seed(key)
- plainText = ''
- for i in range(len(msg)):
- ch = msg[i]
- randCh = randomLetter()
- if ch == ' ':
- plainText += ch
- else:
- plainText += undoVig(randCh, ch)
- return plainText
- # Takes no parameters
- # Takes user input for a key and a message to be encrypted/decrypted
- # using the randomSeedEncrypt and randomSeedDecrypt functions
- def randomSeedEncryptInputWithUserKey():
- userKey = input("Enter your key: ")
- userPlainTextMsg = input("Enter your message: ")
- encryptedMsg = randomSeedEncrypt(userKey, userPlainTextMsg)
- print('Your encrypted message is: ' + encryptedMsg)
- decryptedMsg = randomSeedDecrypt(userKey, encryptedMsg)
- print('Your decrypted message is: ' + decryptedMsg)
- #Code for #1
- #a)
- def try_1a():
- s = 'abc'
- s[0] = 'd'
- #b)
- def try_1b():
- lst = ['a', 'b', 'c']
- lst[0] = 'd'
- #Code for #2
- def try_2():
- s = 'I like apples'
- k1 = s.split()
- k2 = s.split('a')
- k3 = s.split('p')
- #Code for #3
- def try_3():
- x = ['E', 'v', 'a', 'n']
- y = ''.join(x)
- #Code for #4
- # Takes 1 parameter:
- # lst, a list of numbers
- # Returns the average of those numbers
- def getAverage(lst):
- sum = 0
- for num in lst:
- sum += num
- average = sum / len(lst)
- return average
- def try_4():
- numGrades = input("How many grades? ")
- numGrades = int(numGrades)
- lstGrades = []
- for i in range(numGrades):
- userGrade = input('Enter grade #' + str(i+1) + ': ')
- lstGrades.append(int(userGrade))
- gradeAverage = getAverage(lstGrades)
- # Makes a nice looking string to show input grades
- gradeString = ''
- for i in range(len(lstGrades)):
- num = lstGrades[i]
- if i == len(lstGrades) - 1:
- gradeString += 'and ' + str(num)
- else:
- gradeString += str(num) + ', '
- print("Your grades are: " + gradeString)
- print("Your grade average is: " + str(gradeAverage))
- # BONUS
- import random
- def birthdayParadox(numOfPeople, numOfDays):
- birthdayList = []
- for i in range(numOfPeople):
- birthdayList.append(random.randint(0, 365))
- for day in range(numOfDays):
- numOfBirthdays = birthdayList.count(day)
- if numOfBirthdays > 1:
- return True
- return False
- def testBirthdayParadox(numOfPeople, numOfDays, numOfTrials):
- trialOutcomeList = []
- for i in range(numOfTrials):
- trialOutcomeList.append(birthdayParadox(numOfPeople, numOfDays))
- proportionOfShared = trialOutcomeList.count(True) / len(trialOutcomeList)
- print(proportionOfShared)
- classGrades = {'Daniel': 'C', 'Wyatt': 'F', 'Angelo': 'A++++++'}
- print(classGrades.keys())
- # dict_keys(['Wyatt', 'Angelo', 'Daniel'])
- print(classGrades.values())
- # dict_values(['F', 'A++++++', 'C'])
- print(classGrades.items())
- # dict_items([('Wyatt', 'F'), ('Angelo', 'A++++++'), ('Daniel', 'C')])
- print(classGrades.get('Professor Fox', 'Has no grade'))
- # 'Has no grade'
- print('Wyatt' in classGrades)
- # True
- print('Daniel' not in classGrades)
- # False
- print(classGrades['Wyatt'])
- # 'F'
- del classGrades['Angelo']
- print(classGrades)
- # {'Wyatt': 'F', 'Daniel': 'C'}
- def userPassDict():
- userPswd = {}
- amountOfNames = 0
- while amountOfNames < 5:
- userName = input('Enter your username: ')
- # Prevents the user from accidently overwriting password
- if userName in userPswd:
- print(userName + ' has already been entered! Enter a unique username')
- continue
- userPass = input ('Enter your password: ')
- userPswd[userName] = userPass
- amountOfNames += 1
- while True:
- userName = input('Enter a username that you wish to know the password of (or hit enter to see none): ')
- if userName == '':
- break
- elif userName in userPswd:
- print('The password of "' + userName + '" is ' + userPswd[userName])
- break
- elif userName not in userPswd:
- print(userName + ' is not a valid username')
- print('Enter a valid username or hit enter to exit the loop')
- print(userPswd)
- import random
- def lotterySim():
- print('Time to gamble! Enter five integers from 0 to 9 inclusive!')
- userTicket = []
- amountOfNums = 0
- validNums = ['0','1','2','3','4','5','6','7','8','9']
- while amountOfNums < 5:
- userNum = input('Enter number ' + str(amountOfNums+1) + ': ')
- if userNum not in validNums:
- print('Your number must be an integer between 0 and 9 (inclusive)!')
- continue
- userTicket.append(userNum)
- amountOfNums += 1
- lottery = []
- correctGuesses = 0
- userTicketCopy = userTicket
- for i in range(5):
- lotteryNum = str(random.randint(0,9))
- lottery.append(lotteryNum)
- if lotteryNum in userTicketCopy:
- correctGuesses += 1
- userTicketCopy.remove(lotteryNum)
- print('Your guesses were: ' + str(userTicket))
- print('The lottery numbers were: ' + str(lottery))
- if correctGuesses == 5:
- print('YOU WON THE JACKPOT')
- elif correctGuesses == 0:
- print('You had no matching numbers')
- else:
- print('You had ' + str(correctGuesses) + ' numbers. Maybe next time!')
- # 1
- def printSentence(name, age, numPets):
- print('%s is %.2f years old and has %d pets.' % (name, age, numPets))
- # 2a
- def rightAlignNum(num):
- print('%20.2f' % (num))
- # 2b
- def leftAlignNum(floatNum, intNum):
- print('%-20.2f %i' % (floatNum, intNum))
- # 2c
- def leadingZeroNum(num):
- print('%020.2f' % (num))
- # 3
- def createStatistics():
- rainfall = open('rainfall.txt', 'r')
- statistics = open('statistics.txt', 'w')
- rainDict = {}
- for line in rainfall:
- rainList = line.split()
- rainDict[rainList[0]] = rainList[1]
- maxRainCity = max(rainDict, key = rainDict.get)
- minRainCity = min(rainDict, key = rainDict.get)
- numOfValues = 0
- totalRain = 0
- for key in rainDict:
- totalRain += float(rainDict[key])
- numOfValues += 1
- averageRain = totalRain / numOfValues
- statistics.write('%s has the most rain with %.2f inches.\n' % (maxRainCity, float(rainDict[maxRainCity])))
- statistics.write('%s has the least rain with %.2f inches.\n' % (minRainCity, float(rainDict[minRainCity])))
- statistics.write('The average amount of rain is %.2f inches.\n' % (averageRain))
- rainfall.close()
- statistics.close()
- # 1
- def convertStringNumbers():
- a = ['1', '2', '3']
- b = [int(x) for x in a]
- return b
- # 5
- def addPositiveIntegers():
- numList = []
- while True:
- inputNum = input('Enter an integer: ')
- try:
- inputNum = int(inputNum)
- except ValueError:
- print('Enter an INTEGER!')
- continue
- if inputNum >= 0:
- numList.append(inputNum)
- else:
- break
- total = 0
- for num in numList:
- total += num
- return total
- # 3
- def rot13(msg):
- alphabet = 'abcdefghijklmnopqrstuvwxyz '
- rot13Key = 'nopqrstuvwxyzabcdefghijklm '
- msg = msg.lower()
- rot13Msg = ''
- for char in msg:
- rot13Msg += rot13Key[alphabet.find(char)]
- return rot13Msg
- #rot13('ncevy sbbyf')
- #'april fools'
- # 4
- # Takes 1 parameter: numTerms, the number of terms
- # Returns the numTerms term of the Fibonacci sequence
- def fibonacci(n):
- if n == 1:
- fibList = [1]
- elif n == 2:
- fibList = [1, 1]
- else:
- fibList = [1, 1]
- currentValue = 2
- twoTermsAgo = 1
- oneTermAgo = 1
- for i in range(2, n):
- currentValue = twoTermsAgo + oneTermAgo
- twoTermsAgo = oneTermAgo
- oneTermAgo = currentValue
- return fibList
- # 2
- # Takes no parameters
- # Prints all of rainfall.txt unformatted
- def printRainfall():
- rainfall = open('rainfall.txt', 'r')
- print(rainfall.readlines())
- rainfall.close()
- # 3
- # Takes no parameters
- # Prints each line of rainfall.txt in a nice and clear format
- def printRainfallNicely():
- rainfall = open('rainfall.txt', 'r')
- for line in rainfall:
- rainList = line.split()
- rainLocation = rainList[0]
- rainInches = rainList[1]
- print(rainLocation + ' averages ' + rainInches + ' inches of rain per year')
- rainfall.close()
- # 4
- # Takes no parameters
- # Writes each line of rainfall.txt in a nice and clear format to out.txt
- def writeRainfall():
- rainfall = open('rainfall.txt', 'r')
- outputFile = open('out.txt', 'w')
- for line in rainfall:
- rainList = line.split()
- rainLocation = rainList[0]
- rainInches = rainList[1]
- outputFile.write(rainLocation + ' averages ' + rainInches + ' inches of rain per year\n')
- outputFile.close()
- rainfall.close()
- # 5
- # Takes no parameters
- # Returns the average amount of rainfall for all cities
- # The output (average rainfall) is 34.119600000000005
- def averageRainfall():
- rainfall = open('rainfall.txt', 'r')
- amountOfLocations = 0
- totalRainAmount = 0
- for line in rainfall:
- rainList = line.split()
- rainAmount = float(rainList[1])
- amountOfLocations += 1
- totalRainAmount += rainAmount
- averageRainAmount = totalRainAmount / amountOfLocations
- rainfall.close()
- return averageRainAmount
- # 6
- # Takes no parameters
- # Returns the average amount of rainfall for only cities beginning with 'A'
- def averageRainfallInACities():
- rainfall = open('rainfall.txt', 'r')
- amountOfLocations = 0
- totalRainAmount = 0
- for line in rainfall:
- rainList = line.split()
- if rainList[0][0] == 'A':
- rainAmount = float(rainList[1])
- amountOfLocations += 1
- totalRainAmount += rainAmount
- averageRainAmount = totalRainAmount / amountOfLocations
- rainfall.close()
- return averageRainAmount
- # BONUS PART 1
- # Takes no parameters
- # Writes the lines of rainfall.txt in a nice and clear format, sorted by amount of rainfall, to out.txt
- def outputSortedRainfall():
- rainfall = open('rainfall.txt', 'r')
- outputFile = open('out.txt', 'w')
- rainAmountList = []
- rainLocationList = []
- for line in rainfall:
- rainList = line.split()
- rainLocationList.append(rainList[0])
- rainAmountList.append(rainList[1])
- sortedRainAmountList = sorted(rainAmountList)
- for amount in sortedRainAmountList:
- index = rainAmountList.index(amount)
- rainLocation = rainLocationList[index]
- outputFile.write(rainLocation + ' averages ' + amount + ' inches of rain per year\n')
- outputFile.close()
- # BONUS PART 2
- import random
- import math
- # Takes no parameters
- # Returns the standard deviation of the rainfall amount data set
- def standardDev():
- rainfall = open('rainfall.txt', 'r')
- rainAmountList = []
- for line in rainfall:
- rainList = line.split()
- rainAmountList.append(rainList[1])
- total = 0
- amountOfItems = 0
- for amount in rainAmountList:
- total += float(amount)
- amountOfItems += 1
- mean = total / amountOfItems
- stdTotal = 0
- for item in rainAmountList:
- difference = float(item) - mean
- diffsq = difference ** 2
- stdTotal += diffsq
- sdev = math.sqrt(stdTotal / (len(rainAmountList)-1))
- return sdev
- # Takes no parameters
- # Writes a simulated amount of rainfall for the next 30 years to out.txt
- def simulateClimateData():
- rainfall = open('rainfall.txt', 'r')
- outputFile = open('out.txt', 'w')
- average = averageRainfall()
- stdDev = standardDev()
- for i in range(2018, 2049):
- rainAmount = random.gauss(average, stdDev)
- outputFile.write('In the year ' + str(i) + ', there will be ' + str(rainAmount) + ' inches of rain\n')
- outputFile.close()
- rainfall.close()
- # 3.18
- # Takes 1 parameter: myString, a string
- # Returns myString with all spaces removed
- def stripSpaces(myString):
- outputString = ''
- for ch in myString:
- if ch != ' ':
- outputString += ch
- return outputString
- # 3.19
- # Takes 1 parameter: plaintText, a string
- # Returns the an encrypted form of plainText with the three-rail cipher
- def threeRailFenceCipher(plainText):
- rail1Chars = ''
- rail2Chars = ''
- rail3Chars = ''
- charCount = 0
- for ch in plainText:
- # There are four conditionals for three rails in order to have the rail-fence pattern
- if charCount == 0:
- rail1Chars += ch
- elif charCount == 1:
- rail2Chars += ch
- elif charCount == 2:
- rail3Chars += ch
- else:
- rail2Chars += ch
- # -1 is assigned to charCount so that it starts the next loop at 0
- charCount = -1
- charCount += 1
- cipherText = rail1Chars + rail2Chars + rail3Chars
- return cipherText
- # Example: threeRailFenceCipher('I am testing my string') returns 'I t sn mtsigm tigaenyr'
- # The grid for this rail-fence cipher would look like: ('-' represents nothingness)
- # I - - - - - - T - - - - - - S - - - N -
- # - - M - T - S - I - G - M - - T - I - G
- # - - A - - - E - - - N - - - Y - - - R - - -
- # 4.1
- myList = [7, 9, 'a', 'cat', False]
- # 4.2
- myList.append(3.14)
- myList.append(7)
- myList.insert(3, 'dog')
- myList.index('cat')
- myList.count(7)
- myList.remove(7)
- myList.pop(2)
- # The following line would also remove 'dog' from the list, but
- # 'dog' is no longer in myList, so the following line will cause an error
- #myList.remove('dog')
- # 4.3
- 'the quick brown fox'.split(' ')
- # 4.4
- 'mississippi'.split('i')
- # 4.5
- # Takes 1 parameter: sentence, a string of words
- # Returns the amount of words in that string
- def numOfWords(sentence):
- listOfWords = sentence.split(' ')
- numOfWords = len(listOfWords)
- return numOfWords
- # 4.6
- # Takes 2 parameters: aList, a list; item, an item in the list
- # Returns the amount of times that item is within aList
- def my_count(aList, item):
- itemCount = 0
- for el in aList:
- if el == item:
- itemCount += 1
- return itemCount
- # Takes 2 parameters: aList, a list; item, an item in the list
- # Returns True if item is in aList, or False if it is not
- def my_in(aList, item):
- for el in aList:
- if el == item:
- return True
- return False
- # Takes 1 parameters: aList, a list
- # Returns aList in the opposite order
- def my_reverse(aList):
- reversedList = []
- for el in aList:
- reversedList.insert(0, el)
- return reversedList
- # Takes 2 parameters: aList, a list; item, an item in the list
- # Returns the index of the first occurence of item in aList or -1 if item is not in aList
- def my_index(aList, item):
- for i in range(len(aList)):
- if item == aList[i]:
- return i
- return -1
- # Takes 3 parameters: aList, a list; item, an item in the list; index, an integer
- # Returns aList with item inserted at the position of index
- def my_insert(aList, item, index):
- outputList = []
- i = 0
- for el in aList:
- if index == i:
- outputList.append(item)
- outputList.append(el)
- i += 1
- return outputList
- # 4.11
- #myList[1].append(2)
- # This code does not work...
- # AttributeError: 'str' object has no attribute 'append'
- # This is because myList[1] is 'a', a string
- # A string cannot be appended to, so 'a'.append(2) results in an error.
- # 1
- # Takes 0 parameters
- # Prompts the user for two words, word1 and word2, to be compared
- # Returns True if all of word1's characters are within word2, and False if otherwise
- def compareWords():
- word1 = input('Enter the first word: ')
- word2 = input('Enter the second word: ')
- for ch in word1:
- if ch not in word2:
- return False
- return True
- # 2
- # Takes 1 parameter: my_string, a string
- # Returns a dictionary containing the frequency of vowels within my_string
- def count_vowels(my_string):
- vowelDict = {}
- for ch in my_string:
- if ch in 'aeiou':
- vowelDict[ch] = vowelDict.get(ch, 0) + 1
- return vowelDict
- # 3
- # Takes 1 parameter: my_dict, a dictionary containing values corresponding to temperatures
- # Returns the keys of that dictionary that would be considered 'moderate' (between 70 and 79)
- def moderate_days(my_dict):
- dayList = []
- for key in my_dict:
- if my_dict[key] >= 70 and my_dict[key] <= 79:
- dayList.append(key)
- return dayList
- # 4
- # Takes no parameters, but takes a phone number from the user as input (inputNum)
- # Returns inputNum but with the letters within inputNum replaced with their corresponding number
- def reverse_phone():
- inputNum = input('Enter a phone number to be converted: ')
- comparisonDict = {'a': 2, 'b': 2, 'c': 2,
- 'd': 3, 'e': 3, 'f': 3,
- 'g': 4, 'h': 4, 'i': 4,
- 'j': 5, 'k': 5, 'l': 5,
- 'm': 6, 'n': 6, 'o': 6,
- 'p': 7, 'q': 7, 'r': 7, 's': 7,
- 't': 8, 'u': 8, 'v': 8,
- 'w': 9, 'x': 9, 'y': 9, 'z': 9}
- outputList = []
- keyList = list(comparisonDict.keys())
- for ch in inputNum:
- if ch in keyList:
- outputList.append(str(comparisonDict[ch]))
- else:
- outputList.append(ch)
- outputNum = ''.join(outputList)
- return outputNum
- # 5
- # Takes no parameters
- # Reads from hw7Text.txt, and writes output to hw7TextOutput.txt
- # Writes a fancy table of the freqeuency of different words in hw7TextOutput
- def outputFrequencies():
- inputFile = open('hw7Text.txt', 'r')
- outputFile = open('hw7TextOutput.txt', 'w')
- outputFile.write('%-13s%s\n' % ('Word', 'Frequency'))
- outputFile.write('#######################\n')
- wordFreqDict = {}
- for line in inputFile:
- wordList = line.split()
- for word in wordList:
- wordFreqDict[word] = wordFreqDict.get(word, 0) + 1
- for key in sorted(wordFreqDict):
- outputFile.write('%-17s%d\n' % (key + ':', wordFreqDict[key]))
- outputFile.write('-----------------------\n')
- inputFile.close()
- outputFile.close()
- # 6
- # Takes no parameters
- # Reads from barCodes.txt
- # Checks if the check sum digit of each bar code is correct or not using an algorithm
- # Prints the UPC Code, the Checksum, and the result of the test (True if correct Checksum, False otherwise)
- def verifyCheckSums():
- barCodesFile = open('barCodes.txt', 'r')
- for line in barCodesFile:
- upc = line[0:11]
- checkSum = int(line[11])
- oddSum = 3 * (int(upc[0]) + int(upc[2]) + int(upc[4]) + int(upc[6]) + int(upc[8]) + int(upc[10]))
- evenSum = int(upc[1]) + int(upc[3]) + int(upc[5]) + int(upc[7]) + int(upc[9])
- remainderOfSum = (oddSum + evenSum) % 10
- calculatedCheckSum = 10 - remainderOfSum
- if calculatedCheckSum == 10:
- calculatedCheckSum = 0
- if calculatedCheckSum == checkSum:
- result = True
- else:
- result = False
- print('UPC Code: %s' % (''.join(upc)))
- print('Checksum Digit: %d' % (checkSum))
- print(result)
- barCodesFile.close()
- # Takes 2 parameters:
- # salaryDict, a dictionary where the keys are people and the values are their salaries
- # bonus, an integer amount to be added to each person's salaries
- # Returns a dictionary with the same people and their new salaries
- def addBonusToSalary(salaryDict, bonus):
- salaryList = list(salaryDict.keys())
- salaryWithBonusDict = salaryDict
- for employee in salaryList:
- salaryWithBonusDict[employee] += bonus
- return salaryWithBonusDict
- # Takes 1 parameter: englishString, a string containing phrases in plain English
- # Translates this plain English string into a pirate English string
- # Works with single words and two-word phrases, such as 'excuse me'
- def toPirate(englishString):
- pirateTranslationDictionary = {
- 'hello': 'avast',
- 'excuse me': 'arrr',
- 'sir': 'matey',
- 'boy': 'matey',
- 'man': 'matey',
- 'madam': 'proud beauty',
- 'officer': 'foul blaggart',
- 'the': 'th\'',
- 'my': 'me',
- 'your': 'yer',
- 'is': 'be',
- 'are': 'be',
- 'restroom': 'head',
- 'restaurant': 'galley',
- 'hotel': 'fleabag inn',
- 'yes': 'aye',
- 'woah': 'blimey',
- 'treasure': 'booty',
- 'reward': 'bounty',
- 'pirate': 'buccaneer',
- 'song': 'chantey',
- 'hell': 'Davy Jone\' Locker',
- 'six feet': 'fathom',
- 'water': 'rum',
- 'kid': 'lad',
- 'money': 'loot',
- 'rookie': 'scallywag',
- 'veteran': 'seadog',
- }
- englishWordList = englishString.split(' ')
- pirateWordList = []
- pirateDictionaryWordList = pirateTranslationDictionary.keys()
- i = 0
- while i < len(englishWordList):
- englishWord = englishWordList[i]
- if i+1 < len(englishWordList):
- nextEnglishWord = ' ' + englishWordList[i+1]
- else:
- nextEnglishWord = ''
- englishTwoWordPhrase = englishWord + nextEnglishWord
- if englishTwoWordPhrase in pirateDictionaryWordList and englishTwoWordPhrase != englishWord:
- pirateWordList.append(pirateTranslationDictionary[englishTwoWordPhrase])
- i += 1
- elif englishWord in pirateDictionaryWordList:
- pirateWordList.append(pirateTranslationDictionary[englishWord])
- else:
- pirateWordList.append(englishWord)
- i += 1
- pirateString = ' '.join(pirateWordList)
- return pirateString
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement