Skip to content Skip to sidebar Skip to footer

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 imp

Solution 1:

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.

Solution 2:

You're not using arrays, but lists. This is inefficient as your program needs memory in order of the file size, but only needs significantly less (i.e. enough memory to hold the largest and the count of lines).

One could simply call max and len on the elements of the file, like this:

defmain():
    withopen('numbers.dat', 'r') as infile:
        largest = max(map(int, infile))
        print('The largest number in the file is: ',largest)

    withopen('numbers.dat', 'r') as infile:
        count = sum(1for line in infile)
        print('The amount of numbers in the file is: ', count)
main()

However, both variants are obviously suboptimal since you'd need to read the file twice. Instead, you can modify your for loop, like this:

defmain():
    largest = float('-inf')
    count = 0withopen('numbers.dat', 'r') as infile:
        for line in infile:
            v = int(line)
            # Left as homework: Update largest and countprint('The largest number in the file is: ',largest)
    print('The amount of numbers in the file is: ', count)

Post a Comment for "Largest Number From A File Without Using Array Implementation"