<Below this line, add a link to the exact exercise that you are stuck at.>
<In what way does your code behave incorrectly? Include ALL error messages.>
Test case number: 1
Your function return is NOT correct but your printed output is correct.
For example when your function is called as shown below:
calculate_expenses(‘expenses_very_long.txt’)
Your function returns:
[(‘bread’, ‘$1.90’), (‘chips’, ‘$2.54’), (‘chocolate’, ‘$21.95’), (‘goods’, ‘$4.69’), (‘insurance’, ‘$415.00’), (‘loan’, ‘$195.00’), (‘milk’, ‘$2.35’)]
The returned variable type from your function is: list
Instructor’s function returns:
[(‘bread’, ‘$1.90’), (‘chips’, ‘$2.54’), (‘chocolate’, ‘$21.95’), (‘goods’, ‘$4.69’), (‘insurance’, ‘$220.00’), (‘loan’, ‘$390.00’), (‘milk’, ‘$2.35’)]
The returned variable type from instructor’s function is: list
<What do you expect to happen instead?>
I do not want the error.
Here is the actual question.
Write a function named calculate_expenses that receives a filename as argument. The file contains the information about a person’s expenses on items. Your function should return a list of tuples sorted based on the name of the items. Each tuple consists of the name of the item and total expense of that item as shown below:
milk,2.35
bread , 1.95
chips , 2.54
milk , 2.38
milk,2.31
bread, 1.90
Notice that each line of the file only includes an item and the purchase price of that item separated by a comma. There may be spaces before or after the item or the price. Then your function should read the file and return a list of tuples such as:
[(‘bread’, ‘$3.85’), (‘chips’, ‘$2.54’), (‘milk’, ’7.04')]
Notes:
Tuples are sorted based on the item names i.e. bread comes before chips which comes before milk.
The total expenses are strings which start with a and they have two digits of accuracy after the decimal point.
Hint: Use “${:.2f}” to properly create and format strings for the total expenses.
def calculate_expenses(filename):
# Make a connection to the file
file_pointer = open(filename, 'r')
data = file_pointer.readlines()
pata=[]
for line in data:
line=removes_spaces_gives_list(line)####comes from function at step 1 at the bottom
pata.append(line)
################################
l=len(pata)
outer_list=[]
i=0
while i<l:
j=i+1
total=float(pata[i][1])
while j<l:
if pata[i][0]==pata[j][0]:
total=total+float(pata[j][1])
pata.remove(pata[j])
l=len(pata)
j=j
else:
j=j+1
total='${0:.2f}'.format(total)
inner_tpl=(pata[i][0],total)
outer_list.append(inner_tpl)
i=i+1
list_sorted=sorted(outer_list)
return list_sorted
#################################
def removes_spaces_gives_list(dhago):
dhago=dhago.strip('\n')
sago=dhago.split(',')
sata=[]
for item in sago:
pitem=item.rstrip()
kitem=pitem.lstrip()
sata.append(kitem)
return sata
###############closes file##############
file_pointer.close()