关于python:此代码未显示正确答案

This code isn't displaying the correct answer

1
2
3
4
5
6
7
8
9
10
11
dictionary = open('dictionary.txt','r')
def main():
    print("part 4")
    part4()
def part4():
    naclcount = 0
    for words in dictionary:
        if 'nacl' in words:
            naclcount = naclcount + 1
    return naclcount
main()

基本上,它附带了答案25,这是正确的,除了我在第4部分前面放入另一个函数时,它将打印为0。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def part1():
    vowels = 'aeiouy'
    vowelcount = 0
    for words in dictionary:
        words = words.lower()
        vowelcount = 0
        if len(words) == 8:
            if 's' not in words:
                for letters in words:
                    if letters in vowels:
                        vowelcount += 1
                if vowelcount == 1:
                    print(words)
    return words


您可能应该将文件名作为参数传递给part4函数,然后创建一个新的文件对象,因为当您对它进行一次迭代时,它将停止返回新行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
def main():
    dict_filename = 'dictionary.txt'
    print("part 4")
    part4(dict_filename)


def part1(dict_filename):
    vowels = 'aeiouy'
    vowelcount = 0
    dictionary = open(dict_filename,'r')
    for words in dictionary:
        words = words.lower()
        vowelcount = 0
        if len(words) == 8:
            if 's' not in words:
                for letters in words:
                    if letters in vowels:
                        vowelcount += 1
                if vowelcount == 1:
                    print(words)
    return words

def part4(dict_filename):
    dictionary = open(dict_filename,'r')
    naclcount = 0
    for words in dictionary:
        if 'nacl' in words:
            naclcount = naclcount + 1
    return naclcount

main()

此外,如果希望能够将脚本用作导入模块或独立模块,则应使用

1
2
3
4
if __name__ == '__main__':
    dict_filename = 'dictionary.txt'
    print("part 4")
    part4(dict_filename)

代替main功能


你能再粘贴一个函数吗?这个问题不清楚,除非你展示你的另一个功能。

根据我从你的问题和代码推断出来的。我已经修改(清除)了你的代码。看看是否有帮助。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def part4(dictionary):
    words = dictionary.readlines()[0].split(' ')
    nacl_count = 0
    for word in words:
        if word == 'the':
            nacl_count += 1
        #print nacl_count
    return nacl_count


def part1(dictionary):
    words = dictionary.readlines()[0].split(' ')
    words = [word.lower() for word in words]
    vowels = list('aeiou')
    vowel_count = 0
    for word in words:
        if len(word) == 8 and 's' not in word:
            for letter in words:
                if letter in vowels:
                    vowel_count += 1
        if vowel_count == 1:
            #print(word)
            return word


def main():
    dictionary = open('./dictionary.txt', 'r')
    print("part 1")
    #part1(dictionary)
    print("part 4")
    part4(dictionary)


main()