【问题标题】:Euler 22 code not returning correct answerEuler 22 代码未返回正确答案
【发布时间】:2018-05-14 12:59:19
【问题描述】:

我一直在尝试解决 Project 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 是正确的答案。我的代码或方法有什么错误吗?

如果有人可以提供帮助,那就太好了!

【问题讨论】:

    标签: python python-3.x list


    【解决方案1】:

    你很接近。您的代码存在一些问题:

    1. namedict 不是字典,而是列表。
    2. 要求是按名称的字母顺序排序,而不是按值排序。
    3. 您需要使用或存储排序列表的索引。我为此使用enumerate

    结合这些元素:

    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
    

    【讨论】:

    • 非常感谢,非常有帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多