Problem #42

Another prob­lem solved! This prob­lem intro­duced me to some util­ity func­tions in python that I did not pre­vi­ously know about. It involved the gen­er­a­tion of two lists, check­ing if a list con­tains a spe­cific value, read­ing a file, con­vert­ing a char­ac­ter into it’s ASCII num­ber, and keep­ing track of time inter­nal to the program.

Check­ing a List for Items
I searched and came across this expla­na­tion of the in oper­a­tor. Some­how I either missed it or haven’t had enough caf­feine today. I use in all the time with loop­ing con­structs like for line in file but never real­ized that it pro­duced a Boolean output.

ASCII Val­ues of Char­ac­ters
This prob­lem required the abil­ity to assign a numer­i­cal value to each let­ter. To do this I used a stan­dard func­tion named ord.

ord(“A”) # Returns 65 — the base10 ASCII Value

Con­vert­ing it to hex is sim­ple with the func­tion named hex

hex(ord(“A”)) # Returns ‘0x41’

Below is the code:


import time

# Glob­als
tri_numbers = []
total = 0

def calc_value(word):
    value = 0
    for chr in list(word):
        value += ord(chr)64
    return value

def populate_triangle_numbers(max):
    for n in range(1,max+1):

start = time.time()

file = open(“words.txt”)
words =­line().split(”,”)

for word in words:
    word = word.replace(\”, “”)
    value = calc_value(word)
    if value in tri_numbers:
        total += 1
stop = time.time()

print “Count: ” + str(total)
print “Run­time: ” + str(stop — start)

Leave a Reply