Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...