Python: Problem solving with lists, strings, and files Write a program that read
ID: 3602914 • Letter: P
Question
Python: Problem solving with lists, strings, and files Write a program that reads a csv data file called csv sales that contains sales of land in various parts of the UK for years of 2012-2014. The file consists of 4 columns: the area and the 3 years of sales numbers. It will calculate the following stats (printing to screen optional): Areas with average sales across the three years in the ranges 0-3000, 3001-5000, 5001. It should generate a CSV file (columns separated by commas, rows separated by newlines Note that the rows do not have to be in any particular order. It should create a table similar to the following (table incomplete): 0-3000 City of London Barking and Dagenham 001-5000 Barnet Crovden >-5001 Bromley WandsworthExplanation / Answer
import csv
import copy
def average_sales(input_csv_file):
"""takes input_csv_file as input which is path to file"""
area_average = {}
output_data = {'0-3000' : [], '3001-5000' : [], '>=5001' : []}
data_list = []
with open('csv_sales.csv', 'rb') as csvfile:
data = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in data:
row_data = row[0].split(',')
if row_data[0] == '':
break
data_list.append(row[0].split(','))
for row in data_list[1:]:
area_average[row[0]] = int((int(row[1]) + int(row[2]) + int(row[3]))/3)
for key in area_average.keys():
if area_average[key] <= 3000:
output_data['0-3000'].append(key)
elif area_average[key] > 3000 and area_average[key] <= 5000:
output_data['3001-5000'].append(key)
elif area_average[key] > 5000:
output_data['>=5001'].append(key)
max_length = 0
for key in output_data:
if len(output_data[key]) > max_length:
max_length = len(output_data[key])
lis = []
for i in range(max_length):
lis_temp = []
try:
lis_temp.append(output_data['0-3000'][i])
except:
lis_temp.append('')
try:
lis_temp.append(output_data['3001-5000'][i])
except:
lis_temp.append('')
try:
lis_temp.append(output_data['>=5001'][i])
except:
lis_temp.append('')
lis.append(copy.copy(lis_temp))
with open('average_ouput_sales.csv', 'wb') as csvfile:
writer = csv.writer(csvfile, delimiter=',',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
writer.writerow(['0-3000','3001-5000','>=5001'])
for val in lis:
writer.writerow(val)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.