princeofsudan

ProjectEuler#42 Coded triangle numbers

Mar 29th, 2013
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.74 KB | None | 0 0
  1. #The nth term of the sequence of triangle numbers is given by,
  2. #tn = (n(n+1))/2; so the first ten triangle numbers are:
  3.  
  4. #1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
  5.  
  6. #By converting each letter in a word to a number corresponding to its
  7. #alphabetical position and adding these values we form a word value.
  8. #For example, the word value for SKY is 19 + 11 + 25 = 55 = t10.
  9. #If the word value is a triangle number then we shall call the word
  10. #a triangle word.
  11.  
  12. #Using words.txt (right click and 'Save Link/Target As...'), a 16K text
  13. #file containing nearly two-thousand common English words,
  14. #how many are triangle words?
  15.  
  16. #An integer x is triangular if and only if 8x + 1 is a square.
  17. #Source: http://en.wikipedia.org/wiki/Triangular_number
  18. #Section: Triangular roots and tests for triangular numbers
  19.  
  20. import string
  21.  
  22. def isPerfectSquare(n):
  23.     if n < 0:
  24.         return False
  25.     result = int(n**0.5)
  26.     return result*result == n
  27.      
  28. def isTriangle(n):
  29.     return isPerfectSquare((8*n)+1)
  30.  
  31. def namesFile2List(fileName):
  32.     namesHandle = open(fileName,'r')
  33.     namesString = namesHandle.readline()
  34.     namesHandle.close()
  35.     namesListTemp = namesString.split(',')
  36.     namesList = []
  37.     for i in namesListTemp:
  38.         namesList.append(i.strip('"'))
  39.     return namesList
  40.  
  41. def createUCCoder():
  42.     coderDict = {}
  43.     upperCase = string.ascii_uppercase
  44.     for i in range(len(upperCase)):
  45.         coderDict[upperCase[i]] = i+1
  46.     return coderDict
  47.  
  48. namesList = namesFile2List('words.txt')
  49. coderDict = createUCCoder()
  50.  
  51. numOfTriWords = 0
  52. for name in namesList:
  53.     wordValue = 0
  54.     for letter in name:
  55.         wordValue += coderDict[letter]
  56.     if isTriangle(wordValue):
  57.         numOfTriWords += 1
  58. print numOfTriWords
Advertisement
Add Comment
Please, Sign In to add comment