From daa100633298f527e73bccb126448c03b29aa5bf Mon Sep 17 00:00:00 2001 From: Mahyar Fardinfar Date: Fri, 18 Aug 2023 11:20:02 +0330 Subject: [PATCH] making it more efficient Reading file inside for loop is something costly!!!! --- Solutions/1_27/pcost.py | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/Solutions/1_27/pcost.py b/Solutions/1_27/pcost.py index 8386d53f3..067f78ffa 100644 --- a/Solutions/1_27/pcost.py +++ b/Solutions/1_27/pcost.py @@ -1,13 +1,9 @@ # pcost.py -total_cost = 0.0 - -with open('../../Work/Data/portfolio.csv', 'rt') as f: - headers = next(f) - for line in f: - row = line.split(',') - nshares = int(row[1]) - price = float(row[2]) - total_cost += nshares * price - -print('Total cost', total_cost) +total_cost = 0 +f = open("../../Work/Data/portfolio.csv", 'rt') # reading file line by line +all_data = f.readlines() # reading all of the lines +for data in all_data: + data = data.split(",") # splitting csv fomat + total_cost = int(data[1]) * float(data[2]) # doing the arithmetic (you don't neet it to be int use float instead!!) +print(f"Total_cos: {t}")