Skip to content
Advertisement

How to find the maxValue’s line number in one loop?

here’s the code:
Tips how to simplify the code are welcome

eqlCounter = 0
octals = []
with open("D:maturaMatura2017Dane_PR2liczby.txt", "r") as f: #file contains 2 sets of numbers(1st decimal, second octal)
    for x in f:
        lines = f.readline()
        splited = lines.split()
        toInt = int(splited[1], 8) #oct to int(dec)
        octals.append(toInt)
        if int(splited[0]) == toInt:
            eqlCounter += 1
    print("same nmbrs: ", eqlCounter) #a
    print("min: ", min(octals),"at: ")
    print("max: ", max(octals),"at: ")

I would like to find a position of the line that contains the max value(already found that value) I know i can just use another loop to find the placement, but i wonder if there’s a shorter and more efficient way to do it

Advertisement

Answer

There’s a method to find the position of a value in an iterable: index.

low = min(octals)
print("min: ", low ,"at: ", octals.index(low))

Another possibility is to track the extremes and their positions as you iterate through the file. For instance:

low = 99999999999999999999999999999999999999999999999999
with ...
    for idx, x in enumerate(f):
        if toInt < low:
            low = toInt
            low_pos = idx

Treat the high element similarly.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement