Euler Project : Problem 22

来源:互联网 发布:大数据培训内容 编辑:程序博客网 时间:2024/06/05 01:13

题面是这样的:

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 × 53 = 49714.
What is the total of all the name scores in the file?

首先针对所有的字符串进行排序,然后再计算score,这个数据量其实不大,总共5164条item。

通过python实现的也许是最简单的代码了:

def main():    fd = open('p022_names.txt', 'r')    contents = fd.readline().replace('"', '').split(',')    contents.sort()    value = 0    index = 1    for each in contents:        value += cal_val(each)*index        index += 1    print value    fd.close()    return
#时间开销:real    0m0.112suser    0m0.042ssys     0m0.022s

最开始的时候自己写了个字符串排序的算法,发现耗时比自带的sort长很多:

real    0m7.218suser    0m7.178ssys     0m0.024s

源码如下:

# _*_ coding: utf8 _*_def cal_val(string):    value = 0    for eachCH in string:        value += ord(eachCH)-ord('A')+1    return valuedef min(a, b):    if a < b:        return a    else:        return bdef compare_string(srcStr, dstStr):    for pos in range(min(len(srcStr), len(dstStr))):        if ord(dstStr[pos]) > ord(srcStr[pos]):            return -1        elif ord(dstStr[pos]) < ord(srcStr[pos]):            return 1    if pos < len(dstStr)-1:        return -1    elif pos < len(srcStr)-1:        return 1    else:        return 0def queue_string(strList, string):    newList = []    endPOS = len(strList)-1    for eachPOS in range(len(strList)):        if compare_string(strList[eachPOS], string) > 0:            endPOS += 1            break        #newList.append(strList[eachPOS])    #print endPOS    newList = strList[0:eachPOS]    newList.append(string)    newList = newList + strList[eachPOS:endPOS]    return newListdef main():    fd = open('p022_names.txt', 'r')    contents = fd.readline().replace('"', '').split(',')    nameList = [contents[0]]    for eachStr in contents[1:]:        nameList = queue_string(nameList, eachStr)    #print nameList    fd.close()if __name__ == "__main__":    main()

python自带的sort估计是基于C语言实现的,而我实现的代码运行在解释器上,这是一个很大的差别,还有如果从已排序的字符串列表尾部开始比较是不是能减少比较次数,但这是数据特征决定的,只能算针对性优化。

原创粉丝点击