Euler 22代码没有返回正确的答案

时间:2018-05-14 12:59:19

标签: python python-3.x list

我一直在尝试在项目Euler上做问题22,但我似乎无法得到正确的答案或看到我的代码有任何问题。我复制并粘贴了txt文件的内容,而不是直接从我的代码中访问它。

https://projecteuler.net/problem=22

namelst = open(names.txt)
namedict = {} 
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
for x in namelst: 
  score = 0   #creates score for each word
  for y in x: 
    score += alphabet.index(y.lower())+1   #adds alphabetic score for each letter 
  namedict[x] = score

namedict = sorted(namedict.values())   #creates list of scores ordered by size 
scoresum = 0
for x in namedict:
  index = namedict.index(x)+1
  scoresum += x*index   #multiplies score sum by order in the list

print(scoresum)

不幸的是,这给了我985466567的答案,而871198282是正确答案。我的代码或方法有错误吗?

如果有人能提供帮助那就太棒了!

1 个答案:

答案 0 :(得分:0)

你很亲密。您的代码存在一些问题:

  1. namedict不是字典,而是列表。
  2. 要求是按名称而不是按值按字母顺序排序。
  3. 您需要使用或存储已排序列表的索引。我为此使用了enumerate
  4. 结合这些元素:

    from string import ascii_lowercase
    
    namelst = ['abc', 'def', 'ghi']
    namedict = {} 
    alphabet = ascii_lowercase
    
    for x in namelst: 
        score = 0
        for y in x: 
            score += alphabet.index(y.lower())+1
        namedict[x] = score
    
    namelist = sorted(namedict.items(), key=lambda x: x[1])
    
    print(namelist)
    # [('abc', 6), ('def', 15), ('ghi', 24)]
    
    scoresum = 0
    for idx, x in enumerate(namelist, 1):
        scoresum += idx*x[1]
    
    print(scoresum)
    # 108, i.e. 6 + 30 + 72