#________________________________________________________________________
 
#6.py
 
# Read in numbers from a file and find the minimum and maximum.
# We'll use the same file as in the first example, "data.txt"
 
import sys
 
def  min(file):   # returns min
    incoming = open(file,"r")    
    n = 0   
    for line in incoming:  #we assume datafile has at least one number
        newdata = float(line)
        n = n + 1       
        if (n == 1):
            min = newdata
        else:
              if (newdata < min):
                      min = newdata

                      
    if (n ==0):
            print("File is empty\n")
            sys.exit(0)
    incoming.close()
    return(min,n)
 
def  max(file):   # returns max
    incoming = open(file,"r")    
    n = 0   
    for line in incoming:  #we assume datafile has at least one number
        newdata = float(line)
        n = n + 1       
        if (n == 1):
            max = newdata
        else:
              if (newdata > max):
                      max= newdata

                      
    if (n ==0):
            print("File is empty\n")
            sys.exit(0)
    incoming.close()
    return(max,n)
 
 
def main():
 
 
    minimum,number = min("data.txt")
 
    print("The minimum of all",number," numbers in the given file is:" ,minimum)
    print(" ")
 
    maximum,number = max("data.txt")
 
    print("The maximum of all",number," numbers in the given file is:" ,maximum)
    print(" ")
 
 
main()
 
'''
When you "analyze" how much work this algorithm has to do to find the min or max
you need to ask what is the basic unit of work you are counting?
 
Well, suppose that 1 unit of work = 1 comparison of two numbers
 
So, how many comparisons are being done to find the min (or max) ?
 
Let's say there are a total of n numbers in a list (or array)
 
You cannot know which number is the min (or max) without comparing the current
min or current max to the rest of the numbers in the list
 
At the start, the current min is the first number
 
And this has to be compared to the remaining (n-1) numbers
 
So the work =  (n-1) comparisons for min, and (n-1) comparisons for max
 
Now n and (n-1) differ only by 1 comparision, and that 1 is negligible for n large
 
(we are always focused on "n large")
 
This, this is an O(n) algorithm (i.e., "Big-Oh of n") for an n-element  list
 
both for min and max. This is called a "linear time algorithm", since it's linear in n.
 
'''
 
# Homework: Try to combine both functions into a single function that returns the pair (min,max),
# where min is minimum, and max is maximum 
 
# If you use the above idea, the amount of work (i.e., number of comparisons) required
# by your combined algorithm will be O(2n).
 
# Question: Can we make the code run faster?
# Answer: Well, yes ..... provided we can reduce the number of comparisons to get the result.
 
#_____________________________________________________________________
