Advertisement
Guest User

Untitled

a guest
Apr 5th, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 32.11 KB | None | 0 0
  1. # 1
  2. def printName():
  3. name = input('What is your name?: ')
  4. print(name)
  5.  
  6. # 2
  7. # Prints the Unicode code point of every character of the string 'This is a message'
  8.  
  9. # 3
  10. def replaceVowels(inputString):
  11. vowels = 'aeiouAEIOU'
  12. outputString = ''
  13. for i in range(len(inputString)):
  14. if inputString[i] in vowels:
  15. outputString += '1'
  16. else:
  17. outputString += inputString[i]
  18. return outputString
  19.  
  20. def testReplaceVowels():
  21. name = input('What is your name?: ')
  22. name = replaceVowels(name)
  23. print(name)
  24.  
  25. # 4
  26. def decryptSecretMessage(evenString, oddString):
  27. decryptedString = ''
  28. # Each loop adds a pair of decrypted characters to decryptedString
  29. for i in range(len(evenString)):
  30. decryptedString += evenString[i]
  31. decryptedString += oddString[i]
  32. # If the odd string has an extra character, this if statement adds it to decryptedString
  33. if len(oddString) - len(evenString) == 1:
  34. decryptedString += oddString[-1]
  35. print(decryptedString)
  36.  
  37. # Bonus
  38. def encryptString(inputString):
  39. encryptedString = ''
  40. for i in range(len(inputString)):
  41. encryptedString += str(ord(inputString[i])) + ' '
  42. return encryptedString
  43.  
  44. def decryptString(inputString):
  45. decryptedString = ''
  46. currentOrd = ''
  47. for i in range(len(inputString)):
  48. if inputString[i] == ' ':
  49. decryptedString += str(chr(int(currentOrd)))
  50. currentOrd = ''
  51. else:
  52. currentOrd += inputString[i]
  53. return decryptedString
  54.  
  55.  
  56.  
  57.  
  58.  
  59. # 1
  60. # No, the replaceVowels function can not decrypt a string it has already encrypted
  61. # This is because the replaceVowels function only replaces vowels, instead
  62. # of putting vowels back into the string.
  63.  
  64. # 2
  65. # See cryptography.py
  66.  
  67. # 3
  68. def rot13(msg):
  69. alphabet = 'abcdefghijklmnopqrstuvwxyz '
  70. rot13Key = 'nopqrstuvwxyzabcdefghijklm '
  71. msg = msg.lower()
  72. rot13Msg = ''
  73. for char in msg:
  74. rot13Msg += rot13Key[alphabet.find(char)]
  75. return rot13Msg
  76.  
  77. #print(rot13('unir n tbbq jrrxraq'))
  78. # 'have a good weekend'
  79.  
  80. # BONUS
  81. def caesarCipher(msg, shiftValue):
  82. lowerAlphabet = 'abcdefghijklmnopqrstuvwxyz'
  83. upperAlphabet = 'ABCDEFGHIJKLMOPQRSTUVWXYZ'
  84. encryptedMsg = ''
  85. for char in msg:
  86. if char.lower() in lowerAlphabet:
  87. idx = lowerAlphabet.find(char) + shiftValue
  88. if idx > 25:
  89. idx -= 26
  90. if char == char.lower():
  91. encryptedMsg += lowerAlphabet[idx]
  92. elif char == char.upper():
  93. encryptedMsg += upperAlphabet[idx]
  94. elif char == ' ':
  95. encryptedMsg += ' '
  96. else:
  97. encryptedMsg += char
  98. return encryptedMsg
  99.  
  100.  
  101.  
  102.  
  103.  
  104.  
  105. def removeDupes(myString):
  106. newStr = ""
  107. for ch in myString:
  108. if ch not in newStr:
  109. newStr = newStr + ch
  110. return newStr
  111.  
  112. def removeMatches(myString, removeString):
  113. newStr = ""
  114. for ch in myString:
  115. if ch not in removeString:
  116. newStr = newStr + ch
  117. return newStr
  118.  
  119. #Note: This is slightly different from the code in the book
  120. #It supports spaces and auto-lowercases your password for you
  121. #It also doesn't assign to a parameter, which is a thing the book's code
  122. #does on Line 3 in Listing 3.10, that you should NEVER do
  123. def genKeyFromPass(password):
  124. masterASCIIKey = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
  125. fixedPassword = removeDupes(password)
  126. lastChar = fixedPassword[-1]
  127. lastIdx = masterASCIIKey.find(lastChar)
  128. afterString = removeMatches(masterASCIIKey[lastIdx+1:], fixedPassword)
  129. beforeString = removeMatches(masterASCIIKey[:lastIdx], fixedPassword)
  130. key = fixedPassword + afterString + beforeString
  131. return key
  132.  
  133. # add your code here
  134. masterASCIIKey = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
  135.  
  136. def substitutionEncrypt(plainText,key):
  137. masterASCIIKey = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
  138. cipherText = ""
  139. for ch in plainText:
  140. idx = masterASCIIKey.find(ch)
  141. cipherText = cipherText + key[idx]
  142. return cipherText
  143.  
  144. def substitutionDecrypt(cipherText, key):
  145. masterASCIIKey = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
  146. plainText = ''
  147. for char in cipherText:
  148. plainText += masterASCIIKey[key.find(char)]
  149. return plainText
  150.  
  151. def encryptInputWithUserPassword():
  152. userPlainTextPass = input("Enter your password: ")
  153. userKey = genKeyFromPass(userPlainTextPass)
  154. print(userKey)
  155. userPlainTextMsg = input("Enter your message: ")
  156. userEncryptedMsg = substitutionEncrypt(userPlainTextMsg, userKey)
  157. print('Your encrypted message is: ' + userEncryptedMsg)
  158. print('Your decrypted message is: ' + (substitutionDecrypt(userEncryptedMsg, userKey)))
  159.  
  160. # Switches the order of substrings in the key as well as reverses some substrings
  161. # This decreases the readability of the key, making it slightly more secure
  162. def genKeyFromPass2(password):
  163. masterASCIIKey = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
  164. fixedPassword = removeDupes(password)
  165. lastChar = fixedPassword[-1]
  166. lastIdx = masterASCIIKey.find(lastChar)
  167. afterString = removeMatches(masterASCIIKey[lastIdx+1:], fixedPassword)
  168. beforeString = removeMatches(masterASCIIKey[:lastIdx], fixedPassword)
  169. key = beforeString + fixedPassword[::-1] + afterString[::-1]
  170. return key
  171.  
  172.  
  173.  
  174.  
  175.  
  176.  
  177. #Book's code for Vigenere cipher
  178. #Note: Spellings "Vigenere" and "Vignere" are both acceptable
  179.  
  180. # Takes 1 parameter:
  181. # ch, a single character string
  182. # Returns the index of ch within the alphabet
  183. def letterToIndex(ch):
  184. alphabet = "abcdefghijklmnopqrstuvwxyz"
  185. idx = alphabet.find(ch.lower())
  186. if idx < 0:
  187. print("error: letter not in the alphabet: ", ch)
  188. return idx
  189.  
  190. # Takes 1 parameter:
  191. # idx, an integer from 0 to 25
  192. # Returns the character found at that index of the alphabet
  193. def indexToLetter(idx):
  194. alphabet = "abcdefghijklmnopqrstuvwxyz"
  195. if idx > 25:
  196. print("error: ", idx, " is too large")
  197. letter = ''
  198. elif idx < 0:
  199. print("error: ", idx, " is too small")
  200. letter = ''
  201. else:
  202. letter = alphabet[idx]
  203. return letter
  204.  
  205. # Takes 2 parameters:
  206. # keyLetter, the character to use as a key for the vignere cipher
  207. # plainTextLetter, the character being encrypted
  208. # Returns the encrypted version of plainTextLetter
  209. def vignereIndex(keyLetter, plainTextLetter):
  210. keyIndex = letterToIndex(keyLetter)
  211. ptIndex = letterToIndex(plainTextLetter)
  212. newIdx = (ptIndex + keyIndex) % 26
  213. return indexToLetter(newIdx)
  214.  
  215. # Takes 2 parameters:
  216. # key, the string to use as a key for the vignere cipher
  217. # plainText, the string being encrypted
  218. # Returns the encrypted version of plainText
  219. def encryptVignere(key, plainText):
  220. cipherText = ""
  221. keyLen = len(key)
  222. for i in range(len(plainText)):
  223. ch = plainText[i]
  224. if ch == ' ':
  225. cipherText = cipherText + ch
  226. else:
  227. cipherText = cipherText + vignereIndex(key[i % keyLen], ch)
  228. return cipherText
  229.  
  230. # ===================
  231. # ===================
  232. # ===== MY CODE =====
  233. # ===================
  234. # ===================
  235.  
  236. # 3.28
  237. # Takes 2 parameters:
  238. # keyLetter, the character to use as a key for the vignere cipher
  239. # ctLetter, the character being decrypted
  240. # Returns the decrypted version of ctLetter
  241. def undoVig(keyLetter, ctLetter):
  242. keyIndex = letterToIndex(keyLetter)
  243. ctIndex = letterToIndex(ctLetter)
  244. ptLetter = indexToLetter((ctIndex - keyIndex + 26) % 26)
  245. return ptLetter
  246.  
  247. # 3.29
  248. # Takes 2 parameters:
  249. # key, the string to use as a key for the vignere cipher
  250. # cipherText, the string being decrypted
  251. # Returns the decrypted version of cipherText
  252. def decryptVignere(key, cipherText):
  253. plainText = ''
  254. keyLen = len(key)
  255. for i in range(len(cipherText)):
  256. ctLetter = cipherText[i]
  257. keyLetter = key[i % keyLen]
  258. if ctLetter == ' ':
  259. plainText += ctLetter
  260. else:
  261. plainText += undoVig(keyLetter, ctLetter)
  262. return plainText
  263.  
  264. # Takes no parameters
  265. # Takes user input for a key and a message to be encrypted/decrypted
  266. # using the encryptVignere and decryptVignere functions
  267. def vignereEncryptInputWithUserKey():
  268. userKey = input("Enter your key: ")
  269. userPlainTextMsg = input("Enter your message: ")
  270. encryptedMsg = encryptVignere(userKey, userPlainTextMsg)
  271. print('Your encrypted message is: ' + encryptedMsg)
  272. decryptedMsg = decryptVignere(userKey, encryptedMsg)
  273. print('Your decrypted message is: ' + decryptedMsg)
  274.  
  275. # ===================
  276. # ===================
  277. # ===== BONUS =====
  278. # ===================
  279. # ===================
  280. import random
  281.  
  282. # Takes no parameters
  283. # Returns a random lowercase letter
  284. def randomLetter():
  285. letter = indexToLetter(random.randint(0,25))
  286. return letter
  287.  
  288. # Takes 2 parameters:
  289. # key, the string to use as a key for the random seed vignere cipher
  290. # msg, the string being encrypted
  291. # Returns the encrypted version of msg
  292. def randomSeedEncrypt(key, msg):
  293. random.seed(key)
  294. cipherText = ''
  295. for i in range(len(msg)):
  296. ch = msg[i]
  297. randCh = randomLetter()
  298. if ch == ' ':
  299. cipherText += ch
  300. else:
  301. cipherText += vignereIndex(randCh, ch)
  302. return cipherText
  303.  
  304. # Takes 2 parameters:
  305. # key, the string to use as a key for the random seed vignere cipher
  306. # msg, the string being decrypted
  307. # Returns the decrypted version of msg
  308. def randomSeedDecrypt(key, msg):
  309. random.seed(key)
  310. plainText = ''
  311. for i in range(len(msg)):
  312. ch = msg[i]
  313. randCh = randomLetter()
  314. if ch == ' ':
  315. plainText += ch
  316. else:
  317. plainText += undoVig(randCh, ch)
  318. return plainText
  319.  
  320. # Takes no parameters
  321. # Takes user input for a key and a message to be encrypted/decrypted
  322. # using the randomSeedEncrypt and randomSeedDecrypt functions
  323. def randomSeedEncryptInputWithUserKey():
  324. userKey = input("Enter your key: ")
  325. userPlainTextMsg = input("Enter your message: ")
  326. encryptedMsg = randomSeedEncrypt(userKey, userPlainTextMsg)
  327. print('Your encrypted message is: ' + encryptedMsg)
  328. decryptedMsg = randomSeedDecrypt(userKey, encryptedMsg)
  329. print('Your decrypted message is: ' + decryptedMsg)
  330.  
  331.  
  332.  
  333.  
  334.  
  335.  
  336.  
  337. #Code for #1
  338. #a)
  339. def try_1a():
  340. s = 'abc'
  341. s[0] = 'd'
  342.  
  343. #b)
  344. def try_1b():
  345. lst = ['a', 'b', 'c']
  346. lst[0] = 'd'
  347.  
  348. #Code for #2
  349. def try_2():
  350. s = 'I like apples'
  351. k1 = s.split()
  352. k2 = s.split('a')
  353. k3 = s.split('p')
  354.  
  355. #Code for #3
  356. def try_3():
  357. x = ['E', 'v', 'a', 'n']
  358. y = ''.join(x)
  359.  
  360. #Code for #4
  361.  
  362. # Takes 1 parameter:
  363. # lst, a list of numbers
  364. # Returns the average of those numbers
  365. def getAverage(lst):
  366. sum = 0
  367. for num in lst:
  368. sum += num
  369. average = sum / len(lst)
  370. return average
  371.  
  372. def try_4():
  373. numGrades = input("How many grades? ")
  374. numGrades = int(numGrades)
  375.  
  376. lstGrades = []
  377.  
  378. for i in range(numGrades):
  379. userGrade = input('Enter grade #' + str(i+1) + ': ')
  380. lstGrades.append(int(userGrade))
  381.  
  382. gradeAverage = getAverage(lstGrades)
  383.  
  384. # Makes a nice looking string to show input grades
  385. gradeString = ''
  386. for i in range(len(lstGrades)):
  387. num = lstGrades[i]
  388. if i == len(lstGrades) - 1:
  389. gradeString += 'and ' + str(num)
  390. else:
  391. gradeString += str(num) + ', '
  392.  
  393. print("Your grades are: " + gradeString)
  394.  
  395. print("Your grade average is: " + str(gradeAverage))
  396.  
  397. # BONUS
  398. import random
  399. def birthdayParadox(numOfPeople, numOfDays):
  400. birthdayList = []
  401. for i in range(numOfPeople):
  402. birthdayList.append(random.randint(0, 365))
  403. for day in range(numOfDays):
  404. numOfBirthdays = birthdayList.count(day)
  405. if numOfBirthdays > 1:
  406. return True
  407. return False
  408.  
  409. def testBirthdayParadox(numOfPeople, numOfDays, numOfTrials):
  410. trialOutcomeList = []
  411. for i in range(numOfTrials):
  412. trialOutcomeList.append(birthdayParadox(numOfPeople, numOfDays))
  413. proportionOfShared = trialOutcomeList.count(True) / len(trialOutcomeList)
  414. print(proportionOfShared)
  415.  
  416.  
  417.  
  418.  
  419.  
  420.  
  421.  
  422. classGrades = {'Daniel': 'C', 'Wyatt': 'F', 'Angelo': 'A++++++'}
  423.  
  424. print(classGrades.keys())
  425. # dict_keys(['Wyatt', 'Angelo', 'Daniel'])
  426. print(classGrades.values())
  427. # dict_values(['F', 'A++++++', 'C'])
  428. print(classGrades.items())
  429.  
  430. # dict_items([('Wyatt', 'F'), ('Angelo', 'A++++++'), ('Daniel', 'C')])
  431. print(classGrades.get('Professor Fox', 'Has no grade'))
  432. # 'Has no grade'
  433. print('Wyatt' in classGrades)
  434. # True
  435. print('Daniel' not in classGrades)
  436. # False
  437. print(classGrades['Wyatt'])
  438. # 'F'
  439. del classGrades['Angelo']
  440. print(classGrades)
  441. # {'Wyatt': 'F', 'Daniel': 'C'}
  442.  
  443. def userPassDict():
  444. userPswd = {}
  445. amountOfNames = 0
  446.  
  447. while amountOfNames < 5:
  448. userName = input('Enter your username: ')
  449. # Prevents the user from accidently overwriting password
  450. if userName in userPswd:
  451. print(userName + ' has already been entered! Enter a unique username')
  452. continue
  453. userPass = input ('Enter your password: ')
  454. userPswd[userName] = userPass
  455. amountOfNames += 1
  456.  
  457. while True:
  458. userName = input('Enter a username that you wish to know the password of (or hit enter to see none): ')
  459. if userName == '':
  460. break
  461. elif userName in userPswd:
  462. print('The password of "' + userName + '" is ' + userPswd[userName])
  463. break
  464. elif userName not in userPswd:
  465. print(userName + ' is not a valid username')
  466. print('Enter a valid username or hit enter to exit the loop')
  467.  
  468. print(userPswd)
  469.  
  470. import random
  471. def lotterySim():
  472. print('Time to gamble! Enter five integers from 0 to 9 inclusive!')
  473. userTicket = []
  474. amountOfNums = 0
  475. validNums = ['0','1','2','3','4','5','6','7','8','9']
  476.  
  477. while amountOfNums < 5:
  478. userNum = input('Enter number ' + str(amountOfNums+1) + ': ')
  479. if userNum not in validNums:
  480. print('Your number must be an integer between 0 and 9 (inclusive)!')
  481. continue
  482. userTicket.append(userNum)
  483. amountOfNums += 1
  484.  
  485. lottery = []
  486. correctGuesses = 0
  487. userTicketCopy = userTicket
  488. for i in range(5):
  489. lotteryNum = str(random.randint(0,9))
  490. lottery.append(lotteryNum)
  491. if lotteryNum in userTicketCopy:
  492. correctGuesses += 1
  493. userTicketCopy.remove(lotteryNum)
  494.  
  495. print('Your guesses were: ' + str(userTicket))
  496. print('The lottery numbers were: ' + str(lottery))
  497. if correctGuesses == 5:
  498. print('YOU WON THE JACKPOT')
  499. elif correctGuesses == 0:
  500. print('You had no matching numbers')
  501. else:
  502. print('You had ' + str(correctGuesses) + ' numbers. Maybe next time!')
  503.  
  504.  
  505.  
  506.  
  507.  
  508.  
  509. # 1
  510. def printSentence(name, age, numPets):
  511. print('%s is %.2f years old and has %d pets.' % (name, age, numPets))
  512.  
  513. # 2a
  514. def rightAlignNum(num):
  515. print('%20.2f' % (num))
  516.  
  517. # 2b
  518. def leftAlignNum(floatNum, intNum):
  519. print('%-20.2f %i' % (floatNum, intNum))
  520.  
  521. # 2c
  522. def leadingZeroNum(num):
  523. print('%020.2f' % (num))
  524.  
  525. # 3
  526. def createStatistics():
  527. rainfall = open('rainfall.txt', 'r')
  528. statistics = open('statistics.txt', 'w')
  529.  
  530. rainDict = {}
  531.  
  532. for line in rainfall:
  533. rainList = line.split()
  534. rainDict[rainList[0]] = rainList[1]
  535.  
  536. maxRainCity = max(rainDict, key = rainDict.get)
  537. minRainCity = min(rainDict, key = rainDict.get)
  538.  
  539. numOfValues = 0
  540. totalRain = 0
  541. for key in rainDict:
  542. totalRain += float(rainDict[key])
  543. numOfValues += 1
  544. averageRain = totalRain / numOfValues
  545.  
  546. statistics.write('%s has the most rain with %.2f inches.\n' % (maxRainCity, float(rainDict[maxRainCity])))
  547. statistics.write('%s has the least rain with %.2f inches.\n' % (minRainCity, float(rainDict[minRainCity])))
  548. statistics.write('The average amount of rain is %.2f inches.\n' % (averageRain))
  549.  
  550. rainfall.close()
  551. statistics.close()
  552.  
  553.  
  554.  
  555.  
  556.  
  557. # 1
  558. def convertStringNumbers():
  559. a = ['1', '2', '3']
  560. b = [int(x) for x in a]
  561. return b
  562.  
  563. # 5
  564. def addPositiveIntegers():
  565. numList = []
  566. while True:
  567. inputNum = input('Enter an integer: ')
  568. try:
  569. inputNum = int(inputNum)
  570. except ValueError:
  571. print('Enter an INTEGER!')
  572. continue
  573.  
  574. if inputNum >= 0:
  575. numList.append(inputNum)
  576. else:
  577. break
  578.  
  579. total = 0
  580. for num in numList:
  581. total += num
  582.  
  583. return total
  584.  
  585.  
  586.  
  587.  
  588.  
  589.  
  590. # 3
  591. def rot13(msg):
  592. alphabet = 'abcdefghijklmnopqrstuvwxyz '
  593. rot13Key = 'nopqrstuvwxyzabcdefghijklm '
  594. msg = msg.lower()
  595. rot13Msg = ''
  596. for char in msg:
  597. rot13Msg += rot13Key[alphabet.find(char)]
  598. return rot13Msg
  599.  
  600. #rot13('ncevy sbbyf')
  601. #'april fools'
  602.  
  603. # 4
  604. # Takes 1 parameter: numTerms, the number of terms
  605. # Returns the numTerms term of the Fibonacci sequence
  606. def fibonacci(n):
  607. if n == 1:
  608. fibList = [1]
  609. elif n == 2:
  610. fibList = [1, 1]
  611. else:
  612. fibList = [1, 1]
  613. currentValue = 2
  614. twoTermsAgo = 1
  615. oneTermAgo = 1
  616. for i in range(2, n):
  617. currentValue = twoTermsAgo + oneTermAgo
  618. twoTermsAgo = oneTermAgo
  619. oneTermAgo = currentValue
  620. return fibList
  621.  
  622.  
  623.  
  624.  
  625.  
  626. # 2
  627. # Takes no parameters
  628. # Prints all of rainfall.txt unformatted
  629. def printRainfall():
  630. rainfall = open('rainfall.txt', 'r')
  631. print(rainfall.readlines())
  632. rainfall.close()
  633.  
  634. # 3
  635. # Takes no parameters
  636. # Prints each line of rainfall.txt in a nice and clear format
  637. def printRainfallNicely():
  638. rainfall = open('rainfall.txt', 'r')
  639. for line in rainfall:
  640. rainList = line.split()
  641. rainLocation = rainList[0]
  642. rainInches = rainList[1]
  643. print(rainLocation + ' averages ' + rainInches + ' inches of rain per year')
  644. rainfall.close()
  645.  
  646. # 4
  647. # Takes no parameters
  648. # Writes each line of rainfall.txt in a nice and clear format to out.txt
  649. def writeRainfall():
  650. rainfall = open('rainfall.txt', 'r')
  651. outputFile = open('out.txt', 'w')
  652. for line in rainfall:
  653. rainList = line.split()
  654. rainLocation = rainList[0]
  655. rainInches = rainList[1]
  656. outputFile.write(rainLocation + ' averages ' + rainInches + ' inches of rain per year\n')
  657. outputFile.close()
  658. rainfall.close()
  659.  
  660. # 5
  661. # Takes no parameters
  662. # Returns the average amount of rainfall for all cities
  663. # The output (average rainfall) is 34.119600000000005
  664. def averageRainfall():
  665. rainfall = open('rainfall.txt', 'r')
  666. amountOfLocations = 0
  667. totalRainAmount = 0
  668. for line in rainfall:
  669. rainList = line.split()
  670. rainAmount = float(rainList[1])
  671.  
  672. amountOfLocations += 1
  673. totalRainAmount += rainAmount
  674.  
  675. averageRainAmount = totalRainAmount / amountOfLocations
  676. rainfall.close()
  677. return averageRainAmount
  678.  
  679. # 6
  680. # Takes no parameters
  681. # Returns the average amount of rainfall for only cities beginning with 'A'
  682. def averageRainfallInACities():
  683. rainfall = open('rainfall.txt', 'r')
  684. amountOfLocations = 0
  685. totalRainAmount = 0
  686. for line in rainfall:
  687. rainList = line.split()
  688. if rainList[0][0] == 'A':
  689. rainAmount = float(rainList[1])
  690. amountOfLocations += 1
  691. totalRainAmount += rainAmount
  692.  
  693. averageRainAmount = totalRainAmount / amountOfLocations
  694. rainfall.close()
  695. return averageRainAmount
  696.  
  697. # BONUS PART 1
  698. # Takes no parameters
  699. # Writes the lines of rainfall.txt in a nice and clear format, sorted by amount of rainfall, to out.txt
  700. def outputSortedRainfall():
  701. rainfall = open('rainfall.txt', 'r')
  702. outputFile = open('out.txt', 'w')
  703. rainAmountList = []
  704. rainLocationList = []
  705.  
  706. for line in rainfall:
  707. rainList = line.split()
  708. rainLocationList.append(rainList[0])
  709. rainAmountList.append(rainList[1])
  710.  
  711. sortedRainAmountList = sorted(rainAmountList)
  712. for amount in sortedRainAmountList:
  713. index = rainAmountList.index(amount)
  714. rainLocation = rainLocationList[index]
  715. outputFile.write(rainLocation + ' averages ' + amount + ' inches of rain per year\n')
  716.  
  717. outputFile.close()
  718.  
  719. # BONUS PART 2
  720. import random
  721. import math
  722. # Takes no parameters
  723. # Returns the standard deviation of the rainfall amount data set
  724. def standardDev():
  725. rainfall = open('rainfall.txt', 'r')
  726. rainAmountList = []
  727. for line in rainfall:
  728. rainList = line.split()
  729. rainAmountList.append(rainList[1])
  730.  
  731. total = 0
  732. amountOfItems = 0
  733.  
  734. for amount in rainAmountList:
  735. total += float(amount)
  736. amountOfItems += 1
  737. mean = total / amountOfItems
  738.  
  739. stdTotal = 0
  740. for item in rainAmountList:
  741. difference = float(item) - mean
  742. diffsq = difference ** 2
  743. stdTotal += diffsq
  744.  
  745. sdev = math.sqrt(stdTotal / (len(rainAmountList)-1))
  746. return sdev
  747.  
  748. # Takes no parameters
  749. # Writes a simulated amount of rainfall for the next 30 years to out.txt
  750. def simulateClimateData():
  751. rainfall = open('rainfall.txt', 'r')
  752. outputFile = open('out.txt', 'w')
  753.  
  754. average = averageRainfall()
  755. stdDev = standardDev()
  756. for i in range(2018, 2049):
  757. rainAmount = random.gauss(average, stdDev)
  758. outputFile.write('In the year ' + str(i) + ', there will be ' + str(rainAmount) + ' inches of rain\n')
  759.  
  760. outputFile.close()
  761. rainfall.close()
  762.  
  763.  
  764.  
  765.  
  766.  
  767.  
  768.  
  769.  
  770. # 3.18
  771. # Takes 1 parameter: myString, a string
  772. # Returns myString with all spaces removed
  773. def stripSpaces(myString):
  774. outputString = ''
  775. for ch in myString:
  776. if ch != ' ':
  777. outputString += ch
  778. return outputString
  779.  
  780. # 3.19
  781. # Takes 1 parameter: plaintText, a string
  782. # Returns the an encrypted form of plainText with the three-rail cipher
  783. def threeRailFenceCipher(plainText):
  784. rail1Chars = ''
  785. rail2Chars = ''
  786. rail3Chars = ''
  787. charCount = 0
  788. for ch in plainText:
  789. # There are four conditionals for three rails in order to have the rail-fence pattern
  790. if charCount == 0:
  791. rail1Chars += ch
  792. elif charCount == 1:
  793. rail2Chars += ch
  794. elif charCount == 2:
  795. rail3Chars += ch
  796. else:
  797. rail2Chars += ch
  798. # -1 is assigned to charCount so that it starts the next loop at 0
  799. charCount = -1
  800. charCount += 1
  801. cipherText = rail1Chars + rail2Chars + rail3Chars
  802. return cipherText
  803. # Example: threeRailFenceCipher('I am testing my string') returns 'I t sn mtsigm tigaenyr'
  804. # The grid for this rail-fence cipher would look like: ('-' represents nothingness)
  805. # I - - - - - - T - - - - - - S - - - N -
  806. # - - M - T - S - I - G - M - - T - I - G
  807. # - - A - - - E - - - N - - - Y - - - R - - -
  808.  
  809. # 4.1
  810. myList = [7, 9, 'a', 'cat', False]
  811.  
  812. # 4.2
  813. myList.append(3.14)
  814. myList.append(7)
  815. myList.insert(3, 'dog')
  816. myList.index('cat')
  817. myList.count(7)
  818. myList.remove(7)
  819. myList.pop(2)
  820. # The following line would also remove 'dog' from the list, but
  821. # 'dog' is no longer in myList, so the following line will cause an error
  822. #myList.remove('dog')
  823.  
  824. # 4.3
  825. 'the quick brown fox'.split(' ')
  826.  
  827. # 4.4
  828. 'mississippi'.split('i')
  829.  
  830. # 4.5
  831. # Takes 1 parameter: sentence, a string of words
  832. # Returns the amount of words in that string
  833. def numOfWords(sentence):
  834. listOfWords = sentence.split(' ')
  835. numOfWords = len(listOfWords)
  836. return numOfWords
  837.  
  838. # 4.6
  839. # Takes 2 parameters: aList, a list; item, an item in the list
  840. # Returns the amount of times that item is within aList
  841. def my_count(aList, item):
  842. itemCount = 0
  843. for el in aList:
  844. if el == item:
  845. itemCount += 1
  846. return itemCount
  847.  
  848. # Takes 2 parameters: aList, a list; item, an item in the list
  849. # Returns True if item is in aList, or False if it is not
  850. def my_in(aList, item):
  851. for el in aList:
  852. if el == item:
  853. return True
  854. return False
  855.  
  856. # Takes 1 parameters: aList, a list
  857. # Returns aList in the opposite order
  858. def my_reverse(aList):
  859. reversedList = []
  860. for el in aList:
  861. reversedList.insert(0, el)
  862. return reversedList
  863.  
  864. # Takes 2 parameters: aList, a list; item, an item in the list
  865. # Returns the index of the first occurence of item in aList or -1 if item is not in aList
  866. def my_index(aList, item):
  867. for i in range(len(aList)):
  868. if item == aList[i]:
  869. return i
  870. return -1
  871.  
  872. # Takes 3 parameters: aList, a list; item, an item in the list; index, an integer
  873. # Returns aList with item inserted at the position of index
  874. def my_insert(aList, item, index):
  875. outputList = []
  876. i = 0
  877. for el in aList:
  878. if index == i:
  879. outputList.append(item)
  880. outputList.append(el)
  881. i += 1
  882. return outputList
  883.  
  884. # 4.11
  885. #myList[1].append(2)
  886. # This code does not work...
  887. # AttributeError: 'str' object has no attribute 'append'
  888. # This is because myList[1] is 'a', a string
  889. # A string cannot be appended to, so 'a'.append(2) results in an error.
  890.  
  891.  
  892.  
  893.  
  894.  
  895.  
  896.  
  897.  
  898. # 1
  899. # Takes 0 parameters
  900. # Prompts the user for two words, word1 and word2, to be compared
  901. # Returns True if all of word1's characters are within word2, and False if otherwise
  902. def compareWords():
  903. word1 = input('Enter the first word: ')
  904. word2 = input('Enter the second word: ')
  905. for ch in word1:
  906. if ch not in word2:
  907. return False
  908. return True
  909.  
  910. # 2
  911. # Takes 1 parameter: my_string, a string
  912. # Returns a dictionary containing the frequency of vowels within my_string
  913. def count_vowels(my_string):
  914. vowelDict = {}
  915. for ch in my_string:
  916. if ch in 'aeiou':
  917. vowelDict[ch] = vowelDict.get(ch, 0) + 1
  918. return vowelDict
  919.  
  920. # 3
  921. # Takes 1 parameter: my_dict, a dictionary containing values corresponding to temperatures
  922. # Returns the keys of that dictionary that would be considered 'moderate' (between 70 and 79)
  923. def moderate_days(my_dict):
  924. dayList = []
  925. for key in my_dict:
  926. if my_dict[key] >= 70 and my_dict[key] <= 79:
  927. dayList.append(key)
  928. return dayList
  929.  
  930. # 4
  931. # Takes no parameters, but takes a phone number from the user as input (inputNum)
  932. # Returns inputNum but with the letters within inputNum replaced with their corresponding number
  933. def reverse_phone():
  934. inputNum = input('Enter a phone number to be converted: ')
  935. comparisonDict = {'a': 2, 'b': 2, 'c': 2,
  936. 'd': 3, 'e': 3, 'f': 3,
  937. 'g': 4, 'h': 4, 'i': 4,
  938. 'j': 5, 'k': 5, 'l': 5,
  939. 'm': 6, 'n': 6, 'o': 6,
  940. 'p': 7, 'q': 7, 'r': 7, 's': 7,
  941. 't': 8, 'u': 8, 'v': 8,
  942. 'w': 9, 'x': 9, 'y': 9, 'z': 9}
  943.  
  944. outputList = []
  945. keyList = list(comparisonDict.keys())
  946. for ch in inputNum:
  947. if ch in keyList:
  948. outputList.append(str(comparisonDict[ch]))
  949. else:
  950. outputList.append(ch)
  951.  
  952. outputNum = ''.join(outputList)
  953. return outputNum
  954.  
  955. # 5
  956. # Takes no parameters
  957. # Reads from hw7Text.txt, and writes output to hw7TextOutput.txt
  958. # Writes a fancy table of the freqeuency of different words in hw7TextOutput
  959. def outputFrequencies():
  960. inputFile = open('hw7Text.txt', 'r')
  961. outputFile = open('hw7TextOutput.txt', 'w')
  962. outputFile.write('%-13s%s\n' % ('Word', 'Frequency'))
  963. outputFile.write('#######################\n')
  964.  
  965. wordFreqDict = {}
  966. for line in inputFile:
  967. wordList = line.split()
  968. for word in wordList:
  969. wordFreqDict[word] = wordFreqDict.get(word, 0) + 1
  970.  
  971. for key in sorted(wordFreqDict):
  972. outputFile.write('%-17s%d\n' % (key + ':', wordFreqDict[key]))
  973. outputFile.write('-----------------------\n')
  974.  
  975. inputFile.close()
  976. outputFile.close()
  977.  
  978. # 6
  979. # Takes no parameters
  980. # Reads from barCodes.txt
  981. # Checks if the check sum digit of each bar code is correct or not using an algorithm
  982. # Prints the UPC Code, the Checksum, and the result of the test (True if correct Checksum, False otherwise)
  983. def verifyCheckSums():
  984. barCodesFile = open('barCodes.txt', 'r')
  985. for line in barCodesFile:
  986. upc = line[0:11]
  987. checkSum = int(line[11])
  988.  
  989. oddSum = 3 * (int(upc[0]) + int(upc[2]) + int(upc[4]) + int(upc[6]) + int(upc[8]) + int(upc[10]))
  990. evenSum = int(upc[1]) + int(upc[3]) + int(upc[5]) + int(upc[7]) + int(upc[9])
  991. remainderOfSum = (oddSum + evenSum) % 10
  992. calculatedCheckSum = 10 - remainderOfSum
  993. if calculatedCheckSum == 10:
  994. calculatedCheckSum = 0
  995.  
  996. if calculatedCheckSum == checkSum:
  997. result = True
  998. else:
  999. result = False
  1000.  
  1001. print('UPC Code: %s' % (''.join(upc)))
  1002. print('Checksum Digit: %d' % (checkSum))
  1003. print(result)
  1004.  
  1005. barCodesFile.close()
  1006.  
  1007.  
  1008.  
  1009.  
  1010. # Takes 2 parameters:
  1011. # salaryDict, a dictionary where the keys are people and the values are their salaries
  1012. # bonus, an integer amount to be added to each person's salaries
  1013. # Returns a dictionary with the same people and their new salaries
  1014. def addBonusToSalary(salaryDict, bonus):
  1015. salaryList = list(salaryDict.keys())
  1016. salaryWithBonusDict = salaryDict
  1017. for employee in salaryList:
  1018. salaryWithBonusDict[employee] += bonus
  1019. return salaryWithBonusDict
  1020.  
  1021. # Takes 1 parameter: englishString, a string containing phrases in plain English
  1022. # Translates this plain English string into a pirate English string
  1023. # Works with single words and two-word phrases, such as 'excuse me'
  1024. def toPirate(englishString):
  1025. pirateTranslationDictionary = {
  1026. 'hello': 'avast',
  1027. 'excuse me': 'arrr',
  1028. 'sir': 'matey',
  1029. 'boy': 'matey',
  1030. 'man': 'matey',
  1031. 'madam': 'proud beauty',
  1032. 'officer': 'foul blaggart',
  1033. 'the': 'th\'',
  1034. 'my': 'me',
  1035. 'your': 'yer',
  1036. 'is': 'be',
  1037. 'are': 'be',
  1038. 'restroom': 'head',
  1039. 'restaurant': 'galley',
  1040. 'hotel': 'fleabag inn',
  1041. 'yes': 'aye',
  1042. 'woah': 'blimey',
  1043. 'treasure': 'booty',
  1044. 'reward': 'bounty',
  1045. 'pirate': 'buccaneer',
  1046. 'song': 'chantey',
  1047. 'hell': 'Davy Jone\' Locker',
  1048. 'six feet': 'fathom',
  1049. 'water': 'rum',
  1050. 'kid': 'lad',
  1051. 'money': 'loot',
  1052. 'rookie': 'scallywag',
  1053. 'veteran': 'seadog',
  1054. }
  1055.  
  1056. englishWordList = englishString.split(' ')
  1057. pirateWordList = []
  1058. pirateDictionaryWordList = pirateTranslationDictionary.keys()
  1059.  
  1060. i = 0
  1061. while i < len(englishWordList):
  1062. englishWord = englishWordList[i]
  1063. if i+1 < len(englishWordList):
  1064. nextEnglishWord = ' ' + englishWordList[i+1]
  1065. else:
  1066. nextEnglishWord = ''
  1067.  
  1068. englishTwoWordPhrase = englishWord + nextEnglishWord
  1069. if englishTwoWordPhrase in pirateDictionaryWordList and englishTwoWordPhrase != englishWord:
  1070. pirateWordList.append(pirateTranslationDictionary[englishTwoWordPhrase])
  1071. i += 1
  1072. elif englishWord in pirateDictionaryWordList:
  1073. pirateWordList.append(pirateTranslationDictionary[englishWord])
  1074. else:
  1075. pirateWordList.append(englishWord)
  1076.  
  1077. i += 1
  1078.  
  1079. pirateString = ' '.join(pirateWordList)
  1080. return pirateString
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement