I am relatively new to programming and have been recommended to work through the many tasks in order, in order to better my skills. For some reason, problem 42 had me stumped for a while:
The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, …
By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word.
Using words.txt, a 16K text file containing nearly two-thousand common English words, how many are triangle words?
The following is my beginner-level code, and I was wondering whether any of you wonderful people would help me improve it and give me some tips for the future. In retrospect, I should have probably reused some code from problem 22 since they involve the same skills.
def calculate_total(word):
alphabet = {'a':1, 'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,'m':13,'n':14,'o':15,'p':16,'q':17,'r':18,'s':19,'t':20,'u':21,'v':22,'w':23,'x':24,'y':25,'z':26}
total = 0
index = 1
while word[index] != '"':
total += alphabet[word[index].lower()]
index += 1
return total
def gen_triangles(limit):
triangles = [0, 1]
index = 1
while triangles[index] <= limit:
triangles.append(((index ** 2) + index) // 2)
index += 1
return sorted(list(set(triangles)))
def binary_search(aList, itemToFind, first, last):
if last < first:
#print(itemToFind + "not in list")
return False
else:
midpoint = (first + last)//2
if aList[midpoint] > itemToFind:
return binarySearch(aList, itemToFind, first, midpoint - 1)
else:
if aList[midpoint] < itemToFind:
return binarySearch(aList, itemToFind, midpoint + 1, last)
else:
#print(str(itemToFind) + " Found at position: " + str(midpoint))
return True
def solution():
myFile = open('Words.txt', 'r')
wordsArray = myFile.read().split(',')
for i in range(0, len(wordsArray)):
wordsArray[i] = calculate_total(wordsArray[i])
triangles = gen_triangles(max(wordsArray))
wordTriangles = []
lengthTriangles = len(triangles) - 1
for i in range(0, len(wordsArray)):
#print('i:', i, 'current index:', wordsArray[i])
if binarySearch(triangles, wordsArray[i], 0, lengthTriangles) == True:
wordTriangles.append(wordsArray[i])
print(len(wordTriangles))
solution()
I have been teaching myself some computing theory and have seen that Python's built-in searching keyword in
performs a linear search on the array so I decided to branch out and see if I can make my own binary search, which seemed to have worked :D
What was a surprise to me was that this actually runs really quickly. To all of you guys, though, this is probably a huge mess, but hey, that's why I'm here!