如果回答不正确,函数按其应该的方式运行

2024-04-25 01:48:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我相信你们都会有很多这样的问题,但我只是需要更多的眼睛,因为我找不到问题所在。我要问两件事,一件是谁回答:

  • 我的代码有什么问题导致我得到不正确的答案?你知道吗
  • 你到底是怎么发现这个问题的?你知道吗

Project Euler #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 × 53 = 49714.

What is the total of all the name scores in the file?

他们给你的名字列表的格式如下:

"MARY","PATRICIA","LINDA","BARBARA","ELIZABETH","JENNIFER","MARIA","SUSAN","MARGARET","DOROTHY","LISA","NANCY"

代码如下:

import datetime, string, pprint

def get_rawdata():
    # Use data = getRawData()
    with open('e22-data') as f:  #e22-data is the list of names
        rawdata = [line.strip('"').split('","') for line in f]
        return rawdata

def alphabetize(data):
    data[0].sort()

    return data

def score_letters(data):
    scores = []
    for n in data[0]:
        score = 0
        for l in n:
            score += alpha.index(l)+1
        scores.append(score)
    return scores

def score_placement(scores):
    products = []
    for n in scores:
        products.append(n*(scores.index(n)+1))
    return products


alpha = string.ascii_uppercase

data = get_rawdata()
data = alphabetize(data)
pprint.pprint(data)
scores = score_letters(data)
products = score_placement(scores)

answer = sum(products)
print(answer)

Tags: thenameinfordatareturnnamesis
1条回答
网友
1楼 · 发布于 2024-04-25 01:48:44

您的代码基本上是正确的,但是score_placement()有一个细微的错误。您的代码:

def score_placement(scores):
    products = []
    for n in scores:
        products.append(n*(scores.index(n)+1))
    return products

它查看每个单独的得分值(从49、35、19开始,…),尝试找到值出现的第一个索引(使用^{}),并执行乘法。你知道吗

这种方法的问题在于,它假设每个分数都是唯一的。如果列表后面出现另一个49分,它将使用找到的前49分的索引(在基于1的系统中是1)。你知道吗

因此,您需要同时查看每个分数和每个索引,而不是试图以迂回的方式查找索引。这种改进的算法既正确又更省时(On)vs.On2)。有一种方法score_placement()可以正确地写入:

def score_placement(scores):
    products = []
    for i in range(len(scores)):
        products.append((i+1)*scores[i])
    return products

有了这个小小的改变,整个程序运行产生正确的答案!你知道吗

注意事项:

  • 也可以使用enumerate()实现这个逻辑。你知道吗
  • 你问我是怎么调试的。我以前有solved这个项目的Euler问题,所以我很熟悉它的工作原理。我查看了代码底部的5条主要数据处理语句,打印出了一些值,并将这些数字与直觉告诉我的答案进行了比较。我发现了一些可疑的行为,所以我回到了score_placement()函数中,阅读了代码,发现了逻辑错误。最后,我实现了一个建议的修复程序,并运行它来验证它是否有效。你知道吗

相关问题 更多 >