Untitled
unknown
plain_text
a year ago
1.6 kB
13
Indexable
import csv
from collections import defaultdict
def generateFiles(input_file_name):
product_data = defaultdict(lambda: {'quantity_sum': 0, 'count': 0, 'brands': defaultdict(int)})
# Process the input file in one pass
with open(input_file_name, mode='r') as file:
reader = csv.reader(file)
for row in reader:
product = row[2]
quantity = int(row[3])
brand = row[4]
# Update quantity and count
product_data[product]['quantity_sum'] += quantity
product_data[product]['count'] += 1
# Update brand popularity count
product_data[product]['brands'][brand] += 1
# Write the first output file: 0_input_file_name.csv
output_file_0 = '0_' + input_file_name
with open(output_file_0, mode='w', newline='') as file:
writer = csv.writer(file)
for product, data in product_data.items():
avg_quantity = data['quantity_sum'] / data['count']
writer.writerow([product, f'{avg_quantity:.3f}'])
# Write the second output file: 1_input_file_name.csv
output_file_1 = '1_' + input_file_name
with open(output_file_1, mode='w', newline='') as file:
writer = csv.writer(file)
for product, data in product_data.items():
most_popular_brand = max(data['brands'], key=data['brands'].get)
writer.writerow([product, most_popular_brand])
# Example usage
if __name__ == '__main__':
input_file_name = input()
generateFiles(input_file_name)
Editor is loading...
Leave a Comment