Home > Back-end >  print average and the cost per liter in the text file using python
print average and the cost per liter in the text file using python

Time:10-31

I'm trying to get the average of the cost value and the cost per liter.

r = []
with open('petrolPrice.txt') as f1:
    r = f1.read()
    s = r.split()
    del s[0]
    s.pop(0)
    
    print(sum(s) / len(s)) # AVERAGE COST
    
with open('petrolPrice.txt') as f1:
    r = f1.read()
    s = r.split()
    s.pop(0)
    
    # COST PER LITER

Here is the text file below. The liters and cost are divided using tab space

Liters  Cost
20.0    56.40
9.6 29.95
5.0 15.60
15.0    54.30
18.4    65.32
18.7    75.36
17.7    80.00

print average and the cost per liter in the text file.

CodePudding user response:

import pandas as pd
with open("input.txt") as f:
    lines = f.readlines()
    #get first value of every line as Liters 
    liters = [(line.split()[0]) for line in lines if line.split()[0] != 'Liters']
    #get second value of every line as Cost
    cost = [(line.split()[1]) for line in lines if line.split()[1] != 'Cost']
    #df with Liters and Cost
    df = pd.DataFrame({'Liters': liters, 'Cost': cost})
    #add column with cost per liter
    df['Cost per liter'] = df['Cost'].astype(float) / df['Liters'].astype(float)
    #add row with mean
    df.loc[len(liters)] = [df['Liters'].astype(float).mean(), df['Cost'].astype(float).mean(), df['Cost per liter'].astype(float).mean()]
    #df to text
    df.to_csv('output.txt', sep='\t', index=False)

CodePudding user response:

Open the file reading one line at a time. Skip the first line. Convert the two (expected) whitespace delimited tokens to float. Sum the values. Do a final calculation.

totalLitres = 0
totalCost = 0

with open('petrolPrice.txt') as pp:
    next(pp) # skip heading
    for line in pp:
        litres, cost = map(float, line.split())
        totalLitres  = litres
        totalCost  = cost
    print(f'Average cost per litre = {totalCost/totalLitres:.2f}')

Output:

Average cost per litre = 3.61
  • Related