コード例 #1
0
#
# 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 (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, how many are triangle words?

from myUtils import dequote, wordValue

with open('p042_words.txt') as f:
    data = f.read()

triangleNumbers = [1, 3, 6, 10, 15, 21, 28, 36, 45, 55]

listOfWords = list(map(dequote, data.split(',')))

result = 0
for word in listOfWords:
    value = wordValue(word)

    while value > triangleNumbers[-1]:
        # we need more tringle numbers in 'triangleNumbers'
        n = len(triangleNumbers)
        triangleNumbers.append(n*(n+1)//2)

    if value in triangleNumbers:
        result += 1

print ("Result:", result)
コード例 #2
0
# Names scores
# Problem 22
#
# Using names.txt (right click and 'Save Link/Target As...'),
# a 46K text file containing over five-thousand first names,
# begin by sorting it into alphabetical order.
# Then working out the alphabetical value for each name,
# multiply this value by its alphabetical position in the list to obtain a name score.
#
# For example, when the list is sorted into alphabetical order,
# COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list.
# So, COLIN would obtain a score of 938 x 53 = 49714.
#
# What is the total of all the name scores in the file?

import string
from myUtils import dequote, wordValue

# with statement with file object: opens file in 'r' mode, closes file on exit
with open('p022_names.txt') as f:
    data = f.read()

listOfNames = list(map(dequote, data.split(',')))
listOfNames.sort()

result = 0
for i in range (0, len(listOfNames)):
    result += (i + 1) * wordValue(listOfNames[i])

print ("Result:", result)