Reputation: 11
Q: "Write a function named "internet_histogram" that takes no parameters and does not return a value. There will be a file named "survey.csv" in the testing environment containing survey results as described above (the file has a header line which much be addressed by your code). Write a new file named "histogram.csv" containing 2 columns representing "internet_use,frequency" and no header line that will contain a histogram of the results of responders ages 30 to 33 including the endpoint ages. Your file will have exactly 6 lines with internet_use values of 1-5 corresponding to the intfreq results and 6 for responders who answered 2 to eminuse. Read the survey results file and track how many responders in this age range answered with each of these 6 options and write these counts to your "histogram.csv" file in order of internet_use starting with 1.
Example histogram.csv
:
1,5
2,7
3,0
4,1
5,2
6,4
Here is my code for this:
def internet_histogram():
count_6 = 0
count_5 = 0
count_4 = 0
count_3 = 0
count_2 = 0
count_1 = 0
with open("survey.csv",'r') as f:
reader = csv.reader(f)
with open("histogram.csv", 'w') as g:
writer = csv.writer(g)
next(reader)
for line in reader:
if int(line[3]) >= 29 and int(line[3]) <= 53:
if line[2] != '':
if int(line[2]) == 1:
count_1 += 1
elif int(line[2]) == 2:
count_2 += 1
elif int(line[2]) == 3:
count_3 += 1
elif int(line[2]) == 4:
count_4 += 1
elif int(line[2]) == 5:
count_5 += 1
else:
count_6 += 1
arr = [[1, count_1], [2, count_2], [3, count_3], [4, count_4], [5, count_5], [6, count_6]]
for i in arr:
writer.writerow(i)
Here are my results vs. expected results when the code is ran:
**wrote**:
1,236
2,329
3,42
4,34
5,17
6,0
**expected**:
1,48
2,48
3,7
4,6
5,1
6,3
What is preventing this function from delivering the expected results? What changes could I make? Thank you in advance for your help:)
('survey.csv' file available in this dataset for reference, if needed: http://www.pewinternet.org/dataset/jan-3-10-2018-core-trends-survey/)
Upvotes: 0
Views: 307
Reputation: 11
def internet_histogram():
count_6 = 0
count_5 = 0
count_4 = 0
count_3 = 0
count_2 = 0
count_1 = 0
with open("survey.csv",'r') as f:
reader = csv.reader(f)
with open("histogram.csv", 'w') as g:
writer = csv.writer(g)
next(reader)
for line in reader:
if int(line[3]) >= 31 and int(line[3]) <= 47:
if int(line[0]) == 2:
count_6 +=1
if line[2] != '':
if int(line[2]) == 1:
count_1 += 1
elif int(line[2]) == 2:
count_2 += 1
elif int(line[2]) == 3:
count_3 += 1
elif int(line[2]) == 4:
count_4 += 1
elif int(line[2]) == 5:
count_5 += 1
arr = [[1, count_1], [2, count_2], [3, count_3], [4, count_4], [5, count_5], [6, count_6]]
for i in arr:
writer.writerow(i)
your code should look like this, your age range was wrong and the count_6 was calculated inncorrectly.
Upvotes: 1