Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

python 3.x - Largest number from a file without using array implementation

Basically, the assignment asks for the program to open a file, find the largest number, and count the amount of numbers in the file. Our instructor has told us not to use array implementation and I'm not sure if my code counts as using it. I don't know how to convert it without using array implementations.

    def main():

        infile = open('numbers.dat', 'r')
        numbers = []
        for line in infile:
            numbers.append(int(line))
        infile.close()

        largest = max(numbers)
        print('The largest number in the file is: ',largest)

        count = len(numbers)
        print('The amount of numbers in the file is: ', count)
    main()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, I think your code counts as using it. Your instructor probably doesn't want you to store all the numbers - luckily you don't have to.

Since this is an assessed exercise I won't write your code for you, but I'll explain the basic approach. You need to just keep two integers to do this - one number is the count of the numbers you've seen in the file so far, the other one is the largest number so far. For each number you read, you store the max() of the largest so far and then number you've just seen, and you simply add one to the counter.

One gotcha - if you start the largest number at zero, then you'll get an incorrect result if all the numbers in the file are negative. You don't specify whether negative numbers are allowed, but it's potentially valid. To avoid this, initialise the value with None to start with, and then just set it to the first number that you see in the file if the value is None.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...